Merge "BUG 1082 Migrate sal-rest-connector to Async Data Broker API"
authorTony Tkacik <ttkacik@cisco.com>
Sun, 3 Aug 2014 18:10:03 +0000 (18:10 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Sun, 3 Aug 2014 18:10:03 +0000 (18:10 +0000)
179 files changed:
.gitignore
features/config-netty/src/main/resources/features.xml
features/nsf/src/main/resources/features.xml
itests/base-features-it/pom.xml [new file with mode: 0644]
itests/base-features-it/src/test/java/org/opendaylight/controller/base/BaseFeatureTest.java [new file with mode: 0644]
itests/pom.xml [new file with mode: 0644]
opendaylight/commons/opendaylight/pom.xml
opendaylight/commons/protocol-framework/pom.xml
opendaylight/commons/protocol-framework/src/main/java/org/opendaylight/protocol/framework/AbstractDispatcher.java
opendaylight/commons/protocol-framework/src/main/java/org/opendaylight/protocol/framework/ProtocolSessionPromise.java
opendaylight/commons/protocol-framework/src/main/java/org/opendaylight/protocol/framework/ReconnectPromise.java
opendaylight/commons/protocol-framework/src/main/java/org/opendaylight/protocol/framework/SessionListener.java
opendaylight/commons/protocol-framework/src/test/java/org/opendaylight/protocol/framework/ServerTest.java
opendaylight/commons/protocol-framework/src/test/java/org/opendaylight/protocol/framework/SimpleDispatcher.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/osgi/mapping/CodecRegistryProvider.java
opendaylight/config/config-netty-config/pom.xml [new file with mode: 0644]
opendaylight/config/config-netty-config/src/main/resources/initial/00-netty.xml [moved from opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/00-netty.xml with 100% similarity]
opendaylight/config/pom.xml
opendaylight/distribution/opendaylight/pom.xml
opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IHostTrackerShell.java [new file with mode: 0644]
opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/Activator.java
opendaylight/hosttracker/implementation/src/main/java/org/opendaylight/controller/hosttracker/internal/HostTracker.java
opendaylight/hosttracker/shell/pom.xml [new file with mode: 0644]
opendaylight/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpFailedARPReqList.java [new file with mode: 0644]
opendaylight/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpPendingARPReqList.java [new file with mode: 0644]
opendaylight/hosttracker/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml [new file with mode: 0644]
opendaylight/hosttracker/shell/src/test/java/org/opendaylight/controller/hosttracker/shell/HostTrackerShellTest.java [new file with mode: 0644]
opendaylight/md-sal/md-sal-config/pom.xml [new file with mode: 0644]
opendaylight/md-sal/md-sal-config/src/main/resources/initial/01-md-sal.xml [moved from opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/01-md-sal.xml with 100% similarity]
opendaylight/md-sal/pom.xml
opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/ExampleActor.java
opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/ExampleConfigParamsImpl.java [new file with mode: 0644]
opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/Main.java
opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/example/TestDriver.java
opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/AbstractReplicatedLogImpl.java [new file with mode: 0644]
opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/ConfigParams.java [new file with mode: 0644]
opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/DefaultConfigParamsImpl.java [new file with mode: 0644]
opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActor.java
opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActorContext.java
opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/RaftActorContextImpl.java
opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/AbstractRaftActorBehavior.java
opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/Follower.java
opendaylight/md-sal/sal-akka-raft/src/main/java/org/opendaylight/controller/cluster/raft/behaviors/Leader.java
opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/AbstractReplicatedLogImplTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-akka-raft/src/test/java/org/opendaylight/controller/cluster/raft/MockRaftActorContext.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/RuntimeMappingModule.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractForwardedDataBroker.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/MountPointManagerImpl.java
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/test/Bug1333DataChangeListenerTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/test/DataBrokerTestCustomizer.java
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/util/BindingTestContext.java
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/util/MockSchemaService.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreFactory.java
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/CarsModel.java
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/PeopleModel.java
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/md/cluster/datastore/model/SampleModelsTest.java
opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/sal/core/api/model/SchemaService.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomBrokerImplModule.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/DomInmemoryDataBrokerModule.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/dom/impl/SchemaServiceImplSingletonModule.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/compat/BackwardsCompatibleDataBroker.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/BackwardsCompatibleMountPoint.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/GlobalBundleScanningSchemaServiceImpl.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/osgi/SchemaServiceProxy.java
opendaylight/md-sal/sal-dom-xsql/src/main/java/org/opendaylight/yang/gen/v1/http/netconfcentral/org/ns/xsql/rev140626/XSQLModule.java
opendaylight/md-sal/sal-inmemory-datastore/src/main/java/org/opendaylight/controller/config/yang/inmemory_datastore_provider/InMemoryConfigDataStoreProviderModule.java
opendaylight/md-sal/sal-inmemory-datastore/src/main/java/org/opendaylight/controller/config/yang/inmemory_datastore_provider/InMemoryOperationalDataStoreProviderModule.java
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/config/yang/md/sal/connector/netconf/NetconfConnectorModule.java
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/NetconfDevice.java
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/listener/NetconfDeviceCommunicator.java
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/listener/NetconfSessionCapabilities.java
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceDataBroker.java
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/tx/NetconfDeviceReadOnlyTx.java
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/tx/NetconfDeviceWriteOnlyTx.java
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/util/NetconfMessageTransformUtil.java
opendaylight/md-sal/sal-netconf-connector/src/main/yang/odl-sal-netconf-connector-cfg.yang
opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/listener/NetconfDeviceCommunicatorTest.java
opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/listener/NetconfSessionCapabilitiesTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/sal/tx/NetconfDeviceWriteOnlyTxTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/README-FIRST
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/NodeToNormalizedNodeBuilder.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/NodeValueCodec.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodec.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToProtocolBufferNode.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/AugmentationIdentifierGenerator.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactory.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierGenerator.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierWithPredicatesGenerator.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierWithValueGenerator.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeGetter.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeNavigator.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodePrinter.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/NormalizedNodeVisitor.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/PathUtils.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/node/utils/QNameFactory.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/util/EncoderDecoderUtil.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtils.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/mdsal/CompositeModificationPayload.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/cohort3pc/ThreePhaseCommitCohortMessages.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/common/NormalizedNodeMessages.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/common/SimpleNormalizedNodeMessage.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/datachange/notification/DataChangeListenerMessages.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/persistent/PersistentMessages.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/registration/ListenerRegistrationMessages.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/shard/ShardManagerMessages.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionChainMessages.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionMessages.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/node/NormalizedNodeToNodeCodecTest.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/node/utils/NodeIdentifierFactoryTest.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/util/InstanceIdentifierUtilsTest.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/util/NormalizedNodeXmlConverterTest.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/util/TestModel.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/AbstractMessagesTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/ShardManagerMessagesTest.java [deleted file]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/cohort3pc/ThreePhaseCommitCohortMessagesTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/common/NormalizedNodeMessagesTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/datachange/notification/DataChangeListenerMessagesTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/persistent/PersistentMessagesTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/registration/ListenerRegistrationMessagesTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/shard/ShardManagerMessagesTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionChainMessagesTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionMessagesTest.java
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/augment_choice.xml
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/simple_xml_with_attributes.xml
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/DataChangeListenerMessagesData [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ListenerRegistrationMessagesData [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/NormalizedNodeMessagesTestData [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/PersistentMessagesTestData [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ShardManagerMessagesTestData [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ShardTransactionChainMessagesTestData [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ShardTransactionMessagesTestData [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ThreePhaseCommitCohortMessagesTestData [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/readme.txt [new file with mode: 0644]
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/ActorConstants.java [new file with mode: 0644]
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/RemoteRpcProvider.java
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/RpcManager.java
opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/registry/RpcRegistry.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfProviderImpl.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/ControllerContext.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/Notificator.java
opendaylight/md-sal/samples/pom.xml
opendaylight/md-sal/samples/toaster-config/pom.xml [new file with mode: 0644]
opendaylight/md-sal/samples/toaster-config/src/main/resources/initial/03-toaster-sample.xml [moved from opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/03-toaster-sample.xml with 99% similarity]
opendaylight/netconf/netconf-config/pom.xml [new file with mode: 0644]
opendaylight/netconf/netconf-config/src/main/resources/initial/01-netconf.xml [moved from opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/01-netconf.xml with 100% similarity]
opendaylight/netconf/netconf-connector-config/pom.xml [new file with mode: 0644]
opendaylight/netconf/netconf-connector-config/src/main/resources/initial/99-netconf-connector.xml [moved from opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/99-netconf-connector.xml with 100% similarity]
opendaylight/netconf/pom.xml
opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/Activator.java
opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/NeutronFirewallInterface.java [new file with mode: 0644]
opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/NeutronFirewallPolicyInterface.java [new file with mode: 0644]
opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/NeutronFirewallRuleInterface.java [new file with mode: 0644]
opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallAware.java [new file with mode: 0644]
opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallCRUD.java [new file with mode: 0644]
opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallPolicyAware.java [new file with mode: 0644]
opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallPolicyCRUD.java [new file with mode: 0644]
opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallRuleAware.java [new file with mode: 0644]
opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallRuleCRUD.java [new file with mode: 0644]
opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronCRUDInterfaces.java
opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronFirewall.java [new file with mode: 0644]
opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronFirewallPolicy.java [new file with mode: 0644]
opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronFirewallRule.java [new file with mode: 0644]
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallNorthbound.java [new file with mode: 0644]
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyNorthbound.java [new file with mode: 0644]
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyRequest.java [new file with mode: 0644]
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRequest.java [new file with mode: 0644]
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRuleRequest.java [new file with mode: 0644]
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRulesNorthbound.java [new file with mode: 0644]
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNorthboundRSApplication.java
opendaylight/topologymanager/implementation/pom.xml
opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerShell.java [new file with mode: 0644]
opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/Activator.java
opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/internal/TopologyManagerImpl.java
opendaylight/topologymanager/shell/pom.xml [new file with mode: 0644]
opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/AddUserLink.java [new file with mode: 0644]
opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/DeleteUserLink.java [new file with mode: 0644]
opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintNodeEdges.java [new file with mode: 0644]
opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintUserLink.java [new file with mode: 0644]
opendaylight/topologymanager/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml [new file with mode: 0644]

index f8cf74f8263758e9cf39e2a4dbbf30d6c904628e..9144cda4cc6b40ede292b02156e21f99d136e13b 100644 (file)
@@ -27,3 +27,5 @@ out/
 maven-eclipse.xml
 .DS_STORE
 .metadata
+opendaylight/md-sal/sal-distributed-datastore/journal
+
index 3121ca01a2aa322a69c36d3994857df3e6507112..f1b2d1f753f66cf83dd03ddca24cb6155fe7ab33 100644 (file)
@@ -12,5 +12,6 @@
     <bundle>mvn:org.opendaylight.controller/threadpool-config-api/${project.version}</bundle>
     <bundle>mvn:org.opendaylight.controller/threadpool-config-impl/${project.version}</bundle>
     <feature version='${project.version}'>odl-config-startup</feature>
+    <configfile finalname="configuration/initial/00-netty.xml">mvn:org.opendaylight.controller/config-netty-config/${config.version}/xml/config</configfile>
   </feature>
 </features>
\ No newline at end of file
index fb61f33fb32a58b82ff261a5c84a16cef3b274c4..130d72e01ae588780ccaa8d7840be0727874e2da 100644 (file)
         <bundle>mvn:org.opendaylight.controller/forwardingrulesmanager.implementation/${forwardingrulesmanager.implementation.version}</bundle>
 
         <bundle>mvn:org.opendaylight.controller/topologymanager/${topologymanager.version}</bundle>
+        <bundle>mvn:org.opendaylight.controller/topologymanager.shell/${topologymanager.shell.version}</bundle>
 
         <bundle>mvn:org.opendaylight.controller/networkconfig.neutron/${networkconfig.neutron.version}</bundle>
         <bundle>mvn:org.opendaylight.controller/networkconfig.neutron.implementation/${networkconfig.neutron.implementation.version}</bundle>
 
         <bundle>mvn:org.opendaylight.controller/hosttracker/${hosttracker.api.version}</bundle>
         <bundle>mvn:org.opendaylight.controller/hosttracker.implementation/${hosttracker.implementation.version}</bundle>
+        <bundle>mvn:org.opendaylight.controller/hosttracker.shell/${hosttracker.shell.version}</bundle>
 
         <bundle>mvn:org.opendaylight.controller/forwarding.staticrouting</bundle>
 
@@ -70,4 +72,4 @@
         <bundle>mvn:org.opendaylight.controller/topology.northbound/${topology.northbound.version}</bundle>
         <bundle>mvn:org.opendaylight.controller/usermanager.northbound/${usermanager.northbound.version}</bundle>
     </feature>
-</features>
\ No newline at end of file
+</features>
diff --git a/itests/base-features-it/pom.xml b/itests/base-features-it/pom.xml
new file mode 100644 (file)
index 0000000..8f73779
--- /dev/null
@@ -0,0 +1,90 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <groupId>org.opendaylight.controller</groupId>
+        <artifactId>itests-controller</artifactId>
+        <version>1.4.2-SNAPSHOT</version>
+        <relativePath>../pom.xml</relativePath>
+    </parent>
+    <artifactId>base-features-it</artifactId>
+    <name>base-features-it</name>
+    <packaging>jar</packaging>
+    <dependencies>
+        <dependency>
+            <groupId>org.opendaylight.controller</groupId>
+            <artifactId>base-features</artifactId>
+            <version>${project.version}</version>
+            <classifier>features</classifier>
+            <type>xml</type>
+        </dependency>
+        <dependency>
+            <groupId>org.slf4j</groupId>
+            <artifactId>slf4j-api</artifactId>
+        </dependency>
+        <!-- Dependencies for pax exam karaf container -->
+        <dependency>
+            <groupId>org.ops4j.pax.exam</groupId>
+            <artifactId>pax-exam-container-karaf</artifactId>
+            <version>${pax.exam.version}</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.ops4j.pax.exam</groupId>
+            <artifactId>pax-exam-junit4</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.ops4j.pax.exam</groupId>
+            <artifactId>pax-exam</artifactId>
+            <version>${pax.exam.version}</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.ops4j.pax.url</groupId>
+            <artifactId>pax-url-aether</artifactId>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>javax.inject</groupId>
+            <artifactId>javax.inject</artifactId>
+            <version>1</version>
+            <scope>test</scope>
+        </dependency>
+         <dependency>
+            <groupId>org.apache.karaf.features</groupId>
+            <artifactId>org.apache.karaf.features.core</artifactId>
+            <version>${karaf.version}</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+           <groupId>org.osgi</groupId>
+           <artifactId>org.osgi.core</artifactId>
+           <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>junit</groupId>
+            <artifactId>junit</artifactId>
+            <scope>test</scope>
+        </dependency>
+
+    </dependencies>
+
+    <build>
+        <plugins>
+            <!-- Needed if you use versionAsInProject() -->
+            <!--    <plugin>
+                <groupId>org.apache.servicemix.tooling</groupId>
+                <artifactId>depends-maven-plugin</artifactId>
+                <version>1.2</version>
+                <executions>
+                    <execution>
+                        <id>generate-depends-file</id>
+                        <goals>
+                            <goal>generate-depends-file</goal>
+                        </goals>
+                    </execution>
+                </executions>
+            </plugin> -->
+        </plugins>
+    </build>
+</project>
diff --git a/itests/base-features-it/src/test/java/org/opendaylight/controller/base/BaseFeatureTest.java b/itests/base-features-it/src/test/java/org/opendaylight/controller/base/BaseFeatureTest.java
new file mode 100644 (file)
index 0000000..0d38940
--- /dev/null
@@ -0,0 +1,74 @@
+package org.opendaylight.controller.base;
+
+import static org.ops4j.pax.exam.CoreOptions.maven;
+import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.configureConsole;
+import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.karafDistributionConfiguration;
+import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.keepRuntimeFolder;
+import static org.ops4j.pax.exam.karaf.options.KarafDistributionOption.logLevel;
+
+import java.io.File;
+import java.net.URI;
+import java.util.EnumSet;
+
+import javax.inject.Inject;
+
+import junit.framework.Assert;
+
+import org.apache.karaf.features.Feature;
+import org.apache.karaf.features.FeaturesService;
+import org.apache.karaf.features.Repository;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.ops4j.pax.exam.Configuration;
+import org.ops4j.pax.exam.Option;
+import org.ops4j.pax.exam.junit.PaxExam;
+import org.ops4j.pax.exam.karaf.options.LogLevelOption.LogLevel;
+
+
+@RunWith(PaxExam.class)
+public class BaseFeatureTest {
+   @Inject
+   private FeaturesService featuresService;
+    @Configuration
+    public Option[] config() {
+       return new Option[] {
+             // Provision and launch a container based on a distribution of Karaf (Apache ServiceMix).
+             karafDistributionConfiguration()
+                 .frameworkUrl(
+                          maven()
+                                  .groupId("org.opendaylight.controller")
+                                  .artifactId("distribution.opendaylight-karaf")
+                                  .type("tar.gz")
+                                  .version("1.4.2-SNAPSHOT"))
+                 .name("OpenDaylight")
+                 .unpackDirectory(new File("target/pax"))
+                 .useDeployFolder(false),
+             // It is really nice if the container sticks around after the test so you can check the contents
+             // of the data directory when things go wrong.
+             keepRuntimeFolder(),
+             // Don't bother with local console output as it just ends up cluttering the logs
+             configureConsole().ignoreLocalConsole(),
+             // Force the log level to INFO so we have more details during the test.  It defaults to WARN.
+             logLevel(LogLevel.WARN),
+             // Remember that the test executes in another process.  If you want to debug it, you need
+             // to tell Pax Exam to launch that process with debugging enabled.  Launching the test class itself with
+             // debugging enabled (for example in Eclipse) will not get you the desired results.
+             //debugConfiguration("5000", true),
+       };
+    }
+
+    @Test
+    public void testAllFeatures() throws Exception {
+       featuresService.addRepository(new URI("mvn:org.opendaylight.controller/base-features/1.4.2-SNAPSHOT/xml/features"));
+       Repository repoUnderTest = featuresService.getRepository("base-1.4.2-SNAPSHOT");
+       Assert.assertNotNull(repoUnderTest);
+       Feature[] featuresUnderTest = repoUnderTest.getFeatures();
+       for(int i=0; i< featuresUnderTest.length; i++)
+       {
+          Feature feature = featuresUnderTest[i];
+          featuresService.installFeature(feature,EnumSet.of(FeaturesService.Option.Verbose));
+          System.out.println("Testing Feature:"+feature.getName());
+          Assert.assertTrue(featuresService.isInstalled(feature));
+       }
+    }
+}
\ No newline at end of file
diff --git a/itests/pom.xml b/itests/pom.xml
new file mode 100644 (file)
index 0000000..19836a2
--- /dev/null
@@ -0,0 +1,18 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+  <parent>
+    <groupId>org.opendaylight.controller</groupId>
+    <artifactId>commons.opendaylight</artifactId>
+    <version>1.4.2-SNAPSHOT</version>
+    <relativePath>../opendaylight/commons/opendaylight</relativePath>
+  </parent>
+  <artifactId>itests-controller</artifactId>
+  <packaging>pom</packaging>
+  <prerequisites>
+    <maven>3.0</maven>
+  </prerequisites>
+  <modules>
+    <module>base-features-it</module>
+  </modules>
+</project>
index 9468133db820c05d29dc299de9d80e3f96c209ab..5ce5840da8fc4deb45df33c1d2fc102933c2fe7e 100644 (file)
@@ -95,6 +95,7 @@
     <hosttracker.api.version>0.5.2-SNAPSHOT</hosttracker.api.version>
     <hosttracker.implementation.version>0.5.2-SNAPSHOT</hosttracker.implementation.version>
     <hosttracker.northbound.version>0.4.2-SNAPSHOT</hosttracker.northbound.version>
+    <hosttracker.shell.version>1.0.0-SNAPSHOT</hosttracker.shell.version>
     <hosttracker_new.api.version>0.4.2-SNAPSHOT</hosttracker_new.api.version>
     <hosttracker_new.implementation.version>0.4.2-SNAPSHOT</hosttracker_new.implementation.version>
     <httpservice-bridge.northbound.version>0.0.2-SNAPSHOT</httpservice-bridge.northbound.version>
     <northbound.jolokia.version>1.4.2-SNAPSHOT</northbound.jolokia.version>
     <opendaylight-l2-types.version>2013.08.27.4-SNAPSHOT</opendaylight-l2-types.version>
     <osgi-brandfragment.web.version>0.0.2-SNAPSHOT</osgi-brandfragment.web.version>
+    <pax.exam.version>4.0.0</pax.exam.version>
     <parboiled.version>1.1.6</parboiled.version>
     <parboiled.scala.version>1.1.6</parboiled.scala.version>
     <propertymavenplugin.version>1.0-alpha-2</propertymavenplugin.version>
     <topology.northbound.version>0.4.2-SNAPSHOT</topology.northbound.version>
     <topology.web.version>0.4.2-SNAPSHOT</topology.web.version>
     <topologymanager.version>0.4.2-SNAPSHOT</topologymanager.version>
+    <topologymanager.shell.version>1.0.0-SNAPSHOT</topologymanager.shell.version>
     <troubleshoot.web.version>0.4.2-SNAPSHOT</troubleshoot.web.version>
     <typesafe.config.version>1.2.0</typesafe.config.version>
     <uncommons.maths.version>1.2.2</uncommons.maths.version>
         <artifactId>sal-rest-connector-config</artifactId>
         <version>${mdsal.version}</version>
       </dependency>
+      <dependency>
+        <groupId>org.opendaylight.controller</groupId>
+        <artifactId>config-netty-config</artifactId>
+        <version>${config.version}</version>
+      </dependency>
+      <dependency>
+        <groupId>org.opendaylight.controller</groupId>
+        <artifactId>md-sal-config</artifactId>
+        <version>${mdsal.version}</version>
+      </dependency>
+      <dependency>
+        <groupId>org.opendaylight.controller</groupId>
+        <artifactId>netconf-config</artifactId>
+        <version>${netconf.version}</version>
+      </dependency>
+      <dependency>
+        <groupId>org.opendaylight.controller</groupId>
+        <artifactId>netconf-connector-config</artifactId>
+        <version>${netconf.version}</version>
+      </dependency>
       <dependency>
         <groupId>org.opendaylight.controller</groupId>
         <artifactId>sal-rest-docgen</artifactId>
         <artifactId>sample-toaster-provider</artifactId>
         <version>${mdsal.version}</version>
       </dependency>
+      <dependency>
+        <groupId>org.opendaylight.controller.samples</groupId>
+        <artifactId>toaster-config</artifactId>
+        <version>${mdsal.version}</version>
+      </dependency>
       <dependency>
         <groupId>org.opendaylight.controller.thirdparty</groupId>
         <artifactId>com.sun.jersey.jersey-servlet</artifactId>
index f70698731aa0aea9e1cc6f1cff86d4ded144b454..774bc7c23f178b30f26b94d65212a595d5941b4a 100644 (file)
       <artifactId>netty-event-executor-config</artifactId>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>ch.qos.logback</groupId>
+      <artifactId>logback-classic</artifactId>
+      <scope>test</scope>
+    </dependency>
   </dependencies>
 
   <build>
index a62bd7da06501b355c41f36230dbf30a982d61fa..a05d02cd09ad4e1b447a61da687768bc58e3dd94 100644 (file)
@@ -7,12 +7,19 @@
  */
 package org.opendaylight.protocol.framework;
 
+import java.io.Closeable;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import com.google.common.base.Preconditions;
 
 import io.netty.bootstrap.Bootstrap;
 import io.netty.bootstrap.ServerBootstrap;
-import io.netty.channel.Channel;
 import io.netty.buffer.PooledByteBufAllocator;
+import io.netty.channel.Channel;
 import io.netty.channel.ChannelFuture;
 import io.netty.channel.ChannelInitializer;
 import io.netty.channel.ChannelOption;
@@ -28,13 +35,6 @@ import io.netty.util.concurrent.Future;
 import io.netty.util.concurrent.GlobalEventExecutor;
 import io.netty.util.concurrent.Promise;
 
-import java.io.Closeable;
-import java.net.InetSocketAddress;
-import java.net.SocketAddress;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
 /**
  * Dispatcher class for creating servers and clients. The idea is to first create servers and clients and the run the
  * start method that will handle sockets in different thread.
@@ -155,7 +155,7 @@ public abstract class AbstractDispatcher<S extends ProtocolSession<?>, L extends
      */
     protected Future<S> createClient(final InetSocketAddress address, final ReconnectStrategy strategy, final PipelineInitializer<S> initializer) {
         final Bootstrap b = new Bootstrap();
-        final ProtocolSessionPromise<S> p = new ProtocolSessionPromise<S>(executor, address, strategy, b);
+        final ProtocolSessionPromise<S> p = new ProtocolSessionPromise<>(executor, address, strategy, b);
         b.option(ChannelOption.SO_KEEPALIVE, true).handler(
                 new ChannelInitializer<SocketChannel>() {
                     @Override
@@ -165,18 +165,36 @@ public abstract class AbstractDispatcher<S extends ProtocolSession<?>, L extends
                 });
 
         customizeBootstrap(b);
+        setWorkerGroup(b);
+        setChannelFactory(b);
+
+        p.connect();
+        LOG.debug("Client created.");
+        return p;
+    }
 
+    private void setWorkerGroup(final Bootstrap b) {
         if (b.group() == null) {
             b.group(workerGroup);
         }
+    }
 
-        // There is no way to detect if this was already set by
-        // customizeBootstrap()
-        try {
-            b.channel(NioSocketChannel.class);
-        } catch (IllegalStateException e) {
-            LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
-        }
+    /**
+     * Create a client but use a pre-configured bootstrap.
+     * This method however replaces the ChannelInitializer in the bootstrap. All other configuration is preserved.
+     *
+     * @param address remote address
+     */
+    protected Future<S> createClient(final InetSocketAddress address, final ReconnectStrategy strategy, final Bootstrap bootstrap, final PipelineInitializer<S> initializer) {
+        final ProtocolSessionPromise<S> p = new ProtocolSessionPromise<>(executor, address, strategy, bootstrap);
+
+        bootstrap.handler(
+                new ChannelInitializer<SocketChannel>() {
+                    @Override
+                    protected void initChannel(final SocketChannel ch) {
+                        initializer.initializeChannel(ch, p);
+                    }
+                });
 
         p.connect();
         LOG.debug("Client created.");
@@ -195,6 +213,9 @@ public abstract class AbstractDispatcher<S extends ProtocolSession<?>, L extends
     }
 
     /**
+     *
+     * @deprecated use {@link org.opendaylight.protocol.framework.AbstractDispatcher#createReconnectingClient(java.net.InetSocketAddress, ReconnectStrategyFactory, org.opendaylight.protocol.framework.AbstractDispatcher.PipelineInitializer)} with only one reconnectStrategyFactory instead.
+     *
      * Creates a client.
      *
      * @param address remote address
@@ -204,15 +225,47 @@ public abstract class AbstractDispatcher<S extends ProtocolSession<?>, L extends
      * @return Future representing the reconnection task. It will report completion based on reestablishStrategy, e.g.
      *         success if it indicates no further attempts should be made and failure if it reports an error
      */
+    @Deprecated
     protected Future<Void> createReconnectingClient(final InetSocketAddress address, final ReconnectStrategyFactory connectStrategyFactory,
             final ReconnectStrategy reestablishStrategy, final PipelineInitializer<S> initializer) {
+        return createReconnectingClient(address, connectStrategyFactory, initializer);
+    }
 
-        final ReconnectPromise<S, L> p = new ReconnectPromise<S, L>(GlobalEventExecutor.INSTANCE, this, address, connectStrategyFactory, reestablishStrategy, initializer);
-        p.connect();
+    /**
+     * Creates a reconnecting client.
+     *
+     * @param address remote address
+     * @param connectStrategyFactory Factory for creating reconnection strategy for every reconnect attempt
+     *
+     * @return Future representing the reconnection task. It will report completion based on reestablishStrategy, e.g.
+     *         success if it indicates no further attempts should be made and failure if it reports an error
+     */
+    protected Future<Void> createReconnectingClient(final InetSocketAddress address, final ReconnectStrategyFactory connectStrategyFactory,
+            final PipelineInitializer<S> initializer) {
+        final Bootstrap b = new Bootstrap();
+
+        final ReconnectPromise<S, L> p = new ReconnectPromise<>(GlobalEventExecutor.INSTANCE, this, address, connectStrategyFactory, b, initializer);
+
+        b.option(ChannelOption.SO_KEEPALIVE, true);
 
+        customizeBootstrap(b);
+        setWorkerGroup(b);
+        setChannelFactory(b);
+
+        p.connect();
         return p;
     }
 
+    private void setChannelFactory(final Bootstrap b) {
+        // There is no way to detect if this was already set by
+        // customizeBootstrap()
+        try {
+            b.channel(NioSocketChannel.class);
+        } catch (final IllegalStateException e) {
+            LOG.trace("Not overriding channelFactory on bootstrap {}", b, e);
+        }
+    }
+
     /**
      * @deprecated Should only be used with {@link AbstractDispatcher#AbstractDispatcher()}
      */
@@ -225,5 +278,4 @@ public abstract class AbstractDispatcher<S extends ProtocolSession<?>, L extends
             this.bossGroup.shutdownGracefully();
         }
     }
-
 }
index a78274cca0ca4f49e3c14ce69e6e6815b7a7e395..a38db61eaddcdb4ebd2daa79f03790fc6bde2007 100644 (file)
@@ -7,6 +7,7 @@
  */
 package org.opendaylight.protocol.framework;
 
+import com.google.common.base.Preconditions;
 import io.netty.bootstrap.Bootstrap;
 import io.netty.channel.ChannelFuture;
 import io.netty.channel.ChannelFutureListener;
@@ -16,17 +17,12 @@ import io.netty.util.concurrent.EventExecutor;
 import io.netty.util.concurrent.Future;
 import io.netty.util.concurrent.FutureListener;
 import io.netty.util.concurrent.Promise;
-
 import java.net.InetSocketAddress;
-
 import javax.annotation.concurrent.GuardedBy;
 import javax.annotation.concurrent.ThreadSafe;
-
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Preconditions;
-
 @ThreadSafe
 final class ProtocolSessionPromise<S extends ProtocolSession<?>> extends DefaultPromise<S> {
     private static final Logger LOG = LoggerFactory.getLogger(ProtocolSessionPromise.class);
@@ -54,72 +50,12 @@ final class ProtocolSessionPromise<S extends ProtocolSession<?>> extends Default
             LOG.debug("Promise {} attempting connect for {}ms", lock, timeout);
 
             this.b.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, timeout);
-            this.pending = this.b.connect(this.address).addListener(new ChannelFutureListener() {
-                @Override
-                public void operationComplete(final ChannelFuture cf) throws Exception {
-                    synchronized (lock) {
-
-                        LOG.debug("Promise {} connection resolved", lock);
-
-                        // Triggered when a connection attempt is resolved.
-                        Preconditions.checkState(ProtocolSessionPromise.this.pending.equals(cf));
-
-                        /*
-                         * The promise we gave out could have been cancelled,
-                         * which cascades to the connect getting cancelled,
-                         * but there is a slight race window, where the connect
-                         * is already resolved, but the listener has not yet
-                         * been notified -- cancellation at that point won't
-                         * stop the notification arriving, so we have to close
-                         * the race here.
-                         */
-                        if (isCancelled()) {
-                            if (cf.isSuccess()) {
-                                LOG.debug("Closing channel for cancelled promise {}", lock);
-                                cf.channel().close();
-                            }
-                            return;
-                        }
-
-                        if (!cf.isSuccess()) {
-                            LOG.debug("Attempt to connect to {} failed", ProtocolSessionPromise.this.address, cf.cause());
-
-                            final Future<Void> rf = ProtocolSessionPromise.this.strategy.scheduleReconnect(cf.cause());
-                            rf.addListener(new FutureListener<Void>() {
-                                @Override
-                                public void operationComplete(final Future<Void> sf) {
-                                    synchronized (lock) {
-                                        // Triggered when a connection attempt is to be made.
-                                        Preconditions.checkState(ProtocolSessionPromise.this.pending.equals(sf));
-
-                                        /*
-                                         * The promise we gave out could have been cancelled,
-                                         * which cascades to the reconnect attempt getting
-                                         * cancelled, but there is a slight race window, where
-                                         * the reconnect attempt is already enqueued, but the
-                                         * listener has not yet been notified -- if cancellation
-                                         * happens at that point, we need to catch it here.
-                                         */
-                                        if (!isCancelled()) {
-                                            if (sf.isSuccess()) {
-                                                connect();
-                                            } else {
-                                                setFailure(sf.cause());
-                                            }
-                                        }
-                                    }
-                                }
-                            });
-
-                            ProtocolSessionPromise.this.pending = rf;
-                        } else {
-                            LOG.debug("Promise {} connection successful", lock);
-                        }
-                    }
-                }
-            });
+            final ChannelFuture connectFuture = this.b.connect(this.address);
+            // Add listener that attempts reconnect by invoking this method again.
+            connectFuture.addListener(new BootstrapConnectListener(lock));
+            this.pending = connectFuture;
         } catch (final Exception e) {
-            LOG.info("Failed to connect to {}", e);
+            LOG.info("Failed to connect to {}", address, e);
             setFailure(e);
         }
     }
@@ -140,4 +76,79 @@ final class ProtocolSessionPromise<S extends ProtocolSession<?>> extends Default
         this.strategy.reconnectSuccessful();
         return super.setSuccess(result);
     }
+
+    private class BootstrapConnectListener implements ChannelFutureListener {
+        private final Object lock;
+
+        public BootstrapConnectListener(final Object lock) {
+            this.lock = lock;
+        }
+
+        @Override
+        public void operationComplete(final ChannelFuture cf) throws Exception {
+            synchronized (lock) {
+
+                LOG.debug("Promise {} connection resolved", lock);
+
+                // Triggered when a connection attempt is resolved.
+                Preconditions.checkState(ProtocolSessionPromise.this.pending.equals(cf));
+
+                /*
+                 * The promise we gave out could have been cancelled,
+                 * which cascades to the connect getting cancelled,
+                 * but there is a slight race window, where the connect
+                 * is already resolved, but the listener has not yet
+                 * been notified -- cancellation at that point won't
+                 * stop the notification arriving, so we have to close
+                 * the race here.
+                 */
+                if (isCancelled()) {
+                    if (cf.isSuccess()) {
+                        LOG.debug("Closing channel for cancelled promise {}", lock);
+                        cf.channel().close();
+                    }
+                    return;
+                }
+
+                if(cf.isSuccess()) {
+                    LOG.debug("Promise {} connection successful", lock);
+                    return;
+                }
+
+                LOG.debug("Attempt to connect to {} failed", ProtocolSessionPromise.this.address, cf.cause());
+
+                final Future<Void> rf = ProtocolSessionPromise.this.strategy.scheduleReconnect(cf.cause());
+                rf.addListener(new ReconnectingStrategyListener());
+                ProtocolSessionPromise.this.pending = rf;
+            }
+        }
+
+        private class ReconnectingStrategyListener implements FutureListener<Void> {
+            @Override
+            public void operationComplete(final Future<Void> sf) {
+                synchronized (lock) {
+                    // Triggered when a connection attempt is to be made.
+                    Preconditions.checkState(ProtocolSessionPromise.this.pending.equals(sf));
+
+                    /*
+                     * The promise we gave out could have been cancelled,
+                     * which cascades to the reconnect attempt getting
+                     * cancelled, but there is a slight race window, where
+                     * the reconnect attempt is already enqueued, but the
+                     * listener has not yet been notified -- if cancellation
+                     * happens at that point, we need to catch it here.
+                     */
+                    if (!isCancelled()) {
+                        if (sf.isSuccess()) {
+                            connect();
+                        } else {
+                            setFailure(sf.cause());
+                        }
+                    }
+                }
+            }
+        }
+
+    }
+
 }
index 1fa6a8175352617aa8f87a56e90f6d391bdef029..fe1012f443fc7824b1e2b8b3d3c4ed15ecbfb30d 100644 (file)
  */
 package org.opendaylight.protocol.framework;
 
-import io.netty.channel.ChannelFuture;
+import com.google.common.base.Preconditions;
+import io.netty.bootstrap.Bootstrap;
+import io.netty.channel.ChannelHandlerContext;
+import io.netty.channel.ChannelInboundHandlerAdapter;
 import io.netty.channel.socket.SocketChannel;
 import io.netty.util.concurrent.DefaultPromise;
 import io.netty.util.concurrent.EventExecutor;
 import io.netty.util.concurrent.Future;
-import io.netty.util.concurrent.FutureListener;
 import io.netty.util.concurrent.Promise;
-
-import java.io.Closeable;
 import java.net.InetSocketAddress;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-import org.opendaylight.protocol.framework.AbstractDispatcher.PipelineInitializer;
-
-import com.google.common.base.Preconditions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 final class ReconnectPromise<S extends ProtocolSession<?>, L extends SessionListener<?, ?, ?>> extends DefaultPromise<Void> {
+    private static final Logger LOG = LoggerFactory.getLogger(ReconnectPromise.class);
+
     private final AbstractDispatcher<S, L> dispatcher;
     private final InetSocketAddress address;
     private final ReconnectStrategyFactory strategyFactory;
-    private final ReconnectStrategy strategy;
-    private final PipelineInitializer<S> initializer;
+    private final Bootstrap b;
+    private final AbstractDispatcher.PipelineInitializer<S> initializer;
     private Future<?> pending;
 
-    private final AtomicBoolean negotiationFinished = new AtomicBoolean(false);
-
     public ReconnectPromise(final EventExecutor executor, final AbstractDispatcher<S, L> dispatcher, final InetSocketAddress address,
-            final ReconnectStrategyFactory connectStrategyFactory, final ReconnectStrategy reestablishStrategy,
-            final PipelineInitializer<S> initializer) {
+                            final ReconnectStrategyFactory connectStrategyFactory, final Bootstrap b, final AbstractDispatcher.PipelineInitializer<S> initializer) {
         super(executor);
+        this.b = b;
+        this.initializer = Preconditions.checkNotNull(initializer);
         this.dispatcher = Preconditions.checkNotNull(dispatcher);
         this.address = Preconditions.checkNotNull(address);
         this.strategyFactory = Preconditions.checkNotNull(connectStrategyFactory);
-        this.strategy = Preconditions.checkNotNull(reestablishStrategy);
-        this.initializer = Preconditions.checkNotNull(initializer);
     }
 
-    // FIXME: BUG-190: refactor
-
     synchronized void connect() {
-        negotiationFinished.set(false);
-
         final ReconnectStrategy cs = this.strategyFactory.createReconnectStrategy();
-        final ReconnectStrategy rs = new ReconnectStrategy() {
-            @Override
-            public Future<Void> scheduleReconnect(final Throwable cause) {
-                return cs.scheduleReconnect(cause);
-            }
 
-            @Override
-            public void reconnectSuccessful() {
-                cs.reconnectSuccessful();
-            }
-
-            @Override
-            public int getConnectTimeout() throws Exception {
-                final int cst = cs.getConnectTimeout();
-                final int rst = ReconnectPromise.this.strategy.getConnectTimeout();
-
-                if (cst == 0) {
-                    return rst;
-                }
-                if (rst == 0) {
-                    return cst;
-                }
-                return Math.min(cst, rst);
-            }
-        };
-
-        final Future<S> cf = this.dispatcher.createClient(this.address, rs, new PipelineInitializer<S>() {
+        // Set up a client with pre-configured bootstrap, but add a closed channel handler into the pipeline to support reconnect attempts
+        pending = this.dispatcher.createClient(this.address, cs, b, new AbstractDispatcher.PipelineInitializer<S>() {
             @Override
             public void initializeChannel(final SocketChannel channel, final Promise<S> promise) {
-                addChannelClosedListener(channel.closeFuture());
                 initializer.initializeChannel(channel, promise);
+
+                // add closed channel handler
+                channel.pipeline().addFirst(new ClosedChannelHandler(ReconnectPromise.this));
             }
         });
+    }
 
-        final Object lock = this;
-        this.pending = cf;
+    /**
+     *
+     * @return true if initial connection was established successfully, false if initial connection failed due to e.g. Connection refused, Negotiation failed
+     */
+    private boolean isInitialConnectFinished() {
+        Preconditions.checkNotNull(pending);
+        return pending.isDone() && pending.isSuccess();
+    }
 
-        cf.addListener(new FutureListener<S>() {
+    @Override
+    public synchronized boolean cancel(final boolean mayInterruptIfRunning) {
+        if (super.cancel(mayInterruptIfRunning)) {
+            Preconditions.checkNotNull(pending);
+            this.pending.cancel(mayInterruptIfRunning);
+            return true;
+        }
 
-            @Override
-            public void operationComplete(final Future<S> future) {
-                synchronized (lock) {
-                    if (!future.isSuccess()) {
-                        final Future<Void> rf = ReconnectPromise.this.strategy.scheduleReconnect(cf.cause());
-
-                        if(rf == null) {
-                            // This should reflect: no more reconnecting strategies, enough
-                            // Currently all reconnect strategies fail with exception, should return null
-                            return;
-                        }
-
-                        ReconnectPromise.this.pending = rf;
-
-                        rf.addListener(new FutureListener<Void>() {
-                            @Override
-                            public void operationComplete(final Future<Void> sf) {
-                                synchronized (lock) {
-                                    /*
-                                     * The promise we gave out could have been cancelled,
-                                     * which cascades to the reconnect attempt getting
-                                     * cancelled, but there is a slight race window, where
-                                     * the reconnect attempt is already enqueued, but the
-                                     * listener has not yet been notified -- if cancellation
-                                     * happens at that point, we need to catch it here.
-                                     */
-                                    if (!isCancelled()) {
-                                        if (sf.isSuccess()) {
-                                            connect();
-                                        } else {
-                                            setFailure(sf.cause());
-                                        }
-                                    }
-                                }
-                            }
-                        });
-                    } else {
-                        /*
-                         *  FIXME: BUG-190: we have a slight race window with cancellation
-                         *         here. Analyze and define its semantics.
-                         */
-                        ReconnectPromise.this.strategy.reconnectSuccessful();
-                        negotiationFinished.set(true);
-                    }
-                }
-            }
-        });
+        return false;
     }
 
-    private final ClosedChannelListener closedChannelListener = new ClosedChannelListener();
-
-    class ClosedChannelListener implements Closeable, FutureListener<Void> {
+    /**
+     * Channel handler that responds to channelInactive event and reconnects the session.
+     * Only if the initial connection was successfully established and promise was not canceled.
+     */
+    private static final class ClosedChannelHandler extends ChannelInboundHandlerAdapter {
+        private final ReconnectPromise<?, ?> promise;
 
-        private final AtomicBoolean stop = new AtomicBoolean(false);
+        public ClosedChannelHandler(final ReconnectPromise<?, ?> promise) {
+            this.promise = promise;
+        }
 
         @Override
-        public void operationComplete(final Future<Void> future) throws Exception {
-            if (stop.get()) {
+        public void channelInactive(final ChannelHandlerContext ctx) throws Exception {
+            if (promise.isCancelled()) {
                 return;
             }
 
-            // Start reconnecting crashed session after negotiation was successful
-            if (!negotiationFinished.get()) {
+            // Check if initial connection was fully finished. If the session was dropped during negotiation, reconnect will not happen.
+            // Session can be dropped during negotiation on purpose by the client side and would make no sense to initiate reconnect
+            if (promise.isInitialConnectFinished() == false) {
                 return;
             }
 
-            connect();
-        }
-
-        @Override
-        public void close() {
-            this.stop.set(true);
+            LOG.debug("Reconnecting after connection to {} was dropped", promise.address);
+            promise.connect();
         }
     }
 
-    private void addChannelClosedListener(final ChannelFuture channelFuture) {
-        channelFuture.addListener(closedChannelListener);
-    }
-
-    @Override
-    public synchronized boolean cancel(final boolean mayInterruptIfRunning) {
-        closedChannelListener.close();
-
-        if (super.cancel(mayInterruptIfRunning)) {
-            this.pending.cancel(mayInterruptIfRunning);
-            return true;
-        }
-
-        return false;
-    }
 }
index 3c429fc7749be6b4ac37cf5e5800f5978861fa2c..a756a0da7e780e84510d8e329b475b9342e0c9e7 100644 (file)
@@ -10,7 +10,7 @@ package org.opendaylight.protocol.framework;
 import java.util.EventListener;
 
 /**
- * Listener that receives session state informations. This interface should be
+ * Listener that receives session state information. This interface should be
  * implemented by a protocol specific abstract class, that is extended by
  * a final class that implements the methods.
  */
index bead1ee49e64bd1b708ecc6d23c51321f4cc72bd..63026e384c498ce12dca810c94886f9a562215d8 100644 (file)
@@ -9,6 +9,14 @@ package org.opendaylight.protocol.framework;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
+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.timeout;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+
 import io.netty.channel.Channel;
 import io.netty.channel.ChannelFuture;
 import io.netty.channel.nio.NioEventLoopGroup;
@@ -16,50 +24,139 @@ import io.netty.util.concurrent.DefaultPromise;
 import io.netty.util.concurrent.Future;
 import io.netty.util.concurrent.GlobalEventExecutor;
 import io.netty.util.concurrent.Promise;
-
+import io.netty.util.concurrent.SucceededFuture;
 import java.io.IOException;
 import java.net.InetSocketAddress;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
-
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
+import org.mockito.Mockito;
 
 public class ServerTest {
     SimpleDispatcher clientDispatcher, dispatcher;
 
-    final SimpleSessionListener pce = new SimpleSessionListener();
-
     SimpleSession session = null;
 
     ChannelFuture server = null;
 
     InetSocketAddress serverAddress;
     private NioEventLoopGroup eventLoopGroup;
-
+    // Dedicated loop group for server, needed for testing reconnection client
+    // With dedicated server group we can simulate session drop by shutting only the server group down
+    private NioEventLoopGroup serverLoopGroup;
 
     @Before
     public void setUp() {
         final int port = 10000 + (int)(10000 * Math.random());
         serverAddress = new InetSocketAddress("127.0.0.1", port);
         eventLoopGroup = new NioEventLoopGroup();
+        serverLoopGroup = new NioEventLoopGroup();
+    }
+
+    @After
+    public void tearDown() throws IOException, InterruptedException, ExecutionException {
+        if(server != null) {
+            this.server.channel().close();
+        }
+        this.eventLoopGroup.shutdownGracefully().get();
+        this.serverLoopGroup.shutdownGracefully().get();
+        try {
+            Thread.sleep(500);
+        } catch (final InterruptedException e) {
+            throw new RuntimeException(e);
+        }
     }
 
     @Test
-    public void testConnectionEstablished() throws Exception {
+    public void testConnectionRefused() throws Exception {
+        this.clientDispatcher = getClientDispatcher();
+
+        final ReconnectStrategy mockReconnectStrategy = getMockedReconnectStrategy();
+
+        this.clientDispatcher.createClient(this.serverAddress,
+                mockReconnectStrategy, new SessionListenerFactory<SimpleSessionListener>() {
+                    @Override
+                    public SimpleSessionListener getSessionListener() {
+                        return new SimpleSessionListener();
+                    }
+                });
+
+        Mockito.verify(mockReconnectStrategy, timeout(5000).atLeast(2)).scheduleReconnect(any(Throwable.class));
+    }
+
+    @Test
+    public void testConnectionReestablishInitial() throws Exception {
+        this.clientDispatcher = getClientDispatcher();
+
+        final ReconnectStrategy mockReconnectStrategy = getMockedReconnectStrategy();
+
+        this.clientDispatcher.createClient(this.serverAddress,
+                mockReconnectStrategy, new SessionListenerFactory<SimpleSessionListener>() {
+                    @Override
+                    public SimpleSessionListener getSessionListener() {
+                        return new SimpleSessionListener();
+                    }
+                });
+
+        Mockito.verify(mockReconnectStrategy, timeout(5000).atLeast(2)).scheduleReconnect(any(Throwable.class));
+
+        final Promise<Boolean> p = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
+        this.dispatcher = getServerDispatcher(p);
+
+        this.server = this.dispatcher.createServer(this.serverAddress, new SessionListenerFactory<SimpleSessionListener>() {
+            @Override
+            public SimpleSessionListener getSessionListener() {
+                return new SimpleSessionListener();
+            }
+        });
+
+        this.server.get();
+
+        assertEquals(true, p.get(3, TimeUnit.SECONDS));
+    }
+
+    @Test
+    public void testConnectionDrop() throws Exception {
         final Promise<Boolean> p = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
 
-        this.dispatcher = new SimpleDispatcher(new SessionNegotiatorFactory<SimpleMessage, SimpleSession, SimpleSessionListener>() {
+        this.dispatcher = getServerDispatcher(p);
 
+        this.server = this.dispatcher.createServer(this.serverAddress, new SessionListenerFactory<SimpleSessionListener>() {
             @Override
-            public SessionNegotiator<SimpleSession> getSessionNegotiator(final SessionListenerFactory<SimpleSessionListener> factory,
-                    final Channel channel, final Promise<SimpleSession> promise) {
-                p.setSuccess(true);
-                return new SimpleSessionNegotiator(promise, channel);
+            public SimpleSessionListener getSessionListener() {
+                return new SimpleSessionListener();
             }
-        }, new DefaultPromise<SimpleSession>(GlobalEventExecutor.INSTANCE), eventLoopGroup);
+        });
+
+        this.server.get();
+
+        this.clientDispatcher = getClientDispatcher();
+
+        final ReconnectStrategy reconnectStrategy = getMockedReconnectStrategy();
+        this.session = this.clientDispatcher.createClient(this.serverAddress,
+                reconnectStrategy, new SessionListenerFactory<SimpleSessionListener>() {
+                    @Override
+                    public SimpleSessionListener getSessionListener() {
+                        return new SimpleSessionListener();
+                    }
+                }).get(6, TimeUnit.SECONDS);
+
+        assertEquals(true, p.get(3, TimeUnit.SECONDS));
+
+        shutdownServer();
+
+        // No reconnect should be scheduled after server drops connection with not-reconnecting client
+        verify(reconnectStrategy, times(0)).scheduleReconnect(any(Throwable.class));
+    }
+
+    @Test
+    public void testConnectionReestablishAfterDrop() throws Exception {
+        final Promise<Boolean> p = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
+
+        this.dispatcher = getServerDispatcher(p);
 
         this.server = this.dispatcher.createServer(this.serverAddress, new SessionListenerFactory<SimpleSessionListener>() {
             @Override
@@ -70,13 +167,42 @@ public class ServerTest {
 
         this.server.get();
 
-        this.clientDispatcher = new SimpleDispatcher(new SessionNegotiatorFactory<SimpleMessage, SimpleSession, SimpleSessionListener>() {
+        this.clientDispatcher = getClientDispatcher();
+
+        final ReconnectStrategyFactory reconnectStrategyFactory = mock(ReconnectStrategyFactory.class);
+        final ReconnectStrategy reconnectStrategy = getMockedReconnectStrategy();
+        doReturn(reconnectStrategy).when(reconnectStrategyFactory).createReconnectStrategy();
+
+        this.clientDispatcher.createReconnectingClient(this.serverAddress,
+                reconnectStrategyFactory, new SessionListenerFactory<SimpleSessionListener>() {
+                    @Override
+                    public SimpleSessionListener getSessionListener() {
+                        return new SimpleSessionListener();
+                    }
+                });
+
+        assertEquals(true, p.get(3, TimeUnit.SECONDS));
+        shutdownServer();
+
+        verify(reconnectStrategyFactory, timeout(20000).atLeast(2)).createReconnectStrategy();
+    }
+
+    @Test
+    public void testConnectionEstablished() throws Exception {
+        final Promise<Boolean> p = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
+
+        this.dispatcher = getServerDispatcher(p);
+
+        this.server = this.dispatcher.createServer(this.serverAddress, new SessionListenerFactory<SimpleSessionListener>() {
             @Override
-            public SessionNegotiator<SimpleSession> getSessionNegotiator(final SessionListenerFactory<SimpleSessionListener> factory,
-                    final Channel channel, final Promise<SimpleSession> promise) {
-                return new SimpleSessionNegotiator(promise, channel);
+            public SimpleSessionListener getSessionListener() {
+                return new SimpleSessionListener();
             }
-        }, new DefaultPromise<SimpleSession>(GlobalEventExecutor.INSTANCE), eventLoopGroup);
+        });
+
+        this.server.get();
+
+        this.clientDispatcher = getClientDispatcher();
 
         this.session = this.clientDispatcher.createClient(this.serverAddress,
                 new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 5000), new SessionListenerFactory<SimpleSessionListener>() {
@@ -93,15 +219,7 @@ public class ServerTest {
     public void testConnectionFailed() throws IOException, InterruptedException, ExecutionException, TimeoutException {
         final Promise<Boolean> p = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
 
-        this.dispatcher = new SimpleDispatcher(new SessionNegotiatorFactory<SimpleMessage, SimpleSession, SimpleSessionListener>() {
-
-            @Override
-            public SessionNegotiator<SimpleSession> getSessionNegotiator(final SessionListenerFactory<SimpleSessionListener> factory,
-                    final Channel channel, final Promise<SimpleSession> promise) {
-                p.setSuccess(true);
-                return new SimpleSessionNegotiator(promise, channel);
-            }
-        }, new DefaultPromise<SimpleSession>(GlobalEventExecutor.INSTANCE), eventLoopGroup);
+        this.dispatcher = getServerDispatcher(p);
 
         this.server = this.dispatcher.createServer(this.serverAddress, new SessionListenerFactory<SimpleSessionListener>() {
             @Override
@@ -112,13 +230,7 @@ public class ServerTest {
 
         this.server.get();
 
-        this.clientDispatcher = new SimpleDispatcher(new SessionNegotiatorFactory<SimpleMessage, SimpleSession, SimpleSessionListener>() {
-            @Override
-            public SessionNegotiator<SimpleSession> getSessionNegotiator(final SessionListenerFactory<SimpleSessionListener> factory,
-                    final Channel channel, final Promise<SimpleSession> promise) {
-                return new SimpleSessionNegotiator(promise, channel);
-            }
-        }, new DefaultPromise<SimpleSession>(GlobalEventExecutor.INSTANCE), eventLoopGroup);
+        this.clientDispatcher = getClientDispatcher();
 
         this.session = this.clientDispatcher.createClient(this.serverAddress,
                 new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 5000), new SessionListenerFactory<SimpleSessionListener>() {
@@ -138,14 +250,89 @@ public class ServerTest {
         assertFalse(session.isSuccess());
     }
 
-    @After
-    public void tearDown() throws IOException, InterruptedException {
-        this.server.channel().close();
-        this.eventLoopGroup.shutdownGracefully();
-        try {
-            Thread.sleep(500);
-        } catch (final InterruptedException e) {
-            throw new RuntimeException(e);
-        }
+    @Test
+    public void testNegotiationFailedNoReconnect() throws Exception {
+        final Promise<Boolean> p = new DefaultPromise<>(GlobalEventExecutor.INSTANCE);
+
+        this.dispatcher = getServerDispatcher(p);
+
+        this.server = this.dispatcher.createServer(this.serverAddress, new SessionListenerFactory<SimpleSessionListener>() {
+            @Override
+            public SimpleSessionListener getSessionListener() {
+                return new SimpleSessionListener();
+            }
+        });
+
+        this.server.get();
+
+        this.clientDispatcher = new SimpleDispatcher(new SessionNegotiatorFactory<SimpleMessage, SimpleSession, SimpleSessionListener>() {
+            @Override
+            public SessionNegotiator<SimpleSession> getSessionNegotiator(final SessionListenerFactory<SimpleSessionListener> factory,
+                                                                         final Channel channel, final Promise<SimpleSession> promise) {
+
+                return new SimpleSessionNegotiator(promise, channel) {
+                    @Override
+                    protected void startNegotiation() throws Exception {
+                        negotiationFailed(new IllegalStateException("Negotiation failed"));
+                    }
+                };
+            }
+        }, new DefaultPromise<SimpleSession>(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<SimpleSessionListener>() {
+                    @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<SimpleMessage, SimpleSession, SimpleSessionListener>() {
+            @Override
+            public SessionNegotiator<SimpleSession> getSessionNegotiator(final SessionListenerFactory<SimpleSessionListener> factory,
+                                                                         final Channel channel, final Promise<SimpleSession> promise) {
+                return new SimpleSessionNegotiator(promise, channel);
+            }
+        }, new DefaultPromise<SimpleSession>(GlobalEventExecutor.INSTANCE), eventLoopGroup);
+    }
+
+    private ReconnectStrategy getMockedReconnectStrategy() throws Exception {
+        final ReconnectStrategy mockReconnectStrategy = mock(ReconnectStrategy.class);
+        final Future<Void> future = new SucceededFuture<>(GlobalEventExecutor.INSTANCE, null);
+        doReturn(future).when(mockReconnectStrategy).scheduleReconnect(any(Throwable.class));
+        doReturn(5000).when(mockReconnectStrategy).getConnectTimeout();
+        doNothing().when(mockReconnectStrategy).reconnectSuccessful();
+        return mockReconnectStrategy;
+    }
+
+
+    private void shutdownServer() throws InterruptedException, ExecutionException {
+        // Shutdown server
+        server.channel().close().get();
+        // Closing server channel does not close established connections, eventLoop has to be closed as well to simulate dropped session
+        serverLoopGroup.shutdownGracefully().get();
+    }
+
+    private SimpleDispatcher getServerDispatcher(final Promise<Boolean> p) {
+        return new SimpleDispatcher(new SessionNegotiatorFactory<SimpleMessage, SimpleSession, SimpleSessionListener>() {
+
+            @Override
+            public SessionNegotiator<SimpleSession> getSessionNegotiator(final SessionListenerFactory<SimpleSessionListener> factory,
+                                                                         final Channel channel, final Promise<SimpleSession> promise) {
+                p.setSuccess(true);
+                return new SimpleSessionNegotiator(promise, channel);
+            }
+        }, null, serverLoopGroup);
+    }
+
 }
index 12aac9ecc5257432ee282159f24dbb1fd2c319a5..d83738520cccc1e7bc24b4f97cb31c30ff6e51ad 100644 (file)
@@ -54,6 +54,10 @@ public class SimpleDispatcher extends AbstractDispatcher<SimpleSession, SimpleSe
         return super.createClient(address, strategy, new SimplePipelineInitializer(listenerFactory));
     }
 
+    public Future<Void> createReconnectingClient(final InetSocketAddress address, final ReconnectStrategyFactory strategy, final SessionListenerFactory<SimpleSessionListener> listenerFactory) {
+        return super.createReconnectingClient(address, strategy, new SimplePipelineInitializer(listenerFactory));
+    }
+
     public ChannelFuture createServer(final InetSocketAddress address, final SessionListenerFactory<SimpleSessionListener> listenerFactory) {
         return super.createServer(address, new SimplePipelineInitializer(listenerFactory));
     }
index ec46219aaf8469e3d8ecadcc9988bb4a47188e3f..6050f7c07073061fe4233e99d915308489bc5a7f 100644 (file)
@@ -14,7 +14,7 @@ import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy
 import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
 import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
 import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
 import org.osgi.framework.BundleContext;
 
 /**
@@ -31,7 +31,7 @@ public class CodecRegistryProvider implements AutoCloseable {
     public CodecRegistryProvider(final ClassLoadingStrategy classLoadingStrategy, final BundleContext context) {
         service = new RuntimeGeneratedMappingServiceImpl(CLASS_POOL, classLoadingStrategy);
         registration = OsgiRegistrationUtil.registerService(context, service,
-                SchemaServiceListener.class, BindingIndependentMappingService.class);
+                SchemaContextListener.class, BindingIndependentMappingService.class);
     }
 
     public CodecRegistry getCodecRegistry() {
diff --git a/opendaylight/config/config-netty-config/pom.xml b/opendaylight/config/config-netty-config/pom.xml
new file mode 100644 (file)
index 0000000..8dc31dc
--- /dev/null
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+  <modelVersion>4.0.0</modelVersion>
+  <parent>
+    <groupId>org.opendaylight.controller</groupId>
+    <artifactId>config-subsystem</artifactId>
+    <version>0.2.5-SNAPSHOT</version>
+  </parent>
+  <artifactId>config-netty-config</artifactId>
+  <description>Configuration files for sal-rest-connector</description>
+  <packaging>jar</packaging>
+  <build>
+       <plugins>
+               <plugin>
+        <groupId>org.codehaus.mojo</groupId>
+        <artifactId>build-helper-maven-plugin</artifactId>
+        <executions>
+          <execution>
+            <id>attach-artifacts</id>
+            <goals>
+              <goal>attach-artifact</goal>
+            </goals>
+            <phase>package</phase>
+            <configuration>
+              <artifacts>
+                <artifact>
+                  <file>${project.build.directory}/classes/initial/00-netty.xml</file>
+                  <type>xml</type>
+                  <classifier>config</classifier>
+                </artifact>
+              </artifacts>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+    </plugins>
+  </build>
+</project>
index 66bb01f051fa1042e9fc08d4019a236f1e07bb04..26fac47e71cc63c6d1462335a7f520f9309ed259 100644 (file)
@@ -39,6 +39,7 @@
     <module>shutdown-impl</module>
     <module>netconf-config-dispatcher</module>
     <module>config-module-archetype</module>
+    <module>config-netty-config</module>
   </modules>
 
   <dependencies>
index 1d579ebe42ae891f934a1d4a88766774a9e893b9..7c3289adb5e0a7857227549535a8997be6837114 100644 (file)
             <phase>generate-resources</phase>
             <configuration>
                <outputDirectory>${project.build.directory}/configuration</outputDirectory>
-               <includeArtifactIds>sal-rest-connector-config</includeArtifactIds>
+               <includeArtifactIds>sal-rest-connector-config,config-netty-config,md-sal-config,netconf-config,toaster-config,netconf-connector-config</includeArtifactIds>
                <includes>**\/*.xml</includes>
                <excludeTransitive>true</excludeTransitive>
                <ignorePermissions>false</ignorePermissions>
           <groupId>org.opendaylight.controller</groupId>
           <artifactId>sal-rest-connector-config</artifactId>
         </dependency>
+        <dependency>
+          <groupId>org.opendaylight.controller</groupId>
+          <artifactId>config-netty-config</artifactId>
+        </dependency>
+        <dependency>
+          <groupId>org.opendaylight.controller</groupId>
+          <artifactId>md-sal-config</artifactId>
+        </dependency>
+        <dependency>
+          <groupId>org.opendaylight.controller</groupId>
+          <artifactId>netconf-config</artifactId>
+        </dependency>
+        <dependency>
+          <groupId>org.opendaylight.controller</groupId>
+          <artifactId>netconf-connector-config</artifactId>
+        </dependency>
+        <dependency>
+          <groupId>org.opendaylight.controller.samples</groupId>
+          <artifactId>toaster-config</artifactId>
+        </dependency>
         <dependency>
           <groupId>org.opendaylight.controller</groupId>
           <artifactId>sal-rest-docgen</artifactId>
                 <phase>generate-resources</phase>
                 <configuration>
                    <outputDirectory>${project.build.directory}/configuration</outputDirectory>
-                   <includeArtifactIds>sal-rest-connector-config</includeArtifactIds>
+                   <includeArtifactIds>sal-rest-connector-config,config-netty-config,md-sal-config,netconf-config,toaster-config,netconf-connector-config</includeArtifactIds>
                    <includes>**\/*.xml</includes>
                    <excludeTransitive>true</excludeTransitive>
                    <ignorePermissions>false</ignorePermissions>
diff --git a/opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IHostTrackerShell.java b/opendaylight/hosttracker/api/src/main/java/org/opendaylight/controller/hosttracker/IHostTrackerShell.java
new file mode 100644 (file)
index 0000000..5d11be4
--- /dev/null
@@ -0,0 +1,9 @@
+package org.opendaylight.controller.hosttracker;
+
+import java.util.List;
+
+public interface IHostTrackerShell{
+
+    public List<String> dumpPendingArpReqList();
+    public List<String> dumpFailedArpReqList();
+}
\ No newline at end of file
index 825b2453aac1cb18cb4af3527f19331dd718048d..7e527712b1058b756ad743896f94a5447b65a61b 100644 (file)
@@ -16,6 +16,7 @@ import java.util.Set;
 import org.apache.felix.dm.Component;
 import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
+import org.opendaylight.controller.hosttracker.IHostTrackerShell;
 import org.opendaylight.controller.hosttracker.IfHostListener;
 import org.opendaylight.controller.hosttracker.IfIptoHost;
 import org.opendaylight.controller.hosttracker.IfNewHostNotify;
@@ -78,6 +79,7 @@ public class Activator extends ComponentActivatorAbstractBase {
                             IInventoryListener.class.getName(),
                             IfIptoHost.class.getName(),
                             IfHostListener.class.getName(),
+                            IHostTrackerShell.class.getName(),
                             ITopologyManagerAware.class.getName(),
                             ICacheUpdateAware.class.getName() }, props);
 
index ce49b599e18f90833f1850bc23bfb74b457aabaf..f728b35bbfa7f492c3937b87616e4b655ba3f16f 100644 (file)
@@ -39,6 +39,7 @@ import org.opendaylight.controller.clustering.services.IClusterContainerServices
 import org.opendaylight.controller.clustering.services.IClusterServices;
 import org.opendaylight.controller.hosttracker.HostIdFactory;
 import org.opendaylight.controller.hosttracker.IHostId;
+import org.opendaylight.controller.hosttracker.IHostTrackerShell;
 import org.opendaylight.controller.hosttracker.IPHostId;
 import org.opendaylight.controller.hosttracker.IPMacHostId;
 import org.opendaylight.controller.hosttracker.IfHostListener;
@@ -100,7 +101,7 @@ import org.slf4j.LoggerFactory;
  *
  */
 
-public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAware, IInventoryListener,
+public class HostTracker implements IfIptoHost, IfHostListener, IHostTrackerShell, ISwitchManagerAware, IInventoryListener,
         ITopologyManagerAware, ICacheUpdateAware<IHostId, HostNodeConnector>, CommandProvider {
     static final String ACTIVE_HOST_CACHE = "hosttracker.ActiveHosts";
     static final String INACTIVE_HOST_CACHE = "hosttracker.InactiveHosts";
@@ -1618,4 +1619,24 @@ public class HostTracker implements IfIptoHost, IfHostListener, ISwitchManagerAw
         IHostId id = HostIdFactory.create(addr, null);
         return getHostNetworkHierarchy(id);
     }
+
+    @Override
+    public List<String> dumpPendingArpReqList() {
+        ARPPending arphost;
+        List<String> arpReq = new ArrayList<String>();
+        for (Entry<IHostId, ARPPending> entry : ARPPendingList.entrySet()) {
+            arpReq.add(entry.getValue().getHostId().toString());
+        }
+        return arpReq;
+    }
+
+    @Override
+    public List<String> dumpFailedArpReqList() {
+        ARPPending arphost;
+        List<String> arpReq = new ArrayList<String>();
+        for (Entry<IHostId, ARPPending> entry : failedARPReqList.entrySet()) {
+            arpReq.add(entry.getValue().getHostId().toString());
+        }
+        return arpReq;
+    }
 }
diff --git a/opendaylight/hosttracker/shell/pom.xml b/opendaylight/hosttracker/shell/pom.xml
new file mode 100644 (file)
index 0000000..3f73303
--- /dev/null
@@ -0,0 +1,52 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+  <parent>
+    <groupId>org.opendaylight.controller</groupId>
+    <artifactId>commons.opendaylight</artifactId>
+    <version>1.4.2-SNAPSHOT</version>
+    <relativePath>../../commons/opendaylight</relativePath>
+  </parent>
+  <artifactId>hosttracker.shell</artifactId>
+  <version>${hosttracker.shell.version}</version>
+  <packaging>bundle</packaging>
+  <dependencies>
+    <dependency>
+      <groupId>junit</groupId>
+      <artifactId>junit</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.karaf.shell</groupId>
+      <artifactId>org.apache.karaf.shell.console</artifactId>
+      <version>3.0.0</version>
+    </dependency>
+    <dependency>
+      <groupId>org.mockito</groupId>
+      <artifactId>mockito-all</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>hosttracker.implementation</artifactId>
+      <version>${hosttracker.implementation.version}</version>
+    </dependency>
+  </dependencies>
+
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.felix</groupId>
+        <artifactId>maven-bundle-plugin</artifactId>
+        <version>${bundle.plugin.version}</version>
+        <configuration>
+          <instructions>
+            <Import-Package>org.apache.felix.service.command,
+              org.apache.karaf.shell.commands,
+              org.apache.karaf.shell.console,
+              *</Import-Package>
+          </instructions>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
+
+</project>
diff --git a/opendaylight/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpFailedARPReqList.java b/opendaylight/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpFailedARPReqList.java
new file mode 100644 (file)
index 0000000..ec9971f
--- /dev/null
@@ -0,0 +1,28 @@
+package org.opendaylight.controller.hosttracker.shell;
+/**
+* Copyright (c) 2014 Inocybe Technologies, 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
+*/
+
+import org.apache.felix.gogo.commands.Command;
+import org.apache.karaf.shell.console.OsgiCommandSupport;
+import org.opendaylight.controller.hosttracker.IHostTrackerShell;
+
+@Command(scope = "hosttracker", name = "dumpFailedARPReqList", description="Display the dump failed ARPReqList")
+public class DumpFailedARPReqList extends OsgiCommandSupport{
+
+    private IHostTrackerShell hostTracker;
+
+    @Override
+    protected Object doExecute() throws Exception {
+        System.out.print(hostTracker.dumpFailedArpReqList());
+        return null;
+    }
+
+    public void setHostTracker(IHostTrackerShell hostTracker){
+        this.hostTracker = hostTracker;
+    }
+}
diff --git a/opendaylight/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpPendingARPReqList.java b/opendaylight/hosttracker/shell/src/main/java/org/opendaylight/controller/hosttracker/shell/DumpPendingARPReqList.java
new file mode 100644 (file)
index 0000000..7f52a55
--- /dev/null
@@ -0,0 +1,28 @@
+package org.opendaylight.controller.hosttracker.shell;
+/**
+* Copyright (c) 2014 Inocybe Technologies, 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
+*/
+
+import org.apache.felix.gogo.commands.Command;
+import org.apache.karaf.shell.console.OsgiCommandSupport;
+import org.opendaylight.controller.hosttracker.IHostTrackerShell;
+
+@Command(scope = "hosttracker", name = "dumpPendingARPReqList", description="Display the dump pending ARPReqList")
+public class DumpPendingARPReqList extends OsgiCommandSupport{
+
+    private IHostTrackerShell hostTracker;
+
+    @Override
+    protected Object doExecute() throws Exception {
+        System.out.print(hostTracker.dumpPendingArpReqList());
+        return null;
+    }
+
+    public void setHostTracker(IHostTrackerShell hostTracker){
+        this.hostTracker = hostTracker;
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/hosttracker/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/opendaylight/hosttracker/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml
new file mode 100644 (file)
index 0000000..ba79b5d
--- /dev/null
@@ -0,0 +1,17 @@
+<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
+    <reference id="HostTrackerRef" interface="org.opendaylight.controller.hosttracker.IHostTrackerShell"/>
+
+    <command-bundle xmlns="http://karaf.apache.org/xmlns/shell/v1.1.0">
+
+    <command>
+       <action class="org.opendaylight.controller.hosttracker.shell.DumpFailedARPReqList">
+          <property name="hostTracker" ref="HostTrackerRef"/>
+       </action>
+    </command>
+    <command>
+       <action class="org.opendaylight.controller.hosttracker.shell.DumpPendingARPReqList">
+          <property name="hostTracker" ref="HostTrackerRef"/>
+       </action>
+    </command>
+    </command-bundle>
+</blueprint>
diff --git a/opendaylight/hosttracker/shell/src/test/java/org/opendaylight/controller/hosttracker/shell/HostTrackerShellTest.java b/opendaylight/hosttracker/shell/src/test/java/org/opendaylight/controller/hosttracker/shell/HostTrackerShellTest.java
new file mode 100644 (file)
index 0000000..a0a5a2e
--- /dev/null
@@ -0,0 +1,47 @@
+package org.opendaylight.controller.hosttracker.shell;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.junit.Assert;
+import org.junit.Test;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import org.opendaylight.controller.hosttracker.IHostTrackerShell;
+
+public class HostTrackerShellTest {
+
+    private final long COMMAND_TIMEOUT = 1000;
+    private IHostTrackerShell hostTracker;
+
+    @Test
+    public void testDumpPendingARPReqList() throws Exception {
+        DumpPendingARPReqList dumpPendTest = new DumpPendingARPReqList();
+        hostTracker = mock(IHostTrackerShell.class);
+        List<String> failedList = new ArrayList<String>(Arrays.asList("a", "b", "c"));
+        when(hostTracker.dumpPendingArpReqList()).thenReturn(failedList);
+        dumpPendTest.setHostTracker(hostTracker);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        System.setOut(new PrintStream(baos));
+        dumpPendTest.doExecute();
+        //Assert.assertTrue(true);
+        Assert.assertEquals("[a, b, c]", baos.toString());
+    }
+
+    @Test
+    public void testDumpFailedARPReqList() throws Exception {
+        DumpFailedARPReqList dumpFailTest = new DumpFailedARPReqList();
+        hostTracker = mock(IHostTrackerShell.class);
+        List<String> failedList = new ArrayList<String>(Arrays.asList("a", "b", "c"));
+        when(hostTracker.dumpFailedArpReqList()).thenReturn(failedList);
+        dumpFailTest.setHostTracker(hostTracker);
+        ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        System.setOut(new PrintStream(baos));
+        dumpFailTest.doExecute();
+        //Assert.assertTrue(true);
+        Assert.assertEquals("[a, b, c]", baos.toString());
+    }
+}
diff --git a/opendaylight/md-sal/md-sal-config/pom.xml b/opendaylight/md-sal/md-sal-config/pom.xml
new file mode 100644 (file)
index 0000000..2e19b5a
--- /dev/null
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+  <modelVersion>4.0.0</modelVersion>
+  <parent>
+    <groupId>org.opendaylight.controller</groupId>
+    <artifactId>sal-parent</artifactId>
+    <version>1.1-SNAPSHOT</version>
+  </parent>
+  <artifactId>md-sal-config</artifactId>
+  <description>Configuration files for md-sal</description>
+  <packaging>jar</packaging>
+  <build>
+    <plugins>
+        <plugin>
+        <groupId>org.codehaus.mojo</groupId>
+        <artifactId>build-helper-maven-plugin</artifactId>
+        <executions>
+          <execution>
+            <id>attach-artifacts</id>
+            <goals>
+              <goal>attach-artifact</goal>
+            </goals>
+            <phase>package</phase>
+            <configuration>
+              <artifacts>
+                <artifact>
+                  <file>${project.build.directory}/classes/initial/01-md-sal.xml</file>
+                  <type>xml</type>
+                  <classifier>config</classifier>
+                </artifact>
+              </artifacts>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+    </plugins>
+  </build>
+</project>
index 3f02765affd8a062420f327fb489ed3adf5d3966..02fbde8f1826648b12278311fb3defe1e72c1347 100644 (file)
@@ -32,6 +32,9 @@
 
     <module>sal-binding-util</module>
 
+    <!-- Configuration File -->
+    <module>md-sal-config</module>
+
     <!-- Samples -->
     <module>samples</module>
 
@@ -69,6 +72,9 @@
     <!-- sal-distributed-datastore -->
     <module>sal-distributed-datastore</module>
 
+    <!-- XSQL -->
+    <module>sal-dom-xsql</module>
+
     <!-- Yang Test Models for MD-SAL -->
     <module>sal-test-model</module>
 
index 641ec0582c3790cac20a6b7102ad5e12134e72e1..aa100df9d0517dfa014a78054e2319d8b1bd34fe 100644 (file)
@@ -11,10 +11,12 @@ 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 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.protobuff.client.messages.Payload;
 
@@ -31,15 +33,17 @@ public class ExampleActor extends RaftActor {
     private long persistIdentifier = 1;
 
 
-    public ExampleActor(String id, Map<String, String> peerAddresses) {
-        super(id, peerAddresses);
+    public ExampleActor(String id, Map<String, String> peerAddresses,
+        Optional<ConfigParams> configParams) {
+        super(id, peerAddresses, configParams);
     }
 
-    public static Props props(final String id, final Map<String, String> peerAddresses){
+    public static Props props(final String id, final Map<String, String> peerAddresses,
+        final Optional<ConfigParams> configParams){
         return Props.create(new Creator<ExampleActor>(){
 
             @Override public ExampleActor create() throws Exception {
-                return new ExampleActor(id, peerAddresses);
+                return new ExampleActor(id, peerAddresses, configParams);
             }
         });
     }
@@ -56,10 +60,12 @@ public class ExampleActor extends RaftActor {
             }
 
         } else if (message instanceof PrintState) {
-            LOG.debug("State of the node:"+getId() + " has = "+state.size() + " entries");
+            LOG.debug("State of the node:{} has entries={}, {}",
+                getId(), state.size(), getReplicatedLogState());
 
         } else if (message instanceof PrintRole) {
-            LOG.debug(getId() + " = " + getRaftState());
+            LOG.debug("{} = {}, Peers={}", getId(), getRaftState(),getPeers());
+
         } else {
             super.onReceiveCommand(message);
         }
@@ -83,6 +89,7 @@ public class ExampleActor extends RaftActor {
     @Override protected void applySnapshot(Object snapshot) {
         state.clear();
         state.putAll((HashMap) snapshot);
+        LOG.debug("Snapshot applied to state :" + ((HashMap) snapshot).size());
     }
 
     @Override public void onReceiveRecover(Object message) {
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
new file mode 100644 (file)
index 0000000..d11377d
--- /dev/null
@@ -0,0 +1,20 @@
+/*
+ * 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.example;
+
+import org.opendaylight.controller.cluster.raft.DefaultConfigParamsImpl;
+
+/**
+ * Implementation of ConfigParams for Example
+ */
+public class ExampleConfigParamsImpl extends DefaultConfigParamsImpl {
+    @Override
+    public long getSnapshotBatchCount() {
+        return 50;
+    }
+}
index a148ed4009e81870d7443fa867faac43605d4c25..0e5d643a643731277003781b75dd353c92697285 100644 (file)
@@ -11,7 +11,9 @@ package org.opendaylight.controller.cluster.example;
 import akka.actor.ActorRef;
 import akka.actor.ActorSystem;
 import akka.actor.PoisonPill;
+import com.google.common.base.Optional;
 import org.opendaylight.controller.cluster.example.messages.KeyValue;
+import org.opendaylight.controller.cluster.raft.ConfigParams;
 
 import java.io.BufferedReader;
 import java.io.InputStreamReader;
@@ -34,15 +36,15 @@ public class Main {
     public static void main(String[] args) throws Exception{
         ActorRef example1Actor =
             actorSystem.actorOf(ExampleActor.props("example-1",
-                withoutPeer("example-1")), "example-1");
+                withoutPeer("example-1"), Optional.<ConfigParams>absent()), "example-1");
 
         ActorRef example2Actor =
             actorSystem.actorOf(ExampleActor.props("example-2",
-                withoutPeer("example-2")), "example-2");
+                withoutPeer("example-2"), Optional.<ConfigParams>absent()), "example-2");
 
         ActorRef example3Actor =
             actorSystem.actorOf(ExampleActor.props("example-3",
-                withoutPeer("example-3")), "example-3");
+                withoutPeer("example-3"), Optional.<ConfigParams>absent()), "example-3");
 
 
         List<ActorRef> examples = Arrays.asList(example1Actor, example2Actor, example3Actor);
@@ -74,7 +76,8 @@ public class Main {
                         String actorName = "example-" + i;
                         examples.add(i - 1,
                             actorSystem.actorOf(ExampleActor.props(actorName,
-                                withoutPeer(actorName)), actorName));
+                                withoutPeer(actorName), Optional.<ConfigParams>absent()),
+                                actorName));
                         System.out.println("Created actor : " + actorName);
                         continue;
                     }
index c2d0b3a6b7cf9a043554ee092de35fd22a8d293d..fd6e192bf0497777de2643a1b3f28a2a76b72e42 100644 (file)
@@ -2,8 +2,10 @@ package org.opendaylight.controller.cluster.example;
 
 import akka.actor.ActorRef;
 import akka.actor.ActorSystem;
+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 org.opendaylight.controller.cluster.raft.client.messages.RemoveRaftPeer;
 
@@ -11,14 +13,13 @@ import java.io.BufferedReader;
 import java.io.InputStreamReader;
 import java.util.HashMap;
 import java.util.Map;
-import java.util.Random;
 import java.util.concurrent.ConcurrentHashMap;
 
 /**
  * This is a test driver for testing akka-raft implementation
  * Its uses ExampleActors and threads to push content(key-vals) to these actors
  * Each ExampleActor can have one or more ClientActors. Each ClientActor spawns
- * a thread and starts push logs to the actor its assignged to.
+ * a thread and starts push logs to the actor its assigned to.
  */
 public class TestDriver {
 
@@ -26,7 +27,9 @@ public class TestDriver {
     private static Map<String, String> allPeers = new HashMap<>();
     private static Map<String, ActorRef> clientActorRefs  = new HashMap<String, ActorRef>();
     private static Map<String, ActorRef> actorRefs = new HashMap<String, ActorRef>();
-    private static LogGenerator logGenerator = new LogGenerator();;
+    private static LogGenerator logGenerator = new LogGenerator();
+    private int nameCounter = 0;
+    private static ConfigParams configParams = new ExampleConfigParamsImpl();
 
     /**
      * Create nodes, add clients and start logging.
@@ -35,6 +38,7 @@ public class TestDriver {
      *  createNodes:{num}
      *  addNodes:{num}
      *  stopNode:{nodeName}
+     *  reinstateNode:{nodeName}
      *  addClients:{num}
      *  addClientsToNode:{nodeName, num}
      *  startLogging
@@ -83,6 +87,10 @@ public class TestDriver {
                 String[] arr = command.split(":");
                 td.stopNode(arr[1]);
 
+            } else if (command.startsWith("reinstateNode")) {
+                String[] arr = command.split(":");
+                td.reinstateNode(arr[1]);
+
             } else if (command.startsWith("startLogging")) {
                 td.startAllLogging();
 
@@ -106,15 +114,19 @@ public class TestDriver {
         }
     }
 
+    public static ActorRef createExampleActor(String name) {
+        return actorSystem.actorOf(ExampleActor.props(name, withoutPeer(name),
+            Optional.of(configParams)), name);
+    }
+
     public void createNodes(int num) {
         for (int i=0; i < num; i++)  {
-            int rand = getUnusedRandom(num);
-            allPeers.put("example-"+rand, "akka://default/user/example-"+rand);
+            nameCounter = nameCounter + 1;
+            allPeers.put("example-"+nameCounter, "akka://default/user/example-"+nameCounter);
         }
 
         for (String s : allPeers.keySet())  {
-            ActorRef exampleActor = actorSystem.actorOf(
-                ExampleActor.props(s, withoutPeer(s)), s);
+            ActorRef exampleActor = createExampleActor(s);
             actorRefs.put(s, exampleActor);
             System.out.println("Created node:"+s);
 
@@ -125,15 +137,14 @@ public class TestDriver {
     public void addNodes(int num) {
         Map<String, String> newPeers = new HashMap<>();
         for (int i=0; i < num; i++)  {
-            int rand = getUnusedRandom(num);
-            newPeers.put("example-"+rand, "akka://default/user/example-"+rand);
-            allPeers.put("example-"+rand, "akka://default/user/example-"+rand);
+            nameCounter = nameCounter + 1;
+            newPeers.put("example-"+nameCounter, "akka://default/user/example-"+nameCounter);
+            allPeers.put("example-"+nameCounter, "akka://default/user/example-"+nameCounter);
 
         }
         Map<String, ActorRef> newActorRefs = new HashMap<String, ActorRef>(num);
         for (Map.Entry<String, String> entry : newPeers.entrySet())  {
-            ActorRef exampleActor = actorSystem.actorOf(
-                ExampleActor.props(entry.getKey(), withoutPeer(entry.getKey())), entry.getKey());
+            ActorRef exampleActor = createExampleActor(entry.getKey());
             newActorRefs.put(entry.getKey(), exampleActor);
 
             //now also add these new nodes as peers from the previous nodes
@@ -165,7 +176,7 @@ public class TestDriver {
     public void addClientsToNode(String actorName, int num) {
         ActorRef actorRef = actorRefs.get(actorName);
         for (int i=0; i < num; i++) {
-            String clientName = "client-" + i + "-" + actorRef;
+            String clientName = "client-" + i + "-" + actorName;
             clientActorRefs.put(clientName,
                 actorSystem.actorOf(ClientActor.props(actorRef), clientName));
             System.out.println("Added client-node:" + clientName);
@@ -174,11 +185,13 @@ public class TestDriver {
 
     public void stopNode(String actorName) {
         ActorRef actorRef = actorRefs.get(actorName);
-        String clientName = "client-"+actorName;
-        if(clientActorRefs.containsKey(clientName)) {
-            actorSystem.stop(clientActorRefs.get(clientName));
-            clientActorRefs.remove(clientName);
+
+        for (Map.Entry<String,ActorRef> entry : clientActorRefs.entrySet()) {
+            if (entry.getKey().endsWith(actorName)) {
+                actorSystem.stop(entry.getValue());
+            }
         }
+
         actorSystem.stop(actorRef);
         actorRefs.remove(actorName);
 
@@ -187,7 +200,21 @@ public class TestDriver {
         }
 
         allPeers.remove(actorName);
+    }
 
+    public void reinstateNode(String actorName) {
+        String address = "akka://default/user/"+actorName;
+        allPeers.put(actorName, address);
+
+        ActorRef exampleActor = createExampleActor(actorName);
+
+        for (ActorRef actor : actorRefs.values()) {
+            actor.tell(new AddRaftPeer(actorName, address), null);
+        }
+
+        actorRefs.put(actorName, exampleActor);
+
+        addClientsToNode(actorName, 1);
     }
 
     public void startAllLogging() {
@@ -232,14 +259,6 @@ public class TestDriver {
         return null;
     }
 
-    private int getUnusedRandom(int num) {
-        int rand = -1;
-        do {
-            rand = (new Random()).nextInt(num * num);
-        } while (allPeers.keySet().contains("example-"+rand));
-
-        return rand;
-    }
 
     private static Map<String, String> withoutPeer(String peerId) {
         Map<String, String> without = new ConcurrentHashMap<>(allPeers);
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
new file mode 100644 (file)
index 0000000..24bfa3d
--- /dev/null
@@ -0,0 +1,153 @@
+/*
+ * 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 java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Abstract class handling the mapping of
+ * logical LogEntry Index and the physical list index.
+ */
+public abstract class AbstractReplicatedLogImpl implements ReplicatedLog {
+
+    protected final List<ReplicatedLogEntry> journal;
+    protected final Object snapshot;
+    protected long snapshotIndex = -1;
+    protected long snapshotTerm = -1;
+
+    public AbstractReplicatedLogImpl(Object state, long snapshotIndex,
+        long snapshotTerm, List<ReplicatedLogEntry> unAppliedEntries) {
+        this.snapshot = state;
+        this.snapshotIndex = snapshotIndex;
+        this.snapshotTerm = snapshotTerm;
+        this.journal = new ArrayList<>(unAppliedEntries);
+    }
+
+
+    public AbstractReplicatedLogImpl() {
+        this.snapshot = null;
+        this.journal = new ArrayList<>();
+    }
+
+    protected int adjustedIndex(long logEntryIndex) {
+        if(snapshotIndex < 0){
+            return (int) logEntryIndex;
+        }
+        return (int) (logEntryIndex - (snapshotIndex + 1));
+    }
+
+    @Override
+    public ReplicatedLogEntry get(long logEntryIndex) {
+        int adjustedIndex = adjustedIndex(logEntryIndex);
+
+        if (adjustedIndex < 0 || adjustedIndex >= journal.size()) {
+            // physical index should be less than list size and >= 0
+            return null;
+        }
+
+        return journal.get(adjustedIndex);
+    }
+
+    @Override
+    public ReplicatedLogEntry last() {
+        if (journal.isEmpty()) {
+            return null;
+        }
+        // get the last entry directly from the physical index
+        return journal.get(journal.size() - 1);
+    }
+
+    @Override
+    public long lastIndex() {
+        if (journal.isEmpty()) {
+            // it can happen that after snapshot, all the entries of the
+            // journal are trimmed till lastApplied, so lastIndex = snapshotIndex
+            return snapshotIndex;
+        }
+        return last().getIndex();
+    }
+
+    @Override
+    public long lastTerm() {
+        if (journal.isEmpty()) {
+            // it can happen that after snapshot, all the entries of the
+            // journal are trimmed till lastApplied, so lastTerm = snapshotTerm
+            return snapshotTerm;
+        }
+        return last().getTerm();
+    }
+
+    @Override
+    public void removeFrom(long logEntryIndex) {
+        int adjustedIndex = adjustedIndex(logEntryIndex);
+        if (adjustedIndex < 0 || adjustedIndex >= journal.size()) {
+            // physical index should be less than list size and >= 0
+            return;
+        }
+        journal.subList(adjustedIndex , journal.size()).clear();
+    }
+
+    @Override
+    public void append(ReplicatedLogEntry replicatedLogEntry) {
+        journal.add(replicatedLogEntry);
+    }
+
+    @Override
+    public List<ReplicatedLogEntry> getFrom(long logEntryIndex) {
+        int adjustedIndex = adjustedIndex(logEntryIndex);
+        int size = journal.size();
+        List<ReplicatedLogEntry> entries = new ArrayList<>(100);
+        if (adjustedIndex >= 0 && adjustedIndex < size) {
+            // physical index should be less than list size and >= 0
+            entries.addAll(journal.subList(adjustedIndex, size));
+        }
+        return entries;
+    }
+
+    @Override
+    public long size() {
+       return journal.size();
+    }
+
+    @Override
+    public boolean isPresent(long logEntryIndex) {
+        if (logEntryIndex > lastIndex()) {
+            // if the request logical index is less than the last present in the list
+            return false;
+        }
+        int adjustedIndex = adjustedIndex(logEntryIndex);
+        return (adjustedIndex >= 0);
+    }
+
+    @Override
+    public boolean isInSnapshot(long logEntryIndex) {
+        return logEntryIndex <= snapshotIndex;
+    }
+
+    @Override
+    public Object getSnapshot() {
+        return snapshot;
+    }
+
+    @Override
+    public long getSnapshotIndex() {
+        return snapshotIndex;
+    }
+
+    @Override
+    public long getSnapshotTerm() {
+        return snapshotTerm;
+    }
+
+    @Override
+    public abstract void appendAndPersist(ReplicatedLogEntry replicatedLogEntry);
+
+    @Override
+    public abstract void removeFromAndPersist(long index);
+}
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
new file mode 100644 (file)
index 0000000..4c6434a
--- /dev/null
@@ -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.raft;
+
+import scala.concurrent.duration.FiniteDuration;
+
+/**
+ * Configuration Parameter interface for configuring the Raft consensus system
+ * <p/>
+ * Any component using this implementation might want to provide an implementation of
+ * this interface to configure
+ *
+ * A default implementation will be used if none is provided.
+ *
+ * @author Kamal Rameshan
+ */
+public interface ConfigParams {
+    /**
+     * The minimum number of entries to be present in the in-memory Raft log
+     * for a snapshot to be taken
+     *
+     * @return long
+     */
+    public long getSnapshotBatchCount();
+
+    /**
+     * The interval at which a heart beat message will be sent to the remote
+     * RaftActor
+     *
+     * @return FiniteDuration
+     */
+    public FiniteDuration getHeartBeatInterval();
+
+    /**
+     * The interval in which a new election would get triggered if no leader is found
+     *
+     * Normally its set to atleast twice the heart beat interval
+     *
+     * @return FiniteDuration
+     */
+    public FiniteDuration getElectionTimeOutInterval();
+
+    /**
+     * The maximum election time variance. The election is scheduled using both
+     * the Election Timeout and Variance
+     *
+     * @return int
+     */
+    public int getElectionTimeVariance();
+}
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
new file mode 100644 (file)
index 0000000..c633337
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * 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 scala.concurrent.duration.FiniteDuration;
+
+import java.util.concurrent.TimeUnit;
+
+/**
+ * Default implementation of the ConfigParams
+ *
+ * If no implementation is provided for ConfigParams, then this will be used.
+ */
+public class DefaultConfigParamsImpl implements ConfigParams {
+
+    private static final int SNAPSHOT_BATCH_COUNT = 100000;
+
+    /**
+     * The maximum election time variance
+     */
+    private static final int ELECTION_TIME_MAX_VARIANCE = 100;
+
+
+    /**
+     * The interval at which a heart beat message will be sent to the remote
+     * RaftActor
+     * <p/>
+     * Since this is set to 100 milliseconds the Election timeout should be
+     * at least 200 milliseconds
+     */
+    protected static final FiniteDuration HEART_BEAT_INTERVAL =
+        new FiniteDuration(100, TimeUnit.MILLISECONDS);
+
+
+    @Override
+    public long getSnapshotBatchCount() {
+        return SNAPSHOT_BATCH_COUNT;
+    }
+
+    @Override
+    public FiniteDuration getHeartBeatInterval() {
+        return HEART_BEAT_INTERVAL;
+    }
+
+
+    @Override
+    public FiniteDuration getElectionTimeOutInterval() {
+        // returns 2 times the heart beat interval
+        return HEART_BEAT_INTERVAL.$times(2);
+    }
+
+    @Override
+    public int getElectionTimeVariance() {
+        return ELECTION_TIME_MAX_VARIANCE;
+    }
+}
index b8e9653bc5db92ffa4cb15afd391c6a9ec05cd16..70b85b4627dc707b0223f8a7bdae37dfab1441f1 100644 (file)
@@ -22,6 +22,7 @@ import akka.persistence.UntypedPersistentActor;
 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.Replicate;
+import com.google.common.base.Optional;
 import org.opendaylight.controller.cluster.raft.behaviors.Candidate;
 import org.opendaylight.controller.cluster.raft.behaviors.Follower;
 import org.opendaylight.controller.cluster.raft.behaviors.Leader;
@@ -33,7 +34,6 @@ import org.opendaylight.controller.cluster.raft.client.messages.RemoveRaftPeer;
 import org.opendaylight.controller.cluster.raft.protobuff.client.messages.Payload;
 
 import java.io.Serializable;
-import java.util.ArrayList;
 import java.util.List;
 import java.util.Map;
 
@@ -100,14 +100,22 @@ public abstract class RaftActor extends UntypedPersistentActor {
 
 
     public RaftActor(String id, Map<String, String> peerAddresses) {
+        this(id, peerAddresses, Optional.<ConfigParams>absent());
+    }
+
+    public RaftActor(String id, Map<String, String> peerAddresses,
+         Optional<ConfigParams> configParams) {
+
         context = new RaftActorContextImpl(this.getSelf(),
-            this.getContext(),
-            id, new ElectionTermImpl(),
-            -1, -1, replicatedLog, peerAddresses, LOG);
+            this.getContext(), id, new ElectionTermImpl(),
+            -1, -1, replicatedLog, peerAddresses,
+            (configParams.isPresent() ? configParams.get(): new DefaultConfigParamsImpl()),
+            LOG);
     }
 
     @Override public void onReceiveRecover(Object message) {
         if (message instanceof SnapshotOffer) {
+            LOG.debug("SnapshotOffer called..");
             SnapshotOffer offer = (SnapshotOffer) message;
             Snapshot snapshot = (Snapshot) offer.snapshot();
 
@@ -116,6 +124,13 @@ public abstract class RaftActor extends UntypedPersistentActor {
             // when we need to install it on a peer
             replicatedLog = new ReplicatedLogImpl(snapshot);
 
+            context.setReplicatedLog(replicatedLog);
+
+            LOG.debug("Applied snapshot to replicatedLog. " +
+                "snapshotIndex={}, snapshotTerm={}, journal-size={}",
+                replicatedLog.snapshotIndex, replicatedLog.snapshotTerm,
+                replicatedLog.size());
+
             // Apply the snapshot to the actors state
             applySnapshot(snapshot.getState());
 
@@ -127,7 +142,11 @@ public abstract class RaftActor extends UntypedPersistentActor {
             context.getTermInformation().update(((UpdateElectionTerm) message).getCurrentTerm(), ((UpdateElectionTerm) message).getVotedFor());
         } else if (message instanceof RecoveryCompleted) {
             LOG.debug(
-                "Last index in log : " + replicatedLog.lastIndex());
+                "RecoveryCompleted - Switching actor to Follower - " +
+                    "Last index in log:{}, snapshotIndex={}, snapshotTerm={}, " +
+                    "journal-size={}",
+                replicatedLog.lastIndex(), replicatedLog.snapshotIndex,
+                replicatedLog.snapshotTerm, replicatedLog.size());
             currentBehavior = switchBehavior(RaftState.Follower);
         }
     }
@@ -191,6 +210,15 @@ public abstract class RaftActor extends UntypedPersistentActor {
         }
     }
 
+    public java.util.Set<String> getPeers() {
+        return context.getPeerAddresses().keySet();
+    }
+
+    protected String getReplicatedLogState() {
+        return "snapshotIndex=" + context.getReplicatedLog().getSnapshotIndex()
+            + ", snapshotTerm=" + context.getReplicatedLog().getSnapshotTerm()
+            + ", im-mem journal size=" + context.getReplicatedLog().size();
+    }
 
 
     /**
@@ -343,85 +371,33 @@ public abstract class RaftActor extends UntypedPersistentActor {
     }
 
     private void trimPersistentData(long sequenceNumber) {
-        // Trim snapshots
+        // Trim akka snapshots
         // FIXME : Not sure how exactly the SnapshotSelectionCriteria is applied
         // For now guessing that it is ANDed.
         deleteSnapshots(new SnapshotSelectionCriteria(
-            sequenceNumber - 100000, 43200000));
+            sequenceNumber - context.getConfigParams().getSnapshotBatchCount(), 43200000));
 
-        // Trim journal
+        // Trim akka journal
         deleteMessages(sequenceNumber);
     }
 
 
-    private class ReplicatedLogImpl implements ReplicatedLog {
-        private final List<ReplicatedLogEntry> journal;
-        private final Object snapshot;
-        private long snapshotIndex = -1;
-        private long snapshotTerm = -1;
+    private class ReplicatedLogImpl extends AbstractReplicatedLogImpl {
 
         public ReplicatedLogImpl(Snapshot snapshot) {
-            this.snapshot = snapshot.getState();
-            this.snapshotIndex = snapshot.getLastAppliedIndex();
-            this.snapshotTerm = snapshot.getLastAppliedTerm();
-
-            this.journal = new ArrayList<>(snapshot.getUnAppliedEntries());
+            super(snapshot.getState(),
+                snapshot.getLastAppliedIndex(), snapshot.getLastAppliedTerm(),
+                snapshot.getUnAppliedEntries());
         }
 
         public ReplicatedLogImpl() {
-            this.snapshot = null;
-            this.journal = new ArrayList<>();
+            super();
         }
 
-        @Override public ReplicatedLogEntry get(long index) {
-            int adjustedIndex = adjustedIndex(index);
+        @Override public void removeFromAndPersist(long logEntryIndex) {
+            int adjustedIndex = adjustedIndex(logEntryIndex);
 
-            if (adjustedIndex < 0 || adjustedIndex >= journal.size()) {
-                return null;
-            }
-
-            return journal.get(adjustedIndex);
-        }
-
-        @Override public ReplicatedLogEntry last() {
-            if (journal.size() == 0) {
-                return null;
-            }
-            return get(journal.size() - 1);
-        }
-
-        @Override public long lastIndex() {
-            if (journal.size() == 0) {
-                return -1;
-            }
-
-            return last().getIndex();
-        }
-
-        @Override public long lastTerm() {
-            if (journal.size() == 0) {
-                return -1;
-            }
-
-            return last().getTerm();
-        }
-
-
-        @Override public void removeFrom(long index) {
-            int adjustedIndex = adjustedIndex(index);
-
-            if (adjustedIndex < 0 || adjustedIndex >= journal.size()) {
-                return;
-            }
-
-            journal.subList(adjustedIndex , journal.size()).clear();
-        }
-
-
-        @Override public void removeFromAndPersist(long index) {
-            int adjustedIndex = adjustedIndex(index);
-
-            if (adjustedIndex < 0 || adjustedIndex >= journal.size()) {
+            if (adjustedIndex < 0) {
                 return;
             }
 
@@ -435,29 +411,6 @@ public abstract class RaftActor extends UntypedPersistentActor {
                     //FIXME : Doing nothing for now
                 }
             });
-
-
-        }
-
-        @Override public void append(
-            final ReplicatedLogEntry replicatedLogEntry) {
-            journal.add(replicatedLogEntry);
-        }
-
-        @Override public List<ReplicatedLogEntry> getFrom(long index) {
-            int adjustedIndex = adjustedIndex(index);
-
-            List<ReplicatedLogEntry> entries = new ArrayList<>(100);
-            if (adjustedIndex < 0 || adjustedIndex >= journal.size()) {
-                return entries;
-            }
-
-
-            for (int i = adjustedIndex;
-                 i < journal.size(); i++) {
-                entries.add(journal.get(i));
-            }
-            return entries;
         }
 
         @Override public void appendAndPersist(
@@ -482,20 +435,42 @@ public abstract class RaftActor extends UntypedPersistentActor {
                 new Procedure<ReplicatedLogEntry>() {
                     public void apply(ReplicatedLogEntry evt) throws Exception {
                         // FIXME : Tentatively create a snapshot every hundred thousand entries. To be tuned.
-                        if (size() > 100000) {
-                            ReplicatedLogEntry lastAppliedEntry =
-                                get(context.getLastApplied());
+                        if (journal.size() > context.getConfigParams().getSnapshotBatchCount()) {
+                            LOG.info("Initiating Snapshot Capture..");
                             long lastAppliedIndex = -1;
                             long lastAppliedTerm = -1;
+
+                            ReplicatedLogEntry lastAppliedEntry = get(context.getLastApplied());
                             if (lastAppliedEntry != null) {
                                 lastAppliedIndex = lastAppliedEntry.getIndex();
                                 lastAppliedTerm = lastAppliedEntry.getTerm();
                             }
 
-                            saveSnapshot(Snapshot.create(createSnapshot(),
+                            LOG.debug("Snapshot Capture logSize: {}", journal.size());
+                            LOG.debug("Snapshot Capture lastApplied:{} ", context.getLastApplied());
+                            LOG.debug("Snapshot Capture lastAppliedIndex:{}", lastAppliedIndex);
+                            LOG.debug("Snapshot Capture lastAppliedTerm:{}", lastAppliedTerm);
+
+                            // create a snapshot object from the state provided and save it
+                            // when snapshot is saved async, SaveSnapshotSuccess is raised.
+                            Snapshot sn = Snapshot.create(createSnapshot(),
                                 getFrom(context.getLastApplied() + 1),
                                 lastIndex(), lastTerm(), lastAppliedIndex,
-                                lastAppliedTerm));
+                                lastAppliedTerm);
+                            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,
+                            // TODO: damage-recovery to be done on failure
+                            journal.subList(0, (int) (lastAppliedIndex - snapshotIndex)).clear();
+                            snapshotIndex = lastAppliedIndex;
+                            snapshotTerm = lastAppliedTerm;
+
+                            LOG.info("Removed in-memory snapshotted entries, " +
+                                "adjusted snaphsotIndex:{}" +
+                                "and term:{}", snapshotIndex, lastAppliedTerm);
                         }
                         // Send message for replication
                         if (clientActor != null) {
@@ -509,46 +484,8 @@ public abstract class RaftActor extends UntypedPersistentActor {
             );
         }
 
-        @Override public long size() {
-            return journal.size() + snapshotIndex + 1;
-        }
-
-        @Override public boolean isPresent(long index) {
-            int adjustedIndex = adjustedIndex(index);
-
-            if (adjustedIndex < 0 || adjustedIndex >= journal.size()) {
-                return false;
-            }
-            return true;
-        }
-
-        @Override public boolean isInSnapshot(long index) {
-            return index <= snapshotIndex;
-        }
-
-        @Override public Object getSnapshot() {
-            return snapshot;
-        }
-
-        @Override public long getSnapshotIndex() {
-            return snapshotIndex;
-        }
-
-        @Override public long getSnapshotTerm() {
-            return snapshotTerm;
-        }
-
-        private int adjustedIndex(long index) {
-            if(snapshotIndex < 0){
-                return (int) index;
-            }
-            return (int) (index - snapshotIndex);
-        }
     }
 
-
-
-
     private static class DeleteEntries implements Serializable {
         private final int fromIndex;
 
@@ -609,6 +546,17 @@ public abstract class RaftActor extends UntypedPersistentActor {
         public long getLastAppliedTerm() {
             return lastAppliedTerm;
         }
+
+        public String getLogMessage() {
+            StringBuilder sb = new StringBuilder();
+            return sb.append("Snapshot={")
+                .append("lastTerm:" + this.getLastTerm()  + ", ")
+                .append("LastAppliedIndex:" + this.getLastAppliedIndex()  + ", ")
+                .append("LastAppliedTerm:" + this.getLastAppliedTerm()  + ", ")
+                .append("UnAppliedEntries size:" + this.getUnAppliedEntries().size()  + "}")
+                .toString();
+
+        }
     }
 
     private class ElectionTermImpl implements ElectionTerm {
index ae9431a43acf576f2769672b49d3ce234014e3c0..0eb4b7377976526ac48eaefa9a9922b6a70c0076 100644 (file)
@@ -85,6 +85,12 @@ public interface RaftActorContext {
      */
     void setLastApplied(long lastApplied);
 
+    /**
+     *
+     * @param replicatedLog
+     */
+    public void setReplicatedLog(ReplicatedLog replicatedLog);
+
     /**
      * @return A representation of the log
      */
@@ -155,4 +161,9 @@ public interface RaftActorContext {
      * @param peerAddress
      */
     void setPeerAddress(String peerId, String peerAddress);
+
+    /**
+     * @return ConfigParams
+     */
+    public ConfigParams getConfigParams();
 }
index 833c8a9e8ad1ca7b8fe170aadffc25b3c12b6b24..25da37105cea18e46270a4baccfdae9b459a2500 100644 (file)
@@ -19,7 +19,7 @@ import java.util.Map;
 
 import static com.google.common.base.Preconditions.checkState;
 
-public class RaftActorContextImpl implements RaftActorContext{
+public class RaftActorContextImpl implements RaftActorContext {
 
     private final ActorRef actor;
 
@@ -33,16 +33,20 @@ public class RaftActorContextImpl implements RaftActorContext{
 
     private long lastApplied;
 
-    private final ReplicatedLog replicatedLog;
+    private ReplicatedLog replicatedLog;
 
     private final Map<String, String> peerAddresses;
 
     private final LoggingAdapter LOG;
 
+    private final ConfigParams configParams;
+
     public RaftActorContextImpl(ActorRef actor, UntypedActorContext context,
         String id,
         ElectionTerm termInformation, long commitIndex,
-        long lastApplied, ReplicatedLog replicatedLog, Map<String, String> peerAddresses, LoggingAdapter logger) {
+        long lastApplied, ReplicatedLog replicatedLog,
+        Map<String, String> peerAddresses, ConfigParams configParams,
+        LoggingAdapter logger) {
         this.actor = actor;
         this.context = context;
         this.id = id;
@@ -51,6 +55,7 @@ public class RaftActorContextImpl implements RaftActorContext{
         this.lastApplied = lastApplied;
         this.replicatedLog = replicatedLog;
         this.peerAddresses = peerAddresses;
+        this.configParams = configParams;
         this.LOG = logger;
     }
 
@@ -90,6 +95,10 @@ public class RaftActorContextImpl implements RaftActorContext{
         this.lastApplied = lastApplied;
     }
 
+    @Override public void setReplicatedLog(ReplicatedLog replicatedLog) {
+        this.replicatedLog = replicatedLog;
+    }
+
     @Override public ReplicatedLog getReplicatedLog() {
         return replicatedLog;
     }
@@ -110,6 +119,10 @@ public class RaftActorContextImpl implements RaftActorContext{
         return peerAddresses.get(peerId);
     }
 
+    @Override public ConfigParams getConfigParams() {
+        return configParams;
+    }
+
     @Override public void addToPeers(String name, String address) {
         peerAddresses.put(name, address);
     }
index f7281bb8e3967c3ca2be583adb35210cbd07e87b..0a553b40fd59aab555f258f897a2154830afd1c8 100644 (file)
@@ -43,27 +43,6 @@ public abstract class AbstractRaftActorBehavior implements RaftActorBehavior {
      */
     protected final RaftActorContext context;
 
-    /**
-     * The maximum election time variance
-     */
-    private static final int ELECTION_TIME_MAX_VARIANCE = 100;
-
-    /**
-     * The interval at which a heart beat message will be sent to the remote
-     * RaftActor
-     * <p/>
-     * Since this is set to 100 milliseconds the Election timeout should be
-     * at least 200 milliseconds
-     */
-    protected static final FiniteDuration HEART_BEAT_INTERVAL =
-        new FiniteDuration(100, TimeUnit.MILLISECONDS);
-
-    /**
-     * The interval in which a new election would get triggered if no leader is found
-     */
-    private static final long ELECTION_TIME_INTERVAL =
-        HEART_BEAT_INTERVAL.toMillis() * 2;
-
     /**
      *
      */
@@ -208,9 +187,9 @@ public abstract class AbstractRaftActorBehavior implements RaftActorBehavior {
      * @return
      */
     protected FiniteDuration electionDuration() {
-        long variance = new Random().nextInt(ELECTION_TIME_MAX_VARIANCE);
-        return new FiniteDuration(ELECTION_TIME_INTERVAL + variance,
-            TimeUnit.MILLISECONDS);
+        long variance = new Random().nextInt(context.getConfigParams().getElectionTimeVariance());
+        return context.getConfigParams().getElectionTimeOutInterval().$plus(
+            new FiniteDuration(variance, TimeUnit.MILLISECONDS));
     }
 
     /**
index db62dfc2ac1cd4f10c59849c0666b9291ca946a3..c8cd41dfa1883a1c7d1d43d2f7697b0ff988ab38 100644 (file)
@@ -126,15 +126,10 @@ public class Follower extends AbstractRaftActorBehavior {
             int addEntriesFrom = 0;
             if (context.getReplicatedLog().size() > 0) {
 
-                // Find the entry up until which the one that is not in the
-                // follower's log
-                for (int i = 0;
-                     i < appendEntries.getEntries()
-                         .size(); i++, addEntriesFrom++) {
-                    ReplicatedLogEntry matchEntry =
-                        appendEntries.getEntries().get(i);
-                    ReplicatedLogEntry newEntry = context.getReplicatedLog()
-                        .get(matchEntry.getIndex());
+                // Find the entry up until which the one that is not in the follower's log
+                for (int i = 0;i < appendEntries.getEntries().size(); i++, addEntriesFrom++) {
+                    ReplicatedLogEntry matchEntry = appendEntries.getEntries().get(i);
+                    ReplicatedLogEntry newEntry = context.getReplicatedLog().get(matchEntry.getIndex());
 
                     if (newEntry == null) {
                         //newEntry not found in the log
index 53e47c2f842f17ac0b2766811745a7f1ec6eabde..2a44e8b7a5c3adeecd1c534de0664d8deb290934 100644 (file)
@@ -112,8 +112,8 @@ public class Leader extends AbstractRaftActorBehavior {
         scheduleHeartBeat(new FiniteDuration(0, TimeUnit.SECONDS));
 
         scheduleInstallSnapshotCheck(
-            new FiniteDuration(HEART_BEAT_INTERVAL.length() * 1000,
-                HEART_BEAT_INTERVAL.unit())
+            new FiniteDuration(context.getConfigParams().getHeartBeatInterval().length() * 1000,
+                context.getConfigParams().getHeartBeatInterval().unit())
         );
 
     }
@@ -241,7 +241,7 @@ public class Leader extends AbstractRaftActorBehavior {
                     (InstallSnapshotReply) message);
             }
         } finally {
-            scheduleHeartBeat(HEART_BEAT_INTERVAL);
+            scheduleHeartBeat(context.getConfigParams().getHeartBeatInterval());
         }
 
         return super.handleMessage(sender, message);
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
new file mode 100644 (file)
index 0000000..ae8e525
--- /dev/null
@@ -0,0 +1,153 @@
+/*
+ * 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 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;
+/**
+*
+*/
+public class AbstractReplicatedLogImplTest {
+
+    private MockAbstractReplicatedLogImpl replicatedLogImpl;
+
+    @Before
+    public void setUp() {
+        replicatedLogImpl = new MockAbstractReplicatedLogImpl();
+    }
+
+    @After
+    public void tearDown() {
+        replicatedLogImpl.journal.clear();
+        replicatedLogImpl.setSnapshotIndex(-1);
+        replicatedLogImpl.setSnapshotTerm(-1);
+        replicatedLogImpl = null;
+    }
+
+    @Test
+    public void testIndexOperations() {
+        // create a set of initial entries in the in-memory log
+        replicatedLogImpl.append(new MockReplicatedLogEntry(1, 0, new MockPayload("A")));
+        replicatedLogImpl.append(new MockReplicatedLogEntry(1, 1, new MockPayload("B")));
+        replicatedLogImpl.append(new MockReplicatedLogEntry(1, 2, new MockPayload("C")));
+        replicatedLogImpl.append(new MockReplicatedLogEntry(2, 3, new MockPayload("D")));
+
+        // check if the values returned are correct, with snapshotIndex = -1
+        assertEquals("B", replicatedLogImpl.get(1).getData().toString());
+        assertEquals("D", replicatedLogImpl.last().getData().toString());
+        assertEquals(3, replicatedLogImpl.lastIndex());
+        assertEquals(2, replicatedLogImpl.lastTerm());
+        assertEquals(2, replicatedLogImpl.getFrom(2).size());
+        assertEquals(4, replicatedLogImpl.size());
+        assertTrue(replicatedLogImpl.isPresent(2));
+        assertFalse(replicatedLogImpl.isPresent(4));
+        assertFalse(replicatedLogImpl.isInSnapshot(2));
+
+        // 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);
+
+        // check the values after the snapshot.
+        // each index value passed in the test is the logical index (log entry index)
+        // which gets mapped to the list's physical index
+        assertEquals("D", replicatedLogImpl.get(3).getData().toString());
+        assertEquals("D", replicatedLogImpl.last().getData().toString());
+        assertNull(replicatedLogImpl.get(1));
+        assertEquals(3, replicatedLogImpl.lastIndex());
+        assertEquals(2, replicatedLogImpl.lastTerm());
+        assertEquals(0, replicatedLogImpl.getFrom(2).size());
+        assertEquals(1, replicatedLogImpl.size());
+        assertFalse(replicatedLogImpl.isPresent(2));
+        assertTrue(replicatedLogImpl.isPresent(3));
+        assertFalse(replicatedLogImpl.isPresent(4));
+        assertTrue(replicatedLogImpl.isInSnapshot(2));
+
+        // append few more entries
+        replicatedLogImpl.append(new MockReplicatedLogEntry(2, 4, new MockPayload("E")));
+        replicatedLogImpl.append(new MockReplicatedLogEntry(2, 5, new MockPayload("F")));
+        replicatedLogImpl.append(new MockReplicatedLogEntry(3, 6, new MockPayload("G")));
+        replicatedLogImpl.append(new MockReplicatedLogEntry(3, 7, new MockPayload("H")));
+
+        // check their values as well
+        assertEquals(5, replicatedLogImpl.size());
+        assertEquals("D", replicatedLogImpl.get(3).getData().toString());
+        assertEquals("E", replicatedLogImpl.get(4).getData().toString());
+        assertEquals("H", replicatedLogImpl.last().getData().toString());
+        assertEquals(3, replicatedLogImpl.lastTerm());
+        assertEquals(7, replicatedLogImpl.lastIndex());
+        assertTrue(replicatedLogImpl.isPresent(7));
+        assertFalse(replicatedLogImpl.isInSnapshot(7));
+        assertEquals(1, replicatedLogImpl.getFrom(7).size());
+        assertEquals(2, replicatedLogImpl.getFrom(6).size());
+
+        // take a second snapshot with 5 entries with 0 unapplied entries left in the log
+        state = takeSnapshot(5);
+
+        assertEquals(0, replicatedLogImpl.size());
+        assertNull(replicatedLogImpl.last());
+        assertNull(replicatedLogImpl.get(7));
+        assertNull(replicatedLogImpl.get(1));
+        assertFalse(replicatedLogImpl.isPresent(7));
+        assertTrue(replicatedLogImpl.isInSnapshot(7));
+        assertEquals(0, replicatedLogImpl.getFrom(7).size());
+        assertEquals(0, replicatedLogImpl.getFrom(6).size());
+
+    }
+
+    // create a snapshot for test
+    public Map takeSnapshot(int numEntries) {
+        Map map = new HashMap(numEntries);
+        List<ReplicatedLogEntry> entries = replicatedLogImpl.getEntriesTill(numEntries);
+        for (ReplicatedLogEntry entry : entries) {
+            map.put(entry.getIndex(), entry.getData().toString());
+        }
+
+        int term = (int) replicatedLogImpl.lastTerm();
+        int lastIndex = (int) entries.get(entries.size() - 1).getIndex();
+        entries.clear();
+        replicatedLogImpl.setSnapshotTerm(term);
+        replicatedLogImpl.setSnapshotIndex(lastIndex);
+
+        return map;
+
+    }
+    class MockAbstractReplicatedLogImpl extends AbstractReplicatedLogImpl {
+        @Override
+        public void appendAndPersist(ReplicatedLogEntry replicatedLogEntry) {
+        }
+
+        @Override
+        public void removeFromAndPersist(long index) {
+        }
+
+        public void setSnapshotIndex(long snapshotIndex) {
+            this.snapshotIndex = snapshotIndex;
+        }
+
+        public void setSnapshotTerm(long snapshotTerm) {
+            this.snapshotTerm = snapshotTerm;
+        }
+
+        public List<ReplicatedLogEntry> getEntriesTill(int index) {
+            return journal.subList(0, index);
+        }
+    }
+}
index 2e200cba275d9d4265f56da69ee36e61acd0db76..aa50fa7442b1f54ed026c5e2b95ff4c52270ea86 100644 (file)
@@ -177,7 +177,10 @@ public class MockRaftActorContext implements RaftActorContext {
         this.peerAddresses = peerAddresses;
     }
 
-
+    @Override
+    public ConfigParams getConfigParams() {
+        return new DefaultConfigParamsImpl();
+    }
 
     public static class SimpleReplicatedLog implements ReplicatedLog {
         private final List<ReplicatedLogEntry> log = new ArrayList<>();
index 823a4d9f322fe0b76726e7773bea0267132d45a5..b0c2d742e214046be839cca263dbc0652005aa9b 100644 (file)
@@ -23,7 +23,7 @@ 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.SchemaServiceListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.ServiceReference;
 import org.slf4j.Logger;
@@ -74,7 +74,7 @@ public final class RuntimeMappingModule extends
         }
 
         final RuntimeGeneratedMappingServiceImpl service = new RuntimeGeneratedMappingServiceImpl(SingletonHolder.CLASS_POOL);
-        bundleContext.registerService(SchemaServiceListener.class, service, new Hashtable<String,String>());
+        bundleContext.registerService(SchemaContextListener.class, service, new Hashtable<String,String>());
         return service;
     }
 
index 15e4a466cf688d67154d8a504cca0c5383d7feea..2d81b6022d35af1c70fba4adb269ffc2d8c93dce 100644 (file)
@@ -41,7 +41,6 @@ import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMapping
 import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -58,14 +57,14 @@ public abstract class AbstractForwardedDataBroker implements Delegator<DOMDataBr
     private final BindingToNormalizedNodeCodec codec;
     private BindingIndependentConnector connector;
     private ProviderSession context;
-    private final ListenerRegistration<SchemaServiceListener> schemaListenerRegistration;
+    private final ListenerRegistration<SchemaContextListener> schemaListenerRegistration;
 
     protected AbstractForwardedDataBroker(final DOMDataBroker domDataBroker,
             final BindingIndependentMappingService mappingService,final SchemaService schemaService) {
         this.domDataBroker = domDataBroker;
         this.mappingService = mappingService;
         this.codec = new BindingToNormalizedNodeCodec(mappingService);
-        this.schemaListenerRegistration = schemaService.registerSchemaServiceListener(this);
+        this.schemaListenerRegistration = schemaService.registerSchemaContextListener(this);
     }
 
     protected BindingToNormalizedNodeCodec getCodec() {
index df09f78620a11bcce20f04034e6a7b7cf144780f..05651bfabe5c521d66c25a219fb096b5d9ef0ecb 100644 (file)
@@ -9,6 +9,7 @@ package org.opendaylight.controller.sal.binding.impl;
 
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.Executors;
 
 import org.opendaylight.controller.md.sal.binding.util.AbstractBindingSalProviderInstance;
 import org.opendaylight.controller.sal.binding.api.mount.MountProviderInstance;
@@ -20,6 +21,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
 
 public class MountPointManagerImpl implements MountProviderService {
 
@@ -82,7 +84,7 @@ public class MountPointManagerImpl implements MountProviderService {
         RpcProviderRegistryImpl rpcRegistry = new RpcProviderRegistryImpl("mount");
         NotificationBrokerImpl notificationBroker = new NotificationBrokerImpl(getNotificationExecutor());
         DataBrokerImpl dataBroker = new DataBrokerImpl();
-        dataBroker.setExecutor(getDataCommitExecutor());
+        dataBroker.setExecutor(MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()));
         BindingMountPointImpl mountInstance = new BindingMountPointImpl(path, rpcRegistry, notificationBroker,
                 dataBroker);
         mountPoints.putIfAbsent(path, mountInstance);
diff --git a/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/test/Bug1333DataChangeListenerTest.java b/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/test/Bug1333DataChangeListenerTest.java
new file mode 100644 (file)
index 0000000..60d56db
--- /dev/null
@@ -0,0 +1,145 @@
+/*
+ * 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.binding.impl.test;
+
+import static org.opendaylight.controller.md.sal.binding.test.AssertCollections.assertContains;
+import static org.opendaylight.controller.md.sal.binding.test.AssertCollections.assertEmpty;
+import static org.opendaylight.controller.md.sal.binding.test.AssertCollections.assertNotContains;
+import static org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType.CONFIGURATION;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.TOP_FOO_KEY;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.USES_ONE_KEY;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.USES_TWO_KEY;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.complexUsesAugment;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.path;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.top;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.topLevelList;
+
+import org.junit.Test;
+import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
+import org.opendaylight.controller.md.sal.binding.test.AbstractDataChangeListenerTest;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.TreeComplexUsesAugment;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.Top;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelList;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+/**
+ *
+ * This testsuite tries to replicate bug 1333 and tests regresion of it
+ * using test-model with similar construction as one reported.
+ *
+ *
+ * See  https://bugs.opendaylight.org/show_bug.cgi?id=1333 for Bug Description
+ *
+ */
+public class Bug1333DataChangeListenerTest extends AbstractDataChangeListenerTest{
+
+    private static final InstanceIdentifier<Top> TOP_PATH = InstanceIdentifier.create(Top.class);
+
+    private static final InstanceIdentifier<?> AUGMENT_WILDCARD = TOP_PATH.child(TopLevelList.class).augmentation(
+            TreeComplexUsesAugment.class);
+
+    public void writeTopWithListItem(final LogicalDatastoreType store) {
+        ReadWriteTransaction tx = getDataBroker().newReadWriteTransaction();
+        Top topItem = top(topLevelList(TOP_FOO_KEY, complexUsesAugment(USES_ONE_KEY, USES_TWO_KEY)));
+        tx.put(store, TOP_PATH, topItem);
+        assertCommit(tx.submit());
+    }
+
+    public void deleteItem(final LogicalDatastoreType store, final InstanceIdentifier<?> path) {
+        ReadWriteTransaction tx = getDataBroker().newReadWriteTransaction();
+        tx.delete(store, path);
+        assertCommit(tx.submit());
+    }
+
+    @Test
+    public void writeTopWithListItemAugmentedListenTopSubtree() {
+        TestListener listener = createListener(CONFIGURATION,TOP_PATH, DataChangeScope.SUBTREE);
+        listener.startCapture();
+
+        writeTopWithListItem(CONFIGURATION);
+
+        AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> event = listener.event();
+
+        assertContains(event.getCreatedData(), TOP_PATH);
+        assertContains(event.getCreatedData(), path(TOP_FOO_KEY));
+        assertContains(event.getCreatedData(), path(TOP_FOO_KEY, TreeComplexUsesAugment.class));
+        assertContains(event.getCreatedData(), path(TOP_FOO_KEY, USES_ONE_KEY));
+        assertContains(event.getCreatedData(), path(TOP_FOO_KEY, USES_TWO_KEY));
+
+        assertEmpty(event.getUpdatedData());
+        assertEmpty(event.getRemovedPaths());
+    }
+
+    @Test
+    public void writeTopWithListItemAugmentedListenAugmentSubtreeWildcarded() {
+        TestListener listener = createListener(CONFIGURATION,AUGMENT_WILDCARD, DataChangeScope.SUBTREE);
+        listener.startCapture();
+        writeTopWithListItem(CONFIGURATION);
+
+        AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> event = listener.event();
+
+        /*
+         * Event should not contain parent nodes
+         */
+        assertNotContains(event.getCreatedData(), TOP_PATH, path(TOP_FOO_KEY));
+
+        assertContains(event.getCreatedData(), path(TOP_FOO_KEY, TreeComplexUsesAugment.class));
+        assertContains(event.getCreatedData(), path(TOP_FOO_KEY, USES_ONE_KEY));
+        assertContains(event.getCreatedData(), path(TOP_FOO_KEY, USES_TWO_KEY));
+
+        assertEmpty(event.getUpdatedData());
+        assertEmpty(event.getRemovedPaths());
+    }
+
+    @Test
+    public void deleteAugmentChildListenTopSubtree() {
+        writeTopWithListItem(CONFIGURATION);
+        TestListener listener = createListener(CONFIGURATION, TOP_PATH, DataChangeScope.SUBTREE);
+        InstanceIdentifier<?> deletePath = path(TOP_FOO_KEY,USES_ONE_KEY);
+        deleteItem(CONFIGURATION,deletePath);
+
+        AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> event = listener.event();
+
+
+        assertEmpty(event.getCreatedData());
+
+        assertContains(event.getRemovedPaths(), deletePath);
+
+        assertContains(event.getUpdatedData(), TOP_PATH);
+        assertContains(event.getUpdatedData(), path(TOP_FOO_KEY));
+        assertContains(event.getUpdatedData(), path(TOP_FOO_KEY, TreeComplexUsesAugment.class));
+
+        assertNotContains(event.getCreatedData(), path(TOP_FOO_KEY, USES_TWO_KEY));
+    }
+
+    @Test
+    public void deleteAugmentChildListenAugmentSubtreeWildcarded() {
+        writeTopWithListItem(CONFIGURATION);
+
+        TestListener listener = createListener(CONFIGURATION, AUGMENT_WILDCARD, DataChangeScope.SUBTREE);
+        InstanceIdentifier<?> deletePath = path(TOP_FOO_KEY,USES_ONE_KEY);
+        deleteItem(CONFIGURATION,deletePath);
+        AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> event = listener.event();
+
+        assertEmpty(event.getCreatedData());
+
+        assertContains(event.getUpdatedData(), path(TOP_FOO_KEY, TreeComplexUsesAugment.class));
+
+        /*
+         * Event should not contain parent nodes
+         */
+        assertNotContains(event.getUpdatedData(), TOP_PATH, path(TOP_FOO_KEY));
+
+        assertContains(event.getRemovedPaths(), deletePath);
+    }
+
+}
index 79aa6b634b8b91136c2b7177992fcc028326ce6c..e0f6f3546f528a2e72621447b8110dc9e377be71 100644 (file)
@@ -47,13 +47,13 @@ public class DataBrokerTestCustomizer {
 
     public DOMStore createConfigurationDatastore() {
         InMemoryDOMDataStore store = new InMemoryDOMDataStore("CFG", MoreExecutors.sameThreadExecutor());
-        schemaService.registerSchemaServiceListener(store);
+        schemaService.registerSchemaContextListener(store);
         return store;
     }
 
     public DOMStore createOperationalDatastore() {
         InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER", MoreExecutors.sameThreadExecutor());
-        schemaService.registerSchemaServiceListener(store);
+        schemaService.registerSchemaContextListener(store);
         return store;
     }
 
index e82c9d385d6592c55982f5a5e59fc3a5249ee749..deb4a8aecacfbcffe47a2cee869c7d117c68f801 100644 (file)
@@ -144,8 +144,8 @@ public class BindingTestContext implements AutoCloseable {
 
         biCompatibleBroker = new BackwardsCompatibleDataBroker(newDOMDataBroker,mockSchemaService);
 
-        mockSchemaService.registerSchemaServiceListener(configStore);
-        mockSchemaService.registerSchemaServiceListener(operStore);
+        mockSchemaService.registerSchemaContextListener(configStore);
+        mockSchemaService.registerSchemaContextListener(operStore);
         biDataLegacyBroker = biCompatibleBroker;
     }
 
@@ -246,7 +246,7 @@ public class BindingTestContext implements AutoCloseable {
     public void startBindingToDomMappingService() {
         checkState(classPool != null, "ClassPool needs to be present");
         mappingServiceImpl = new RuntimeGeneratedMappingServiceImpl(classPool);
-        mockSchemaService.registerSchemaServiceListener(mappingServiceImpl);
+        mockSchemaService.registerSchemaContextListener(mappingServiceImpl);
     }
 
     private void updateYangSchema(final ImmutableSet<YangModuleInfo> moduleInfos) {
index c8acbcd994352d80c85d51c15035fb706af9251d..63a4ffb23a3930d4830ea3e300c168578172c39c 100644 (file)
@@ -13,14 +13,14 @@ import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.concepts.util.ListenerRegistry;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
 
 @SuppressWarnings("deprecation")
 public final class MockSchemaService implements SchemaService, SchemaContextProvider {
 
     private SchemaContext schemaContext;
 
-    ListenerRegistry<SchemaServiceListener> listeners = ListenerRegistry.create();
+    ListenerRegistry<SchemaContextListener> listeners = ListenerRegistry.create();
 
     @Override
     public void addModule(final Module module) {
@@ -38,8 +38,8 @@ public final class MockSchemaService implements SchemaService, SchemaContextProv
     }
 
     @Override
-    public ListenerRegistration<SchemaServiceListener> registerSchemaServiceListener(
-            final SchemaServiceListener listener) {
+    public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(
+            final SchemaContextListener listener) {
         return listeners.register(listener);
     }
 
@@ -55,8 +55,8 @@ public final class MockSchemaService implements SchemaService, SchemaContextProv
 
     public synchronized void changeSchema(final SchemaContext newContext) {
         schemaContext = newContext;
-        for (ListenerRegistration<SchemaServiceListener> listener : listeners) {
+        for (ListenerRegistration<SchemaContextListener> listener : listeners) {
             listener.getInstance().onGlobalContextUpdated(schemaContext);
         }
     }
-}
\ No newline at end of file
+}
index 692d1b4954007b33e285b271ebb61952f0bcb0ed..6d87271f00d54fcdbf6ca70c27843248b0bbc1b9 100644 (file)
@@ -20,7 +20,7 @@ public class DistributedDataStoreFactory {
             new DistributedDataStore(actorSystem, name, new ClusterWrapperImpl(actorSystem),config );
        ShardStrategyFactory.setConfiguration(config);
         schemaService
-            .registerSchemaServiceListener(dataStore);
+            .registerSchemaContextListener(dataStore);
         return dataStore;
 
     }
index 57df20172d59b6008c691617363788d4b64e7d23..6860872b75fddaf0c952af3943a8713f977531f5 100644 (file)
@@ -8,6 +8,7 @@
 
 package org.opendaylight.controller.md.cluster.datastore.model;
 
+import java.math.BigInteger;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
@@ -42,14 +43,14 @@ public class CarsModel {
         MapEntryNode altima =
             ImmutableNodes.mapEntryBuilder(CAR_QNAME, CAR_NAME_QNAME, "altima")
                 .withChild(ImmutableNodes.leafNode(CAR_NAME_QNAME, "altima"))
-                .withChild(ImmutableNodes.leafNode(CAR_PRICE_QNAME, 1000))
+                .withChild(ImmutableNodes.leafNode(CAR_PRICE_QNAME, new BigInteger("1000")))
                 .build();
 
         // Create an entry for the car accord
         MapEntryNode honda =
             ImmutableNodes.mapEntryBuilder(CAR_QNAME, CAR_NAME_QNAME, "accord")
                 .withChild(ImmutableNodes.leafNode(CAR_NAME_QNAME, "accord"))
-                .withChild(ImmutableNodes.leafNode(CAR_PRICE_QNAME, 2000))
+                .withChild(ImmutableNodes.leafNode(CAR_PRICE_QNAME, new BigInteger("2000")))
                 .build();
 
         cars.withChild(altima);
index 1b4020af438c356a3b07b01ded9c179d02a7bdc1..e637920e7855c9859ee9cab249f31b20766e9ef2 100644 (file)
@@ -42,14 +42,14 @@ public class PeopleModel {
         MapEntryNode jack =
             ImmutableNodes.mapEntryBuilder(PERSON_QNAME, PERSON_NAME_QNAME, "jack")
                 .withChild(ImmutableNodes.leafNode(PERSON_NAME_QNAME, "jack"))
-                .withChild(ImmutableNodes.leafNode(PERSON_AGE_QNAME, 100))
+                .withChild(ImmutableNodes.leafNode(PERSON_AGE_QNAME, 100L))
                 .build();
 
         // Create an entry for the person jill
         MapEntryNode jill =
             ImmutableNodes.mapEntryBuilder(PERSON_QNAME, PERSON_NAME_QNAME, "jill")
                 .withChild(ImmutableNodes.leafNode(PERSON_NAME_QNAME, "jill"))
-                .withChild(ImmutableNodes.leafNode(PERSON_AGE_QNAME, 200))
+                .withChild(ImmutableNodes.leafNode(PERSON_AGE_QNAME, 200L))
                 .build();
 
         cars.withChild(jack);
index d8fefcd986cc8033d6530622039c5e0ce005114f..be8713c7020c5848e7eec03278a95a9794a095ad 100644 (file)
@@ -18,45 +18,45 @@ import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 public class SampleModelsTest {
     @Test
     public void testPeopleModel(){
-        NormalizedNode<?, ?> expected = PeopleModel.create();
+        final NormalizedNode<?, ?> expected = PeopleModel.create();
 
 
-        NormalizedNodeMessages.Container node =
+        final NormalizedNodeMessages.Container node =
             new NormalizedNodeToNodeCodec(SchemaContextHelper.full())
                 .encode(YangInstanceIdentifier.of(PeopleModel.BASE_QNAME),
                     expected);
 
-        NormalizedNodeMessages.Node normalizedNode =
+        final NormalizedNodeMessages.Node normalizedNode =
             node.getNormalizedNode();
 
-        NormalizedNode<?,?> actual = new NormalizedNodeToNodeCodec(SchemaContextHelper.full()).decode(YangInstanceIdentifier.of(PeopleModel.BASE_QNAME),
+        final NormalizedNode<?,?> actual = new NormalizedNodeToNodeCodec(SchemaContextHelper.full()).decode(YangInstanceIdentifier.of(PeopleModel.BASE_QNAME),
             normalizedNode);
 
 
-        Assert.assertEquals(expected.toString(), actual.toString());
+        Assert.assertEquals(expected, actual);
 
     }
 
 
     @Test
     public void testCarsModel(){
-        NormalizedNode<?, ?> expected = CarsModel.create();
+        final NormalizedNode<?, ?> expected = CarsModel.create();
 
 
-        NormalizedNodeMessages.Container node =
+        final NormalizedNodeMessages.Container node =
             new NormalizedNodeToNodeCodec(SchemaContextHelper.full())
                 .encode(YangInstanceIdentifier.of(CarsModel.BASE_QNAME),
                     expected);
 
-        NormalizedNodeMessages.Node normalizedNode =
+        final NormalizedNodeMessages.Node normalizedNode =
             node.getNormalizedNode();
 
-        NormalizedNode<?,?> actual = new NormalizedNodeToNodeCodec(SchemaContextHelper.full()).decode(
+        final NormalizedNode<?,?> actual = new NormalizedNodeToNodeCodec(SchemaContextHelper.full()).decode(
             YangInstanceIdentifier.of(CarsModel.BASE_QNAME),
             normalizedNode);
 
 
-        Assert.assertEquals(expected.toString(), actual.toString());
+        Assert.assertEquals(expected, actual);
 
     }
 }
index 34e5b1b8033d2cbda100b1fe6b0552af983abee3..c3e979c536b268c4a6156b7241e745f328569618 100644 (file)
@@ -11,7 +11,7 @@ import org.opendaylight.controller.sal.core.api.BrokerService;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
 
 public interface SchemaService extends BrokerService {
 
@@ -42,5 +42,11 @@ public interface SchemaService extends BrokerService {
      */
     SchemaContext getGlobalContext();
 
-    ListenerRegistration<SchemaServiceListener> registerSchemaServiceListener(SchemaServiceListener listener);
+    /**
+     * Register a listener for changes in schema context.
+     *
+     * @param listener Listener which should be registered
+     * @return Listener registration handle
+     */
+    ListenerRegistration<SchemaContextListener> registerSchemaContextListener(SchemaContextListener listener);
 }
index 17b78f4ebd0e6602532f4fd7f5869d184d8125ba..f1f16cd635ba9ab336eb286ba3e8593c51dc2c50 100644 (file)
@@ -91,7 +91,7 @@ public final class DomBrokerImplModule extends org.opendaylight.controller.confi
         wrappedStore.changeDelegate(legacyStore);
         wrappedStore.setValidationEnabled(false);
 
-        schemaService.registerSchemaServiceListener(wrappedStore);
+        schemaService.registerSchemaContextListener(wrappedStore);
 
         dataService.registerConfigurationReader(rootPath, wrappedStore);
         dataService.registerCommitHandler(rootPath, wrappedStore);
index 69b17ee3c48aeb5aae64dc8c4b02e36abdfce7a7..667c0fc2826a100b2fc6ae77f4c0344a52d723f6 100644 (file)
@@ -50,7 +50,7 @@ public final class DomInmemoryDataBrokerModule extends
            //we will default to InMemoryDOMDataStore creation
           operStore = new InMemoryDOMDataStore("DOM-OPER", storeExecutor);
           //here we will register the SchemaContext listener
-          getSchemaServiceDependency().registerSchemaServiceListener((InMemoryDOMDataStore)operStore);
+          getSchemaServiceDependency().registerSchemaContextListener((InMemoryDOMDataStore)operStore);
         }
 
         DOMStore configStore = getConfigDataStoreDependency();
@@ -58,7 +58,7 @@ public final class DomInmemoryDataBrokerModule extends
            //we will default to InMemoryDOMDataStore creation
            configStore = new InMemoryDOMDataStore("DOM-CFG", storeExecutor);
           //here we will register the SchemaContext listener
-          getSchemaServiceDependency().registerSchemaServiceListener((InMemoryDOMDataStore)configStore);
+          getSchemaServiceDependency().registerSchemaContextListener((InMemoryDOMDataStore)configStore);
         }
         ImmutableMap<LogicalDatastoreType, DOMStore> datastores = ImmutableMap
                 .<LogicalDatastoreType, DOMStore> builder().put(LogicalDatastoreType.OPERATIONAL, operStore)
index fbc418dc2aec0203d4f52ad6b7ace8cc083ca019..62b026430ac07756bb21d2a90095a4c73ce6229a 100644 (file)
@@ -13,7 +13,7 @@ import org.opendaylight.yangtools.concepts.Delegator;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
 import org.osgi.framework.BundleContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -90,8 +90,8 @@ org.opendaylight.controller.config.yang.md.sal.dom.impl.AbstractSchemaServiceImp
         }
 
         @Override
-        public ListenerRegistration<SchemaServiceListener> registerSchemaServiceListener(final SchemaServiceListener arg0) {
-            return delegate.registerSchemaServiceListener(arg0);
+        public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener arg0) {
+            return delegate.registerSchemaContextListener(arg0);
         }
 
         @Override
index e8f8da53c90dd7ff1cafd2f96f50cc2072a5c432..dc122cfdc24d672f9bcf563e26501a57b79bbad4 100644 (file)
@@ -1,3 +1,10 @@
+/*
+ * 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.broker.impl.compat;
 
 import javax.annotation.concurrent.ThreadSafe;
@@ -21,18 +28,17 @@ import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
 
 @ThreadSafe
 public class BackwardsCompatibleDataBroker implements DataProviderService {
 
     private final DOMDataBroker backingBroker;
     private volatile DataNormalizer normalizer;
-    private final ListenerRegistration<SchemaServiceListener> schemaReg;
+    private final ListenerRegistration<SchemaContextListener> schemaReg;
 
     public BackwardsCompatibleDataBroker(final DOMDataBroker newBiDataImpl, final SchemaService schemaService) {
         backingBroker = newBiDataImpl;
-        schemaReg = schemaService.registerSchemaServiceListener(new SchemaListener());
+        schemaReg = schemaService.registerSchemaContextListener(new SchemaListener());
     }
 
     @Override
index d837d75ddc09aecef00a9d2dc7fc78e5be89890c..61ea47e39b79cc681292c4ab656bc846db9ce2fa 100644 (file)
@@ -72,7 +72,7 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgum
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
 
 public class BackwardsCompatibleMountPoint implements MountProvisionInstance, SchemaContextProvider, SchemaService {
 
@@ -83,7 +83,7 @@ public class BackwardsCompatibleMountPoint implements MountProvisionInstance, Sc
     private final NotificationPublishService notificationPublishService;
     private final RpcProvisionRegistry rpcs;
 
-    private final ListenerRegistry<SchemaServiceListener> schemaListenerRegistry = new ListenerRegistry<>();
+    private final ListenerRegistry<SchemaContextListener> schemaListenerRegistry = new ListenerRegistry<>();
 
     private SchemaContext schemaContext;
 
@@ -154,7 +154,7 @@ public class BackwardsCompatibleMountPoint implements MountProvisionInstance, Sc
     }
 
     @Override
-    public ListenerRegistration<SchemaServiceListener> registerSchemaServiceListener(final SchemaServiceListener listener) {
+    public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
         return schemaListenerRegistry.register(listener);
     }
 
@@ -275,7 +275,7 @@ public class BackwardsCompatibleMountPoint implements MountProvisionInstance, Sc
     @Override
     public void setSchemaContext(final SchemaContext schemaContext) {
         this.schemaContext = schemaContext;
-        for (ListenerRegistration<SchemaServiceListener> schemaServiceListenerListenerRegistration : schemaListenerRegistry.getListeners()) {
+        for (ListenerRegistration<SchemaContextListener> schemaServiceListenerListenerRegistration : schemaListenerRegistry.getListeners()) {
             schemaServiceListenerListenerRegistration.getInstance().onGlobalContextUpdated(schemaContext);
         }
     }
index d8174c312ab0e9622a23f17549dd841130a633ff..82637327f6b10d719c04e4fa04ad6a7b53b2dafe 100644 (file)
@@ -23,7 +23,7 @@ import org.opendaylight.yangtools.concepts.Registration;
 import org.opendaylight.yangtools.concepts.util.ListenerRegistry;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
 import org.opendaylight.yangtools.yang.parser.impl.util.URLSchemaContextResolver;
 import org.osgi.framework.Bundle;
 import org.osgi.framework.BundleContext;
@@ -40,15 +40,15 @@ import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 
-public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvider, SchemaService, ServiceTrackerCustomizer<SchemaServiceListener, SchemaServiceListener>, AutoCloseable {
+public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvider, SchemaService, ServiceTrackerCustomizer<SchemaContextListener, SchemaContextListener>, AutoCloseable {
     private static final Logger LOG = LoggerFactory.getLogger(GlobalBundleScanningSchemaServiceImpl.class);
 
-    private final ListenerRegistry<SchemaServiceListener> listeners = new ListenerRegistry<>();
+    private final ListenerRegistry<SchemaContextListener> listeners = new ListenerRegistry<>();
     private final URLSchemaContextResolver contextResolver = new URLSchemaContextResolver();
     private final BundleScanner scanner = new BundleScanner();
     private final BundleContext context;
 
-    private ServiceTracker<SchemaServiceListener, SchemaServiceListener> listenerTracker;
+    private ServiceTracker<SchemaContextListener, SchemaContextListener> listenerTracker;
     private BundleTracker<Iterable<Registration>> bundleTracker;
     private boolean starting = true;
     private static GlobalBundleScanningSchemaServiceImpl instance;
@@ -81,7 +81,7 @@ public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvi
     public void start() {
         checkState(context != null);
 
-        listenerTracker = new ServiceTracker<>(context, SchemaServiceListener.class, GlobalBundleScanningSchemaServiceImpl.this);
+        listenerTracker = new ServiceTracker<>(context, SchemaContextListener.class, GlobalBundleScanningSchemaServiceImpl.this);
         bundleTracker = new BundleTracker<>(context, BundleEvent.RESOLVED | BundleEvent.UNRESOLVED, scanner);
         bundleTracker.open();
         listenerTracker.open();
@@ -115,7 +115,7 @@ public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvi
     }
 
     @Override
-    public synchronized ListenerRegistration<SchemaServiceListener> registerSchemaServiceListener(final SchemaServiceListener listener) {
+    public synchronized ListenerRegistration<SchemaContextListener> registerSchemaContextListener(final SchemaContextListener listener) {
         Optional<SchemaContext> potentialCtx = contextResolver.getSchemaContext();
         if(potentialCtx.isPresent()) {
             listener.onGlobalContextUpdated(potentialCtx.get());
@@ -137,7 +137,7 @@ public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvi
 
     private synchronized void updateContext(final SchemaContext snapshot) {
         Object[] services = listenerTracker.getServices();
-        for (ListenerRegistration<SchemaServiceListener> listener : listeners) {
+        for (ListenerRegistration<SchemaContextListener> listener : listeners) {
             try {
                 listener.getInstance().onGlobalContextUpdated(snapshot);
             } catch (Exception e) {
@@ -146,7 +146,7 @@ public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvi
         }
         if (services != null) {
             for (Object rawListener : services) {
-                SchemaServiceListener listener = (SchemaServiceListener) rawListener;
+                final SchemaContextListener listener = (SchemaContextListener) rawListener;
                 try {
                     listener.onGlobalContextUpdated(snapshot);
                 } catch (Exception e) {
@@ -213,9 +213,9 @@ public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvi
     }
 
     @Override
-    public synchronized SchemaServiceListener addingService(final ServiceReference<SchemaServiceListener> reference) {
+    public synchronized SchemaContextListener addingService(final ServiceReference<SchemaContextListener> reference) {
 
-        SchemaServiceListener listener = context.getService(reference);
+        SchemaContextListener listener = context.getService(reference);
         SchemaContext _ctxContext = getGlobalContext();
         if (getContext() != null && _ctxContext != null) {
             listener.onGlobalContextUpdated(_ctxContext);
@@ -234,12 +234,12 @@ public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvi
     }
 
     @Override
-    public void modifiedService(final ServiceReference<SchemaServiceListener> reference, final SchemaServiceListener service) {
+    public void modifiedService(final ServiceReference<SchemaContextListener> reference, final SchemaContextListener service) {
         // NOOP
     }
 
     @Override
-    public void removedService(final ServiceReference<SchemaServiceListener> reference, final SchemaServiceListener service) {
+    public void removedService(final ServiceReference<SchemaContextListener> reference, final SchemaContextListener service) {
         context.ungetService(reference);
     }
 }
index 1d864eec5bab32c2e1de266ed22eb5f065273109..d8d2346a8cfa42a89685a2dc12552920aea59664 100644 (file)
@@ -8,10 +8,10 @@
 package org.opendaylight.controller.sal.dom.broker.osgi;
 
 import org.opendaylight.controller.sal.core.api.model.SchemaService;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
 import org.osgi.framework.ServiceReference;
 
 public class SchemaServiceProxy extends AbstractBrokerServiceProxy<SchemaService> implements SchemaService {
@@ -41,12 +41,9 @@ public class SchemaServiceProxy extends AbstractBrokerServiceProxy<SchemaService
     }
 
     @Override
-    public ListenerRegistration<SchemaServiceListener> registerSchemaServiceListener(SchemaServiceListener listener) {
-        ListenerRegistration<SchemaServiceListener> registration = getDelegate().registerSchemaServiceListener(listener);
+    public ListenerRegistration<SchemaContextListener> registerSchemaContextListener(SchemaContextListener listener) {
+        ListenerRegistration<SchemaContextListener> registration = getDelegate().registerSchemaContextListener(listener);
         addRegistration(registration);
         return registration;
     }
-
-
-
 }
index 399f49bd6b49094acf9aa92a63fc68e0c874ed18..59cdc76e7ade377911d0cdc1e841b573ab35913f 100644 (file)
@@ -20,7 +20,7 @@ public class XSQLModule extends org.opendaylight.yang.gen.v1.http.netconfcentral
     @Override
     public java.lang.AutoCloseable createInstance() {
         XSQLAdapter xsqlAdapter = XSQLAdapter.getInstance();
-        getSchemaServiceDependency().registerSchemaServiceListener(xsqlAdapter);
+        getSchemaServiceDependency().registerSchemaContextListener(xsqlAdapter);
         xsqlAdapter.setDataBroker(getAsyncDataBrokerDependency());
         XSQLProvider p = new XSQLProvider();
         p.buildXSQL(getDataBrokerDependency());
index 01a5989dcd8a6b5afa67a50844e540cbd68c80c5..805608d479e0e76d1ecebb6a7398a884e11498cb 100644 (file)
@@ -23,7 +23,7 @@ public class InMemoryConfigDataStoreProviderModule extends org.opendaylight.cont
     @Override
     public java.lang.AutoCloseable createInstance() {
       InMemoryDOMDataStore   ids = new InMemoryDOMDataStore("DOM-CFG", MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()));
-      getSchemaServiceDependency().registerSchemaServiceListener(ids);
+      getSchemaServiceDependency().registerSchemaContextListener(ids);
       return ids;
     }
 
index b39c9bbbd8ca7f0cbe504470ec5f9237e88c0a70..f4795588ab61ef62a9f74f6eb1530da1b6307141 100644 (file)
@@ -23,7 +23,7 @@ public class InMemoryOperationalDataStoreProviderModule extends org.opendaylight
     @Override
     public java.lang.AutoCloseable createInstance() {
       InMemoryDOMDataStore ids = new InMemoryDOMDataStore("DOM-OPER", MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()));
-      getOperationalSchemaServiceDependency().registerSchemaServiceListener(ids);
+      getOperationalSchemaServiceDependency().registerSchemaContextListener(ids);
       return ids;
     }
 
index 037bfb4a82c2cd8f34dbfe05513e602e7077b3ff..b75df80f4ef4b3091975e3b5e0f50a70ed9bc71c 100644 (file)
@@ -13,8 +13,10 @@ import static org.opendaylight.controller.config.api.JmxAttributeValidationExcep
 import java.io.File;
 import java.io.InputStream;
 import java.net.InetSocketAddress;
+import java.util.List;
 import java.util.concurrent.ExecutorService;
 
+import org.opendaylight.controller.config.api.JmxAttributeValidationException;
 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
 import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfiguration;
@@ -24,6 +26,7 @@ import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
 import org.opendaylight.controller.sal.connect.api.RemoteDeviceHandler;
 import org.opendaylight.controller.sal.connect.netconf.NetconfDevice;
 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
+import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionCapabilities;
 import org.opendaylight.controller.sal.connect.netconf.sal.NetconfDeviceSalFacade;
 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
 import org.opendaylight.controller.sal.core.api.Broker;
@@ -40,6 +43,8 @@ import org.osgi.framework.BundleContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.base.Optional;
+
 /**
  *
  */
@@ -49,6 +54,7 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
 
     private static AbstractCachingSchemaSourceProvider<String, InputStream> GLOBAL_NETCONF_SOURCE_PROVIDER = null;
     private BundleContext bundleContext;
+    private Optional<NetconfSessionCapabilities> userCapabilities;
 
     public NetconfConnectorModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
         super(identifier, dependencyResolver);
@@ -82,9 +88,11 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
             checkNotNull(getPassword(), passwordJmxAttribute);
         }
 
+        userCapabilities = getUserCapabilities();
+
     }
 
-    private boolean isHostAddressPresent(Host address) {
+    private boolean isHostAddressPresent(final Host address) {
         return address.getDomainName() != null ||
                address.getIpAddress() != null && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null);
     }
@@ -98,10 +106,14 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
         final Broker domBroker = getDomRegistryDependency();
         final BindingAwareBroker bindingBroker = getBindingRegistryDependency();
 
-        final RemoteDeviceHandler salFacade = new NetconfDeviceSalFacade(id, domBroker, bindingBroker, bundleContext, globalProcessingExecutor);
+        final RemoteDeviceHandler<NetconfSessionCapabilities> salFacade
+                = new NetconfDeviceSalFacade(id, domBroker, bindingBroker, bundleContext, globalProcessingExecutor);
         final NetconfDevice device =
                 NetconfDevice.createNetconfDevice(id, getGlobalNetconfSchemaProvider(), globalProcessingExecutor, salFacade);
-        final NetconfDeviceCommunicator listener = new NetconfDeviceCommunicator(id, device);
+
+        final NetconfDeviceCommunicator listener = userCapabilities.isPresent() ?
+                new NetconfDeviceCommunicator(id, device, userCapabilities.get()) : new NetconfDeviceCommunicator(id, device);
+
         final NetconfReconnectingClientConfiguration clientConfig = getClientConfig(listener);
 
         final NetconfClientDispatcher dispatcher = getClientDispatcherDependency();
@@ -116,6 +128,26 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
         };
     }
 
+    private Optional<NetconfSessionCapabilities> getUserCapabilities() {
+        if(getYangModuleCapabilities() == null) {
+            return Optional.absent();
+        }
+
+        final List<String> capabilities = getYangModuleCapabilities().getCapability();
+        if(capabilities == null || capabilities.isEmpty()) {
+            return Optional.absent();
+        }
+
+        final NetconfSessionCapabilities parsedOverrideCapabilities = NetconfSessionCapabilities.fromStrings(capabilities);
+        JmxAttributeValidationException.checkCondition(
+                parsedOverrideCapabilities.getNonModuleCaps().isEmpty(),
+                "Capabilities to override can only contain module based capabilities, non-module capabilities will be retrieved from the device," +
+                        " configured non-module capabilities: " + parsedOverrideCapabilities.getNonModuleCaps(),
+                yangModuleCapabilitiesJmxAttribute);
+
+        return Optional.of(parsedOverrideCapabilities);
+    }
+
     private synchronized AbstractCachingSchemaSourceProvider<String, InputStream> getGlobalNetconfSchemaProvider() {
         if(GLOBAL_NETCONF_SOURCE_PROVIDER == null) {
             final String storageFile = "cache/schema";
@@ -175,8 +207,8 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
         if(getAddress().getDomainName() != null) {
             return new InetSocketAddress(getAddress().getDomainName().getValue(), getPort().getValue());
         } else {
-            IpAddress ipAddress = getAddress().getIpAddress();
-            String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
+            final IpAddress ipAddress = getAddress().getIpAddress();
+            final String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
             return new InetSocketAddress(ip, getPort().getValue());
         }
     }
index de4ac7ac18a106f88f530ac4dc16ea047976b091..07d3c087740c811d4f8404c34d4d90c12ed17143 100644 (file)
@@ -118,6 +118,7 @@ public final class NetconfDevice implements RemoteDevice<NetconfSessionCapabilit
                 // Unable to initialize device, set as disconnected
                 logger.error("{}: Initialization failed", id, t);
                 salFacade.onDeviceDisconnected();
+                // TODO ssh connection is still open if sal initialization fails
             }
         });
     }
index 8045f8cb4a9556160b44fb46d4d3bbc12374435a..3871cdfa4f4cb7556313d8419407e1d3326dc802 100644 (file)
@@ -7,13 +7,19 @@
  */
 package org.opendaylight.controller.sal.connect.netconf.listener;
 
+import com.google.common.base.Optional;
+import com.google.common.base.Strings;
+import com.google.common.collect.Lists;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import io.netty.util.concurrent.Future;
+import io.netty.util.concurrent.FutureListener;
 import java.util.ArrayDeque;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Queue;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantLock;
-
 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
 import org.opendaylight.controller.netconf.api.NetconfMessage;
 import org.opendaylight.controller.netconf.api.NetconfTerminationReason;
@@ -36,31 +42,35 @@ import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Strings;
-import com.google.common.collect.Lists;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-
-import io.netty.util.concurrent.Future;
-import io.netty.util.concurrent.FutureListener;
-
 public class NetconfDeviceCommunicator implements NetconfClientSessionListener, RemoteDeviceCommunicator<NetconfMessage> {
 
     private static final Logger logger = LoggerFactory.getLogger(NetconfDeviceCommunicator.class);
 
     private final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice;
+    private final Optional<NetconfSessionCapabilities> overrideNetconfCapabilities;
     private final RemoteDeviceId id;
     private final Lock sessionLock = new ReentrantLock();
 
+    private final Queue<Request> requests = new ArrayDeque<>();
+    private NetconfClientSession session;
+
+    public NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice,
+            final NetconfSessionCapabilities netconfSessionCapabilities) {
+        this(id, remoteDevice, Optional.of(netconfSessionCapabilities));
+    }
+
     public NetconfDeviceCommunicator(final RemoteDeviceId id,
-            final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice) {
+                                     final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice) {
+        this(id, remoteDevice, Optional.<NetconfSessionCapabilities>absent());
+    }
+
+    private NetconfDeviceCommunicator(final RemoteDeviceId id, final RemoteDevice<NetconfSessionCapabilities, NetconfMessage> remoteDevice,
+            final Optional<NetconfSessionCapabilities> overrideNetconfCapabilities) {
         this.id = id;
         this.remoteDevice = remoteDevice;
+        this.overrideNetconfCapabilities = overrideNetconfCapabilities;
     }
 
-    private final Queue<Request> requests = new ArrayDeque<>();
-    private NetconfClientSession session;
-
     @Override
     public void onSessionUp(final NetconfClientSession session) {
         sessionLock.lock();
@@ -68,10 +78,15 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
             logger.debug("{}: Session established", id);
             this.session = session;
 
-            final NetconfSessionCapabilities netconfSessionCapabilities =
+            NetconfSessionCapabilities netconfSessionCapabilities =
                                              NetconfSessionCapabilities.fromNetconfSession(session);
             logger.trace("{}: Session advertised capabilities: {}", id, netconfSessionCapabilities);
 
+            if(overrideNetconfCapabilities.isPresent()) {
+                netconfSessionCapabilities = netconfSessionCapabilities.replaceModuleCaps(overrideNetconfCapabilities.get());
+                logger.debug("{}: Session capabilities overridden, capabilities that will be used: {}", id, netconfSessionCapabilities);
+            }
+
             remoteDevice.onRemoteSessionUp(netconfSessionCapabilities, this);
         }
         finally {
@@ -223,7 +238,7 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
                 return;
             }
 
-            request.future.set( RpcResultBuilder.<NetconfMessage>success( message ).build() );
+            request.future.set( RpcResultBuilder.success( message ).build() );
         }
     }
 
index 8964a80228bf848538dc83dfc6db71c05f93a102..1a7d90e9c0ad1d9424da229b29eef9ebf7c9b6a4 100644 (file)
@@ -8,6 +8,7 @@ import com.google.common.base.Splitter;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Iterables;
 
+import com.google.common.collect.Sets;
 import java.util.Collection;
 import java.util.HashSet;
 import java.util.Set;
@@ -19,6 +20,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 public final class NetconfSessionCapabilities {
+
     private static final class ParameterMatcher {
         private final Predicate<String> predicate;
         private final int skipLength;
@@ -57,10 +59,10 @@ public final class NetconfSessionCapabilities {
     };
 
     private final Set<QName> moduleBasedCaps;
-    private final Set<String> capabilities;
+    private final Set<String> nonModuleCaps;
 
-    private NetconfSessionCapabilities(final Set<String> capabilities, final Set<QName> moduleBasedCaps) {
-        this.capabilities = Preconditions.checkNotNull(capabilities);
+    private NetconfSessionCapabilities(final Set<String> nonModuleCaps, final Set<QName> moduleBasedCaps) {
+        this.nonModuleCaps = Preconditions.checkNotNull(nonModuleCaps);
         this.moduleBasedCaps = Preconditions.checkNotNull(moduleBasedCaps);
     }
 
@@ -68,30 +70,49 @@ public final class NetconfSessionCapabilities {
         return moduleBasedCaps;
     }
 
-    public boolean containsCapability(final String capability) {
-        return capabilities.contains(capability);
+    public Set<String> getNonModuleCaps() {
+        return nonModuleCaps;
+    }
+
+    public boolean containsNonModuleCapability(final String capability) {
+        return nonModuleCaps.contains(capability);
     }
 
-    public boolean containsCapability(final QName capability) {
+    public boolean containsModuleCapability(final QName capability) {
         return moduleBasedCaps.contains(capability);
     }
 
     @Override
     public String toString() {
         return Objects.toStringHelper(this)
-                .add("capabilities", capabilities)
+                .add("capabilities", nonModuleCaps)
+                .add("moduleBasedCapabilities", moduleBasedCaps)
                 .add("rollback", isRollbackSupported())
                 .add("monitoring", isMonitoringSupported())
                 .toString();
     }
 
     public boolean isRollbackSupported() {
-        return containsCapability(NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString());
+        return containsNonModuleCapability(NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString());
+    }
+
+    public boolean isCandidateSupported() {
+        return containsNonModuleCapability(NetconfMessageTransformUtil.NETCONF_CANDIDATE_URI.toString());
     }
 
     public boolean isMonitoringSupported() {
-        return containsCapability(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING)
-                || containsCapability(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
+        return containsModuleCapability(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING)
+                || containsNonModuleCapability(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
+    }
+
+    public NetconfSessionCapabilities replaceModuleCaps(final NetconfSessionCapabilities netconfSessionModuleCapabilities) {
+        final Set<QName> moduleBasedCaps = Sets.newHashSet(netconfSessionModuleCapabilities.getModuleBasedCaps());
+
+        // Preserve monitoring module, since it indicates support for ietf-netconf-monitoring
+        if(containsModuleCapability(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING)) {
+            moduleBasedCaps.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING);
+        }
+        return new NetconfSessionCapabilities(getNonModuleCaps(), moduleBasedCaps);
     }
 
     public static NetconfSessionCapabilities fromNetconfSession(final NetconfClientSession session) {
@@ -100,6 +121,7 @@ public final class NetconfSessionCapabilities {
 
     public static NetconfSessionCapabilities fromStrings(final Collection<String> capabilities) {
         final Set<QName> moduleBasedCaps = new HashSet<>();
+        final Set<String> nonModuleCaps = Sets.newHashSet(capabilities);
 
         for (final String capability : capabilities) {
             final int qmark = capability.indexOf('?');
@@ -117,6 +139,7 @@ public final class NetconfSessionCapabilities {
             String revision = REVISION_PARAM.from(queryParams);
             if (revision != null) {
                 moduleBasedCaps.add(QName.create(namespace, revision, moduleName));
+                nonModuleCaps.remove(capability);
                 continue;
             }
 
@@ -136,8 +159,9 @@ public final class NetconfSessionCapabilities {
 
             // FIXME: do we really want to continue here?
             moduleBasedCaps.add(QName.create(namespace, revision, moduleName));
+            nonModuleCaps.remove(capability);
         }
 
-        return new NetconfSessionCapabilities(ImmutableSet.copyOf(capabilities), ImmutableSet.copyOf(moduleBasedCaps));
+        return new NetconfSessionCapabilities(ImmutableSet.copyOf(nonModuleCaps), ImmutableSet.copyOf(moduleBasedCaps));
     }
 }
index ee0c8b72179d4101cd22bca526cc7e39cfe40100..f3a9acd630f33bfbf3339d9051d2c4fe4c733a10 100644 (file)
@@ -42,7 +42,7 @@ final class NetconfDeviceDataBroker implements DOMDataBroker {
 
     @Override
     public DOMDataReadOnlyTransaction newReadOnlyTransaction() {
-        return new NetconfDeviceReadOnlyTx(rpc, normalizer);
+        return new NetconfDeviceReadOnlyTx(rpc, normalizer, id);
     }
 
     @Override
@@ -52,8 +52,7 @@ final class NetconfDeviceDataBroker implements DOMDataBroker {
 
     @Override
     public DOMDataWriteTransaction newWriteOnlyTransaction() {
-        // FIXME detect if candidate is supported, true is hardcoded
-        return new NetconfDeviceWriteOnlyTx(id, rpc, normalizer, true, netconfSessionPreferences.isRollbackSupported());
+        return new NetconfDeviceWriteOnlyTx(id, rpc, normalizer, netconfSessionPreferences.isCandidateSupported(), netconfSessionPreferences.isRollbackSupported());
     }
 
     @Override
index 3248453baf498f372715696aaf749c509005345d..9ef44f65849fc6131652b7707374c656d86ab4ee 100644 (file)
@@ -15,6 +15,7 @@ import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessag
 
 import com.google.common.base.Function;
 import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
@@ -22,6 +23,7 @@ import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizat
 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
+import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
 import org.opendaylight.controller.sal.core.api.RpcImplementation;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
@@ -32,16 +34,19 @@ import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+
 public final class NetconfDeviceReadOnlyTx implements DOMDataReadOnlyTransaction {
 
     private static final Logger LOG  = LoggerFactory.getLogger(NetconfDeviceReadOnlyTx.class);
 
     private final RpcImplementation rpc;
     private final DataNormalizer normalizer;
+    private final RemoteDeviceId id;
 
-    public NetconfDeviceReadOnlyTx(final RpcImplementation rpc, final DataNormalizer normalizer) {
+    public NetconfDeviceReadOnlyTx(final RpcImplementation rpc, final DataNormalizer normalizer, final RemoteDeviceId id) {
         this.rpc = rpc;
         this.normalizer = normalizer;
+        this.id = id;
     }
 
     public ListenableFuture<Optional<NormalizedNode<?, ?>>> readConfigurationData(final YangInstanceIdentifier path) {
@@ -51,6 +56,8 @@ public final class NetconfDeviceReadOnlyTx implements DOMDataReadOnlyTransaction
         return Futures.transform(future, new Function<RpcResult<CompositeNode>, Optional<NormalizedNode<?, ?>>>() {
             @Override
             public Optional<NormalizedNode<?, ?>> apply(final RpcResult<CompositeNode> result) {
+                checkReadSuccess(result, path);
+
                 final CompositeNode data = result.getResult().getFirstCompositeByName(NETCONF_DATA_QNAME);
                 final CompositeNode node = (CompositeNode) findNode(data, path);
 
@@ -61,6 +68,11 @@ public final class NetconfDeviceReadOnlyTx implements DOMDataReadOnlyTransaction
         });
     }
 
+    private void checkReadSuccess(final RpcResult<CompositeNode> result, final YangInstanceIdentifier path) {
+        LOG.warn("{}: Unable to read data: {}, errors: {}", id, path, result.getErrors());
+        Preconditions.checkArgument(result.isSuccessful(), "%s: Unable to read data: %s, errors: %s", id, path, result.getErrors());
+    }
+
     private Optional<NormalizedNode<?, ?>> transform(final YangInstanceIdentifier path, final CompositeNode node) {
         if(node == null) {
             return Optional.absent();
@@ -68,7 +80,7 @@ public final class NetconfDeviceReadOnlyTx implements DOMDataReadOnlyTransaction
         try {
             return Optional.<NormalizedNode<?, ?>>of(normalizer.toNormalized(path, node).getValue());
         } catch (final Exception e) {
-            LOG.error("Unable to normalize data for {}, data: {}", path, node, e);
+            LOG.error("{}: Unable to normalize data for {}, data: {}", id, path, node, e);
             throw e;
         }
     }
@@ -79,6 +91,8 @@ public final class NetconfDeviceReadOnlyTx implements DOMDataReadOnlyTransaction
         return Futures.transform(future, new Function<RpcResult<CompositeNode>, Optional<NormalizedNode<?, ?>>>() {
             @Override
             public Optional<NormalizedNode<?, ?>> apply(final RpcResult<CompositeNode> result) {
+                checkReadSuccess(result, path);
+
                 final CompositeNode data = result.getResult().getFirstCompositeByName(NETCONF_DATA_QNAME);
                 final CompositeNode node = (CompositeNode) findNode(data, path);
 
@@ -123,7 +137,7 @@ public final class NetconfDeviceReadOnlyTx implements DOMDataReadOnlyTransaction
 
     @Override
     public ListenableFuture<Optional<NormalizedNode<?, ?>>> read(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
-        final YangInstanceIdentifier legacyPath = toLegacyPath(normalizer, path);
+        final YangInstanceIdentifier legacyPath = toLegacyPath(normalizer, path, id);
 
         switch (store) {
             case CONFIGURATION : {
@@ -134,14 +148,14 @@ public final class NetconfDeviceReadOnlyTx implements DOMDataReadOnlyTransaction
             }
         }
 
-        throw new IllegalArgumentException(String.format("Cannot read data %s for %s datastore, unknown datastore type", path, store));
+        throw new IllegalArgumentException(String.format("%s, Cannot read data %s for %s datastore, unknown datastore type", id, path, store));
     }
 
-    static YangInstanceIdentifier toLegacyPath(final DataNormalizer normalizer, final YangInstanceIdentifier path) {
+    static YangInstanceIdentifier toLegacyPath(final DataNormalizer normalizer, final YangInstanceIdentifier path, final RemoteDeviceId id) {
         try {
             return normalizer.toLegacy(path);
         } catch (final DataNormalizationException e) {
-            throw new IllegalArgumentException("Cannot normalize path " + path, e);
+            throw new IllegalArgumentException(id + ": Cannot normalize path " + path, e);
         }
     }
 
index c8d90282109b3fcd244ceb163f47e1f0ce62036b..87f5477d35d0f986b6f2a0fd8b1044b8b421e58c 100644 (file)
@@ -8,10 +8,11 @@
 
 package org.opendaylight.controller.sal.connect.netconf.sal.tx;
 
+import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.DISCARD_CHANGES_RPC_CONTENT;
 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_CANDIDATE_QNAME;
-import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME;
 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_CONFIG_QNAME;
 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_DEFAULT_OPERATION_QNAME;
+import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_DISCARD_CHANGES_QNAME;
 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME;
 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_ERROR_OPTION_QNAME;
 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_OPERATION_QNAME;
@@ -26,13 +27,14 @@ import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 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.ListenableFuture;
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ExecutionException;
-import javax.annotation.Nullable;
+import java.util.concurrent.atomic.AtomicBoolean;
 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;
@@ -57,97 +59,114 @@ import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class NetconfDeviceWriteOnlyTx implements DOMDataWriteTransaction {
+public class NetconfDeviceWriteOnlyTx implements DOMDataWriteTransaction, FutureCallback<RpcResult<TransactionStatus>> {
 
     private static final Logger LOG  = LoggerFactory.getLogger(NetconfDeviceWriteOnlyTx.class);
 
     private final RemoteDeviceId id;
     private final RpcImplementation rpc;
     private final DataNormalizer normalizer;
+
     private final boolean rollbackSupported;
+    private final boolean candidateSupported;
     private final CompositeNode targetNode;
 
+    // Allow commit to be called only once
+    private final AtomicBoolean finished = new AtomicBoolean(false);
+
     public NetconfDeviceWriteOnlyTx(final RemoteDeviceId id, final RpcImplementation rpc, final DataNormalizer normalizer, final boolean candidateSupported, final boolean rollbackOnErrorSupported) {
         this.id = id;
         this.rpc = rpc;
         this.normalizer = normalizer;
-        this.targetNode = getTargetNode(candidateSupported);
+
+        this.candidateSupported = candidateSupported;
+        this.targetNode = getTargetNode(this.candidateSupported);
         this.rollbackSupported = rollbackOnErrorSupported;
     }
 
-    // FIXME add logging
-
     @Override
     public boolean cancel() {
-        if(isCommitted()) {
+        if(isFinished()) {
             return false;
         }
 
         return discardChanges();
     }
 
-    private boolean isCommitted() {
-        // TODO 732
-        return true;
+    private boolean isFinished() {
+        return finished.get();
     }
 
     private boolean discardChanges() {
-        // TODO 732
+        finished.set(true);
+
+        if(candidateSupported) {
+            sendDiscardChanges();
+        }
         return true;
     }
 
     // TODO should the edit operations be blocking ?
+    // TODO should the discard-changes operations be blocking ?
 
     @Override
     public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
+        checkNotFinished();
         Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION, "Can merge only configuration, not %s", store);
 
         try {
-            final YangInstanceIdentifier legacyPath = NetconfDeviceReadOnlyTx.toLegacyPath(normalizer, path);
+            final YangInstanceIdentifier legacyPath = NetconfDeviceReadOnlyTx.toLegacyPath(normalizer, path, id);
             final CompositeNode legacyData = normalizer.toLegacy(path, data);
-            sendEditRpc(createEditConfigStructure(legacyPath, Optional.of(ModifyAction.REPLACE), Optional.fromNullable(legacyData)), Optional.of(ModifyAction.NONE));
+            sendEditRpc(
+                    createEditConfigStructure(legacyPath, Optional.of(ModifyAction.REPLACE), Optional.fromNullable(legacyData)), Optional.of(ModifyAction.NONE));
         } catch (final ExecutionException e) {
-            LOG.warn("Error putting data to {}, data: {}, discarding changes", path, data, e);
+            LOG.warn("{}: Error putting data to {}, data: {}, discarding changes", id, path, data, e);
             discardChanges();
-            throw new RuntimeException("Error while replacing " + path, e);
+            throw new RuntimeException(id + ": Error while replacing " + path, e);
         }
     }
 
+    private void checkNotFinished() {
+        Preconditions.checkState(isFinished() == false, "%s: Transaction %s already finished", id, getIdentifier());
+    }
+
     @Override
     public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode<?, ?> data) {
-        Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION, "Can merge only configuration, not %s", store);
+        checkNotFinished();
+        Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION, "%s: Can merge only configuration, not %s", id, store);
 
         try {
-            final YangInstanceIdentifier legacyPath = NetconfDeviceReadOnlyTx.toLegacyPath(normalizer, path);
+            final YangInstanceIdentifier legacyPath = NetconfDeviceReadOnlyTx.toLegacyPath(normalizer, path, id);
             final CompositeNode legacyData = normalizer.toLegacy(path, data);
             sendEditRpc(
                     createEditConfigStructure(legacyPath, Optional.<ModifyAction> absent(), Optional.fromNullable(legacyData)), Optional.<ModifyAction> absent());
         } catch (final ExecutionException e) {
-            LOG.warn("Error merging data to {}, data: {}, discarding changes", path, data, e);
+            LOG.warn("{}: Error merging data to {}, data: {}, discarding changes", id, path, data, e);
             discardChanges();
-            throw new RuntimeException("Error while merging " + path, e);
+            throw new RuntimeException(id + ": Error while merging " + path, e);
         }
     }
 
     @Override
     public void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
-        Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION, "Can merge only configuration, not %s", store);
+        checkNotFinished();
+        Preconditions.checkArgument(store == LogicalDatastoreType.CONFIGURATION, "%s: Can merge only configuration, not %s", id, store);
 
         try {
-            sendEditRpc(createEditConfigStructure(NetconfDeviceReadOnlyTx.toLegacyPath(normalizer, path), Optional.of(ModifyAction.DELETE), Optional.<CompositeNode>absent()), Optional.of(ModifyAction.NONE));
+            sendEditRpc(
+                    createEditConfigStructure(NetconfDeviceReadOnlyTx.toLegacyPath(normalizer, path, id), Optional.of(ModifyAction.DELETE), Optional.<CompositeNode>absent()), Optional.of(ModifyAction.NONE));
         } catch (final ExecutionException e) {
-            LOG.warn("Error deleting data {}, discarding changes", path, e);
+            LOG.warn("{}: Error deleting data {}, discarding changes", id, path, e);
             discardChanges();
-            throw new RuntimeException("Error while deleting " + path, e);
+            throw new RuntimeException(id + ": Error while deleting " + path, e);
         }
     }
 
     @Override
     public CheckedFuture<Void, TransactionCommitFailedException> submit() {
         final ListenableFuture<Void> commmitFutureAsVoid = Futures.transform(commit(), new Function<RpcResult<TransactionStatus>, Void>() {
-            @Nullable
             @Override
-            public Void apply(@Nullable final RpcResult<TransactionStatus> input) {
+            public Void apply(final RpcResult<TransactionStatus> input) {
                 return null;
             }
         });
@@ -162,25 +181,46 @@ public class NetconfDeviceWriteOnlyTx implements DOMDataWriteTransaction {
 
     @Override
     public ListenableFuture<RpcResult<TransactionStatus>> commit() {
-        // FIXME do not allow commit if closed or failed
+        checkNotFinished();
+        finished.set(true);
 
-        final ListenableFuture<RpcResult<CompositeNode>> rpcResult = rpc.invokeRpc(NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME, getCommitRequest());
-        return Futures.transform(rpcResult, new Function<RpcResult<CompositeNode>, RpcResult<TransactionStatus>>() {
-            @Override
-            public RpcResult<TransactionStatus> apply(@Nullable final RpcResult<CompositeNode> input) {
-                if(input.isSuccessful()) {
-                    return RpcResultBuilder.success(TransactionStatus.COMMITED).build();
-                } else {
-                    final RpcResultBuilder<TransactionStatus> failed = RpcResultBuilder.failed();
-                    for (final RpcError rpcError : input.getErrors()) {
-                        failed.withError(rpcError.getErrorType(), rpcError.getTag(), rpcError.getMessage(), rpcError.getApplicationTag(), rpcError.getInfo(), rpcError.getCause());
+        if(candidateSupported == false) {
+            return Futures.immediateFuture(RpcResultBuilder.success(TransactionStatus.COMMITED).build());
+        }
+
+        final ListenableFuture<RpcResult<CompositeNode>> rpcResult = rpc.invokeRpc(
+                NetconfMessageTransformUtil.NETCONF_COMMIT_QNAME, NetconfMessageTransformUtil.COMMIT_RPC_CONTENT);
+
+        final ListenableFuture<RpcResult<TransactionStatus>> transformed = Futures.transform(rpcResult,
+                new Function<RpcResult<CompositeNode>, RpcResult<TransactionStatus>>() {
+                    @Override
+                    public RpcResult<TransactionStatus> apply(final RpcResult<CompositeNode> input) {
+                        if (input.isSuccessful()) {
+                            return RpcResultBuilder.success(TransactionStatus.COMMITED).build();
+                        } else {
+                            final RpcResultBuilder<TransactionStatus> failed = RpcResultBuilder.failed();
+                            for (final RpcError rpcError : input.getErrors()) {
+                                failed.withError(rpcError.getErrorType(), rpcError.getTag(), rpcError.getMessage(),
+                                        rpcError.getApplicationTag(), rpcError.getInfo(), rpcError.getCause());
+                            }
+                            return failed.build();
+                        }
                     }
-                    return failed.build();
-                }
-            }
-        });
+                });
 
-        // FIXME 732 detect commit failure
+        Futures.addCallback(transformed, this);
+        return transformed;
+    }
+
+    @Override
+    public void onSuccess(final RpcResult<TransactionStatus> result) {
+        LOG.debug("{}: Write successful, transaction: {}", id, getIdentifier());
+    }
+
+    @Override
+    public void onFailure(final Throwable t) {
+        LOG.warn("{}: Write failed, transaction {}, discarding changes", id, getIdentifier(), t);
+        discardChanges();
     }
 
     private void sendEditRpc(final CompositeNode editStructure, final Optional<ModifyAction> defaultOperation) throws ExecutionException {
@@ -200,6 +240,22 @@ public class NetconfDeviceWriteOnlyTx implements DOMDataWriteTransaction {
         }
     }
 
+    private void sendDiscardChanges() {
+        final ListenableFuture<RpcResult<CompositeNode>> discardFuture = rpc.invokeRpc(NETCONF_DISCARD_CHANGES_QNAME, DISCARD_CHANGES_RPC_CONTENT);
+        Futures.addCallback(discardFuture, new FutureCallback<RpcResult<CompositeNode>>() {
+            @Override
+            public void onSuccess(final RpcResult<CompositeNode> result) {
+                LOG.debug("{}: Discarding transaction: {}", id, getIdentifier());
+            }
+
+            @Override
+            public void onFailure(final Throwable t) {
+                LOG.error("{}: Discarding changes failed, transaction: {}. Device configuration might be corrupted", id, getIdentifier(), t);
+                throw new RuntimeException(id + ": Discarding changes failed, transaction " + getIdentifier(), t);
+            }
+        });
+    }
+
     private CompositeNode createEditConfigStructure(final YangInstanceIdentifier dataPath, final Optional<ModifyAction> operation,
                                                     final Optional<CompositeNode> lastChildOverride) {
         Preconditions.checkArgument(Iterables.isEmpty(dataPath.getPathArguments()) == false, "Instance identifier with empty path %s", dataPath);
@@ -298,13 +354,6 @@ public class NetconfDeviceWriteOnlyTx implements DOMDataWriteTransaction {
         }
     }
 
-    private ImmutableCompositeNode getCommitRequest() {
-        final CompositeNodeBuilder<ImmutableCompositeNode> commitInput = ImmutableCompositeNode.builder();
-        commitInput.setQName(NETCONF_COMMIT_QNAME);
-        return commitInput.toInstance();
-    }
-
-
     @Override
     public Object getIdentifier() {
         return this;
index a6924d9d37a3b3e81921c049d1bc1f5b3a5571a2..d3faddd471d0533c221b00cbe867a8b9d6431a12 100644 (file)
@@ -35,6 +35,7 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.Node;
 import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
+import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
 import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
@@ -45,8 +46,7 @@ import org.w3c.dom.Element;
 
 public class NetconfMessageTransformUtil {
 
-    private NetconfMessageTransformUtil() {
-    }
+    private NetconfMessageTransformUtil() {}
 
     public static final QName IETF_NETCONF_MONITORING = QName.create("urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring", "2010-10-04", "ietf-netconf-monitoring");
     public static URI NETCONF_URI = URI.create("urn:ietf:params:xml:ns:netconf:base:1.0");
@@ -66,14 +66,27 @@ public class NetconfMessageTransformUtil {
     public static QName NETCONF_DEFAULT_OPERATION_QNAME = QName.create(NETCONF_OPERATION_QNAME, "default-operation");
     public static QName NETCONF_EDIT_CONFIG_QNAME = QName.create(NETCONF_QNAME, "edit-config");
     public static QName NETCONF_GET_CONFIG_QNAME = QName.create(NETCONF_QNAME, "get-config");
+    public static QName NETCONF_DISCARD_CHANGES_QNAME = QName.create(NETCONF_QNAME, "discard-changes");
     public static QName NETCONF_TYPE_QNAME = QName.create(NETCONF_QNAME, "type");
     public static QName NETCONF_FILTER_QNAME = QName.create(NETCONF_QNAME, "filter");
     public static QName NETCONF_GET_QNAME = QName.create(NETCONF_QNAME, "get");
     public static QName NETCONF_RPC_QNAME = QName.create(NETCONF_QNAME, "rpc");
+
     public static URI NETCONF_ROLLBACK_ON_ERROR_URI = URI
             .create("urn:ietf:params:netconf:capability:rollback-on-error:1.0");
     public static String ROLLBACK_ON_ERROR_OPTION = "rollback-on-error";
 
+    public static URI NETCONF_CANDIDATE_URI = URI
+            .create("urn:ietf:params:netconf:capability:candidate:1.0");
+
+    // Discard changes message
+    public static final CompositeNode DISCARD_CHANGES_RPC_CONTENT =
+            NodeFactory.createImmutableCompositeNode(NETCONF_DISCARD_CHANGES_QNAME, null, Collections.<Node<?>>emptyList());
+
+    // Commit changes message
+    public static final CompositeNode COMMIT_RPC_CONTENT =
+            NodeFactory.createImmutableCompositeNode(NETCONF_COMMIT_QNAME, null, Collections.<Node<?>>emptyList());
+
     public static Node<?> toFilterStructure(final YangInstanceIdentifier identifier) {
         Node<?> previous = null;
         if (Iterables.isEmpty(identifier.getPathArguments())) {
@@ -269,5 +282,4 @@ public class NetconfMessageTransformUtil {
             return it.toInstance();
         }
     }
-
 }
index 6bad4798c290524dc04ff2d39611f2a1f0c33453..e13398b1dfd36a748bcdeb019db55b30b01c4c04 100644 (file)
@@ -58,6 +58,14 @@ module odl-sal-netconf-connector-cfg {
                 type string;
             }
 
+            container yang-module-capabilities {
+                leaf-list capability {
+                    type string;
+                    description "Set a list of capabilities to override capabilities provided in device's hello message.
+                                 Can be used for devices that do not report any yang modules in their hello message";
+                }
+            }
+
             container dom-registry {
                 uses config:service-ref {
                     refine type {
index 391bf9c6a42f5302ba05e078041edee50022c6af..001b9a8d3abc411b041d3f3624ea27505722560c 100644 (file)
@@ -8,35 +8,35 @@
 
 package org.opendaylight.controller.sal.connect.netconf.listener;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Matchers.same;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.verify;
+import static org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants.RPC_REPLY_KEY;
+import static org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0;
+
+import com.google.common.base.Strings;
+import com.google.common.collect.Sets;
+import com.google.common.util.concurrent.ListenableFuture;
 import io.netty.channel.ChannelFuture;
 import io.netty.util.concurrent.Future;
 import io.netty.util.concurrent.GenericFutureListener;
-
 import java.io.ByteArrayInputStream;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.UUID;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
-
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
-
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.reset;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.eq;
-import static org.mockito.Matchers.same;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants.RPC_REPLY_KEY;
-import static org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants.URN_IETF_PARAMS_XML_NS_NETCONF_BASE_1_0;
-
 import org.apache.commons.lang3.StringUtils;
 import org.junit.Before;
 import org.junit.Test;
@@ -56,10 +56,6 @@ import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-import com.google.common.base.Strings;
-import com.google.common.collect.Sets;
-import com.google.common.util.concurrent.ListenableFuture;
-
 public class NetconfDeviceCommunicatorTest {
 
     @Mock
@@ -129,9 +125,9 @@ public class NetconfDeviceCommunicatorTest {
         verify( mockDevice ).onRemoteSessionUp( netconfSessionCapabilities.capture(), eq( communicator ) );
 
         NetconfSessionCapabilities actualCapabilites = netconfSessionCapabilities.getValue();
-        assertEquals( "containsCapability", true, actualCapabilites.containsCapability(
-                                NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString() ) );
-        assertEquals( "containsCapability", true, actualCapabilites.containsCapability( testCapability ) );
+        assertEquals( "containsModuleCapability", true, actualCapabilites.containsNonModuleCapability(
+                NetconfMessageTransformUtil.NETCONF_ROLLBACK_ON_ERROR_URI.toString()) );
+        assertEquals( "containsModuleCapability", false, actualCapabilites.containsNonModuleCapability(testCapability) );
         assertEquals( "getModuleBasedCaps", Sets.newHashSet(
                             QName.create( "urn:opendaylight:params:xml:ns:test", "2014-06-02", "test-module" )),
                       actualCapabilites.getModuleBasedCaps() );
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
new file mode 100644 (file)
index 0000000..87947b5
--- /dev/null
@@ -0,0 +1,50 @@
+package org.opendaylight.controller.sal.connect.netconf.listener;
+
+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;
+
+public class NetconfSessionCapabilitiesTest {
+
+    @Test
+    public void testMerge() throws Exception {
+        final List<String> caps1 = Lists.newArrayList(
+                "namespace:1?module=module1&revision=2012-12-12",
+                "namespace:2?module=module2&amp;revision=2012-12-12",
+                "urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring?module=ietf-netconf-monitoring&amp;revision=2010-10-04",
+                "urn:ietf:params:netconf:base:1.0",
+                "urn:ietf:params:netconf:capability:rollback-on-error:1.0"
+        );
+        final NetconfSessionCapabilities sessionCaps1 = NetconfSessionCapabilities.fromStrings(caps1);
+        assertCaps(sessionCaps1, 2, 3);
+
+        final List<String> caps2 = Lists.newArrayList(
+                "namespace:3?module=module3&revision=2012-12-12",
+                "namespace:4?module=module4&revision=2012-12-12",
+                "randomNonModuleCap"
+        );
+        final NetconfSessionCapabilities sessionCaps2 = NetconfSessionCapabilities.fromStrings(caps2);
+        assertCaps(sessionCaps2, 1, 2);
+
+        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(), JUnitMatchers.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"));
+    }
+
+    private void assertCaps(final NetconfSessionCapabilities sessionCaps1, final int nonModuleCaps, final int moduleCaps) {
+        assertEquals(nonModuleCaps, sessionCaps1.getNonModuleCaps().size());
+        assertEquals(moduleCaps, sessionCaps1.getModuleBasedCaps().size());
+    }
+}
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
new file mode 100644 (file)
index 0000000..a65e426
--- /dev/null
@@ -0,0 +1,79 @@
+package org.opendaylight.controller.sal.connect.netconf.sal.tx;
+
+import static junit.framework.Assert.fail;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoMoreInteractions;
+import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.DISCARD_CHANGES_RPC_CONTENT;
+
+import com.google.common.util.concurrent.CheckedFuture;
+import com.google.common.util.concurrent.Futures;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+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.common.impl.util.compat.DataNormalizer;
+import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
+import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
+import org.opendaylight.controller.sal.core.api.RpcImplementation;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+
+public class NetconfDeviceWriteOnlyTxTest {
+
+    private final RemoteDeviceId id = new RemoteDeviceId("test-mount");
+
+    @Mock
+    private RpcImplementation rpc;
+    @Mock
+    private DataNormalizer normalizer;
+    private YangInstanceIdentifier yangIId;
+
+    @Before
+    public void setUp() throws Exception {
+        MockitoAnnotations.initMocks(this);
+
+        doReturn(Futures.<RpcResult<CompositeNode>>immediateFailedFuture(new IllegalStateException("Failed tx")))
+        .doReturn(Futures.immediateFuture(RpcResultBuilder.<CompositeNode>success().build()))
+                .when(rpc).invokeRpc(any(QName.class), any(CompositeNode.class));
+
+        yangIId = YangInstanceIdentifier.builder().node(QName.create("namespace", "2012-12-12", "name")).build();
+        doReturn(yangIId).when(normalizer).toLegacy(yangIId);
+    }
+
+    @Test
+    public void testDiscardCahnges() {
+        final NetconfDeviceWriteOnlyTx tx = new NetconfDeviceWriteOnlyTx(id, rpc, normalizer, true, true);
+        final CheckedFuture<Void, TransactionCommitFailedException> submitFuture = tx.submit();
+        try {
+            submitFuture.checkedGet();
+        } catch (final TransactionCommitFailedException e) {
+            // verify discard changes was sent
+            verify(rpc).invokeRpc(NetconfMessageTransformUtil.NETCONF_DISCARD_CHANGES_QNAME, DISCARD_CHANGES_RPC_CONTENT);
+            return;
+        }
+
+        fail("Submit should fail");
+    }
+
+
+    @Test
+    public void testDiscardCahngesNotSentWithoutCandidate() {
+        doReturn(Futures.immediateFuture(RpcResultBuilder.<CompositeNode>success().build()))
+        .doReturn(Futures.<RpcResult<CompositeNode>>immediateFailedFuture(new IllegalStateException("Failed tx")))
+                .when(rpc).invokeRpc(any(QName.class), any(CompositeNode.class));
+
+        final NetconfDeviceWriteOnlyTx tx = new NetconfDeviceWriteOnlyTx(id, rpc, normalizer, false, true);
+        tx.delete(LogicalDatastoreType.CONFIGURATION, yangIId);
+        verify(rpc).invokeRpc(eq(NetconfMessageTransformUtil.NETCONF_EDIT_CONFIG_QNAME), any(CompositeNode.class));
+        verifyNoMoreInteractions(rpc);
+    }
+
+}
index d0be2cbcbb02cdc4310f130aa25c8e4f25fd386b..4791979c171ba9de3ef2dbf217f99a1a01586c07 100644 (file)
@@ -24,5 +24,9 @@ machine
 
 6. !!!WARNING!!! - never edit the generated sources files of protocol buffer
 
-7. !!!NOTE!!! if you are planning to add new .proto file  option java_package should begin with
+7. !!!IMPORTANT!!! if you are planning to add new .proto file  option java_package should begin with
    org.opendaylight.controller.protobuff.messages to properly exclude from sonar.
+
+8. !!!IMPORTANT!!! for any new .proto file added you need to create corresponding version-compatibility-serialized-data
+   serialized test file under test/resources and a test case for one message in your .proto file.
+   Please follow the instruction in readme.txt in that folder
index ce120809d7f73c95604c8cbdd49e3f245af63692..03d632b61fb7070d568e360bcd7494ed40c59041 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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;
 
 import com.google.common.base.Preconditions;
index 7b6f5c46d23621dba8dc838dc7dbec8f54366b0f..14ca75b9f3ecb5071621ff43f8234826360b8263 100644 (file)
@@ -1,9 +1,11 @@
 /*
- * 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
+ *  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;
index fc4b3954c5b9957fd6880bc6e81f16b742d3e385..17bdb36e569612ef513a787e010aeb8583167984 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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;
 
 import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages;
index fb153126650bd55ee07f188c1b5ea900a80aef6b..68d3c590e0d400b369155d9d4101c81d3f9a9ac4 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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;
 
 import com.google.common.base.Preconditions;
index a34307f6b45512fa66d89c2dda48addc29be9008..e2c4c358935c184c9244b969533fcf86175e55e8 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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;
 
 import org.opendaylight.yangtools.yang.common.QName;
index 175e242a11eedc3803e3722139d0b860832aabf7..ea3986f4a0a35fd840a92d341a18f5ccb614a256 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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;
 
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
index 9edec1e23029222101126f83d646171b7ecda6ad..1b9c70867d37e7d330d0541785917565ee3d3096 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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;
 
 import org.opendaylight.yangtools.yang.common.QName;
index 4bfcf391dd7afc3f635732022217a18ec8509884..6d3a26ad77fe73889ecfe4ae77a5b6259dcec94a 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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;
 
 import org.opendaylight.yangtools.yang.common.QName;
index b2ec5644d4b9d8c29803a69eeafc3a758d4c56ab..2d434fffcfe8b9f538aa51f828a382498f21e9bd 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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;
 
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
index e82a23d37f643801112bfb011e37115f08982aef..31e6521a2861e65f1412b99818d4d47684e04c7b 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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;
 
 import com.google.common.base.Preconditions;
index 4ccc7076ff03ace546b3c9112b424b565da4ca8e..0083b00403ac9d1746559fa8b23b562985fc14d1 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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;
 
 import com.google.common.base.Preconditions;
index 7735a12a8b114f0d488021b52a5d245ef73d8536..d370eb2deb5fc8ae6a9042e20f778454954e6314 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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;
 
 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
index 69b00bef92cb3e49e1c7f1ac89137fba5357348f..9e85ccb9ab24c3c90920736ccd6c6a5213ac31b3 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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;
 
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
index ba81836ea89f1452aad33388a6f81f6918aab33f..cf5174319d2128518f70391d0d459ad5af26b2cf 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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;
 
 public class PathUtils {
index 8dba0563bd5ba4ddd1e820725dd4df476e13f3bb..002b9ff82e53eea0b62fd98d97756926a2e21bea 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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;
 
 import org.opendaylight.yangtools.yang.common.QName;
index d9a067b573724ef097052cfe89adbf708c87cf08..90f5cf33960bee7003a3e1e1c541280766dd10c8 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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.util;
 
 import com.google.common.base.Preconditions;
@@ -44,13 +54,6 @@ import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
 
-/*
- * 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
- */
 /*
  *
  * <code>EncoderDecoderUtil</code> helps in wrapping the NormalizedNode into a SimpleNormalizedNode
index 5b459e7e7c3e3b217f9596a5d08954f8119efa11..55cb341086078b79406d574c11cec8961813e6b6 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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.util;
 
 import org.opendaylight.controller.cluster.datastore.node.utils.NodeIdentifierFactory;
index 87b246bd7e631f6e4d752f673137aa80c8186b95..99f4751875902b246370f7ba245b51a0122b1872 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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
+ *
+ */
+
 // Generated by the protocol buffer compiler.  DO NOT EDIT!
 // source: CompositeModificationPayload.proto
 
index ac0701a6d84fb3eff2e49de5026bfd7518d3667b..49cb1ead9c126d9cd4456bd2b165d270bf343ce1 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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
+ *
+ */
+
 // Generated by the protocol buffer compiler.  DO NOT EDIT!
 // source: Cohort.proto
 
@@ -652,7 +662,7 @@ public final class ThreePhaseCommitCohortMessages {
 
       public final boolean isInitialized() {
         if (!hasCanCommit()) {
-          
+
           return false;
         }
         return true;
index 81e5b462cc56a6d27b95f1dd050f330b4dfd1520..f88b66bcd39c2ce3728853277e3d97e11eba85e2 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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
+ *
+ */
+
 // Generated by the protocol buffer compiler.  DO NOT EDIT!
 // source: Common.proto
 
@@ -179,7 +189,7 @@ public final class NormalizedNodeMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -195,7 +205,7 @@ public final class NormalizedNodeMessages {
         getNameBytes() {
       java.lang.Object ref = name_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         name_ = b;
@@ -222,7 +232,7 @@ public final class NormalizedNodeMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -238,7 +248,7 @@ public final class NormalizedNodeMessages {
         getValueBytes() {
       java.lang.Object ref = value_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         value_ = b;
@@ -265,7 +275,7 @@ public final class NormalizedNodeMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -281,7 +291,7 @@ public final class NormalizedNodeMessages {
         getTypeBytes() {
       java.lang.Object ref = type_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         type_ = b;
@@ -541,7 +551,7 @@ public final class NormalizedNodeMessages {
 
       public final boolean isInitialized() {
         if (!hasName()) {
-          
+
           return false;
         }
         return true;
@@ -595,7 +605,7 @@ public final class NormalizedNodeMessages {
           getNameBytes() {
         java.lang.Object ref = name_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           name_ = b;
@@ -669,7 +679,7 @@ public final class NormalizedNodeMessages {
           getValueBytes() {
         java.lang.Object ref = value_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           value_ = b;
@@ -743,7 +753,7 @@ public final class NormalizedNodeMessages {
           getTypeBytes() {
         java.lang.Object ref = type_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           type_ = b;
@@ -930,7 +940,7 @@ public final class NormalizedNodeMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -946,7 +956,7 @@ public final class NormalizedNodeMessages {
         getValueBytes() {
       java.lang.Object ref = value_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         value_ = b;
@@ -1168,7 +1178,7 @@ public final class NormalizedNodeMessages {
 
       public final boolean isInitialized() {
         if (!hasValue()) {
-          
+
           return false;
         }
         return true;
@@ -1222,7 +1232,7 @@ public final class NormalizedNodeMessages {
           getValueBytes() {
         java.lang.Object ref = value_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           value_ = b;
@@ -1341,7 +1351,7 @@ public final class NormalizedNodeMessages {
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 4;</code>
      */
-    java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute> 
+    java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute>
         getAttributesList();
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 4;</code>
@@ -1354,7 +1364,7 @@ public final class NormalizedNodeMessages {
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 4;</code>
      */
-    java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder> 
+    java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
         getAttributesOrBuilderList();
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 4;</code>
@@ -1504,7 +1514,7 @@ public final class NormalizedNodeMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -1520,7 +1530,7 @@ public final class NormalizedNodeMessages {
         getValueBytes() {
       java.lang.Object ref = value_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         value_ = b;
@@ -1555,7 +1565,7 @@ public final class NormalizedNodeMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -1575,7 +1585,7 @@ public final class NormalizedNodeMessages {
         getTypeBytes() {
       java.lang.Object ref = type_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         type_ = b;
@@ -1619,7 +1629,7 @@ public final class NormalizedNodeMessages {
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 4;</code>
      */
-    public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder> 
+    public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
         getAttributesOrBuilderList() {
       return attributes_;
     }
@@ -1948,7 +1958,7 @@ public final class NormalizedNodeMessages {
               attributesBuilder_ = null;
               attributes_ = other.attributes_;
               bitField0_ = (bitField0_ & ~0x00000008);
-              attributesBuilder_ = 
+              attributesBuilder_ =
                 com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
                    getAttributesFieldBuilder() : null;
             } else {
@@ -1962,18 +1972,18 @@ public final class NormalizedNodeMessages {
 
       public final boolean isInitialized() {
         if (!hasValue()) {
-          
+
           return false;
         }
         if (hasNodeType()) {
           if (!getNodeType().isInitialized()) {
-            
+
             return false;
           }
         }
         for (int i = 0; i < getAttributesCount(); i++) {
           if (!getAttributes(i).isInitialized()) {
-            
+
             return false;
           }
         }
@@ -2028,7 +2038,7 @@ public final class NormalizedNodeMessages {
           getValueBytes() {
         java.lang.Object ref = value_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           value_ = b;
@@ -2114,7 +2124,7 @@ public final class NormalizedNodeMessages {
           getTypeBytes() {
         java.lang.Object ref = type_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           type_ = b;
@@ -2275,7 +2285,7 @@ public final class NormalizedNodeMessages {
        * <code>optional .org.opendaylight.controller.mdsal.QName nodeType = 3;</code>
        */
       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> 
+          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>
           getNodeTypeFieldBuilder() {
         if (nodeTypeBuilder_ == null) {
           nodeTypeBuilder_ = new com.google.protobuf.SingleFieldBuilder<
@@ -2483,7 +2493,7 @@ public final class NormalizedNodeMessages {
       /**
        * <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 4;</code>
        */
-      public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder> 
+      public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
            getAttributesOrBuilderList() {
         if (attributesBuilder_ != null) {
           return attributesBuilder_.getMessageOrBuilderList();
@@ -2509,12 +2519,12 @@ public final class NormalizedNodeMessages {
       /**
        * <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 4;</code>
        */
-      public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute.Builder> 
+      public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute.Builder>
            getAttributesBuilderList() {
         return getAttributesFieldBuilder().getBuilderList();
       }
       private com.google.protobuf.RepeatedFieldBuilder<
-          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder> 
+          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
           getAttributesFieldBuilder() {
         if (attributesBuilder_ == null) {
           attributesBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
@@ -2546,7 +2556,7 @@ public final class NormalizedNodeMessages {
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.PathArgument arguments = 1;</code>
      */
-    java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgument> 
+    java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgument>
         getArgumentsList();
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.PathArgument arguments = 1;</code>
@@ -2559,7 +2569,7 @@ public final class NormalizedNodeMessages {
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.PathArgument arguments = 1;</code>
      */
-    java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgumentOrBuilder> 
+    java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgumentOrBuilder>
         getArgumentsOrBuilderList();
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.PathArgument arguments = 1;</code>
@@ -2680,7 +2690,7 @@ public final class NormalizedNodeMessages {
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.PathArgument arguments = 1;</code>
      */
-    public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgumentOrBuilder> 
+    public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgumentOrBuilder>
         getArgumentsOrBuilderList() {
       return arguments_;
     }
@@ -2933,7 +2943,7 @@ public final class NormalizedNodeMessages {
               argumentsBuilder_ = null;
               arguments_ = other.arguments_;
               bitField0_ = (bitField0_ & ~0x00000001);
-              argumentsBuilder_ = 
+              argumentsBuilder_ =
                 com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
                    getArgumentsFieldBuilder() : null;
             } else {
@@ -2948,7 +2958,7 @@ public final class NormalizedNodeMessages {
       public final boolean isInitialized() {
         for (int i = 0; i < getArgumentsCount(); i++) {
           if (!getArguments(i).isInitialized()) {
-            
+
             return false;
           }
         }
@@ -3169,7 +3179,7 @@ public final class NormalizedNodeMessages {
       /**
        * <code>repeated .org.opendaylight.controller.mdsal.PathArgument arguments = 1;</code>
        */
-      public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgumentOrBuilder> 
+      public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgumentOrBuilder>
            getArgumentsOrBuilderList() {
         if (argumentsBuilder_ != null) {
           return argumentsBuilder_.getMessageOrBuilderList();
@@ -3195,12 +3205,12 @@ public final class NormalizedNodeMessages {
       /**
        * <code>repeated .org.opendaylight.controller.mdsal.PathArgument arguments = 1;</code>
        */
-      public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgument.Builder> 
+      public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgument.Builder>
            getArgumentsBuilderList() {
         return getArgumentsFieldBuilder().getBuilderList();
       }
       private com.google.protobuf.RepeatedFieldBuilder<
-          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgument, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgument.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgumentOrBuilder> 
+          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgument, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgument.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.PathArgumentOrBuilder>
           getArgumentsFieldBuilder() {
         if (argumentsBuilder_ == null) {
           argumentsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
@@ -3262,7 +3272,7 @@ public final class NormalizedNodeMessages {
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 3;</code>
      */
-    java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute> 
+    java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute>
         getAttributesList();
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 3;</code>
@@ -3275,7 +3285,7 @@ public final class NormalizedNodeMessages {
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 3;</code>
      */
-    java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder> 
+    java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
         getAttributesOrBuilderList();
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 3;</code>
@@ -3287,7 +3297,7 @@ public final class NormalizedNodeMessages {
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.Node child = 4;</code>
      */
-    java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node> 
+    java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node>
         getChildList();
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.Node child = 4;</code>
@@ -3300,7 +3310,7 @@ public final class NormalizedNodeMessages {
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.Node child = 4;</code>
      */
-    java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> 
+    java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
         getChildOrBuilderList();
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.Node child = 4;</code>
@@ -3546,7 +3556,7 @@ public final class NormalizedNodeMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -3562,7 +3572,7 @@ public final class NormalizedNodeMessages {
         getPathBytes() {
       java.lang.Object ref = path_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         path_ = b;
@@ -3589,7 +3599,7 @@ public final class NormalizedNodeMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -3605,7 +3615,7 @@ public final class NormalizedNodeMessages {
         getTypeBytes() {
       java.lang.Object ref = type_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         type_ = b;
@@ -3627,7 +3637,7 @@ public final class NormalizedNodeMessages {
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 3;</code>
      */
-    public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder> 
+    public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
         getAttributesOrBuilderList() {
       return attributes_;
     }
@@ -3663,7 +3673,7 @@ public final class NormalizedNodeMessages {
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.Node child = 4;</code>
      */
-    public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> 
+    public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
         getChildOrBuilderList() {
       return child_;
     }
@@ -3704,7 +3714,7 @@ public final class NormalizedNodeMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -3720,7 +3730,7 @@ public final class NormalizedNodeMessages {
         getValueBytes() {
       java.lang.Object ref = value_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         value_ = b;
@@ -3747,7 +3757,7 @@ public final class NormalizedNodeMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -3763,7 +3773,7 @@ public final class NormalizedNodeMessages {
         getValueTypeBytes() {
       java.lang.Object ref = valueType_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         valueType_ = b;
@@ -4202,7 +4212,7 @@ public final class NormalizedNodeMessages {
               attributesBuilder_ = null;
               attributes_ = other.attributes_;
               bitField0_ = (bitField0_ & ~0x00000004);
-              attributesBuilder_ = 
+              attributesBuilder_ =
                 com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
                    getAttributesFieldBuilder() : null;
             } else {
@@ -4228,7 +4238,7 @@ public final class NormalizedNodeMessages {
               childBuilder_ = null;
               child_ = other.child_;
               bitField0_ = (bitField0_ & ~0x00000008);
-              childBuilder_ = 
+              childBuilder_ =
                 com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
                    getChildFieldBuilder() : null;
             } else {
@@ -4266,19 +4276,19 @@ public final class NormalizedNodeMessages {
       public final boolean isInitialized() {
         for (int i = 0; i < getAttributesCount(); i++) {
           if (!getAttributes(i).isInitialized()) {
-            
+
             return false;
           }
         }
         for (int i = 0; i < getChildCount(); i++) {
           if (!getChild(i).isInitialized()) {
-            
+
             return false;
           }
         }
         if (hasInstanceIdentifierValue()) {
           if (!getInstanceIdentifierValue().isInitialized()) {
-            
+
             return false;
           }
         }
@@ -4333,7 +4343,7 @@ public final class NormalizedNodeMessages {
           getPathBytes() {
         java.lang.Object ref = path_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           path_ = b;
@@ -4407,7 +4417,7 @@ public final class NormalizedNodeMessages {
           getTypeBytes() {
         java.lang.Object ref = type_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           type_ = b;
@@ -4647,7 +4657,7 @@ public final class NormalizedNodeMessages {
       /**
        * <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 3;</code>
        */
-      public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder> 
+      public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
            getAttributesOrBuilderList() {
         if (attributesBuilder_ != null) {
           return attributesBuilder_.getMessageOrBuilderList();
@@ -4673,12 +4683,12 @@ public final class NormalizedNodeMessages {
       /**
        * <code>repeated .org.opendaylight.controller.mdsal.Attribute attributes = 3;</code>
        */
-      public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute.Builder> 
+      public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute.Builder>
            getAttributesBuilderList() {
         return getAttributesFieldBuilder().getBuilderList();
       }
       private com.google.protobuf.RepeatedFieldBuilder<
-          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder> 
+          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Attribute.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.AttributeOrBuilder>
           getAttributesFieldBuilder() {
         if (attributesBuilder_ == null) {
           attributesBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
@@ -4887,7 +4897,7 @@ public final class NormalizedNodeMessages {
       /**
        * <code>repeated .org.opendaylight.controller.mdsal.Node child = 4;</code>
        */
-      public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> 
+      public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
            getChildOrBuilderList() {
         if (childBuilder_ != null) {
           return childBuilder_.getMessageOrBuilderList();
@@ -4913,12 +4923,12 @@ public final class NormalizedNodeMessages {
       /**
        * <code>repeated .org.opendaylight.controller.mdsal.Node child = 4;</code>
        */
-      public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder> 
+      public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder>
            getChildBuilderList() {
         return getChildFieldBuilder().getBuilderList();
       }
       private com.google.protobuf.RepeatedFieldBuilder<
-          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> 
+          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
           getChildFieldBuilder() {
         if (childBuilder_ == null) {
           childBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
@@ -4961,7 +4971,7 @@ public final class NormalizedNodeMessages {
           getValueBytes() {
         java.lang.Object ref = value_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           value_ = b;
@@ -5035,7 +5045,7 @@ public final class NormalizedNodeMessages {
           getValueTypeBytes() {
         java.lang.Object ref = valueType_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           valueType_ = b;
@@ -5277,7 +5287,7 @@ public final class NormalizedNodeMessages {
        * <code>optional .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierValue = 8;</code>
        */
       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> 
+          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<
@@ -5459,7 +5469,7 @@ public final class NormalizedNodeMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -5475,7 +5485,7 @@ public final class NormalizedNodeMessages {
         getParentPathBytes() {
       java.lang.Object ref = parentPath_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         parentPath_ = b;
@@ -5751,12 +5761,12 @@ public final class NormalizedNodeMessages {
 
       public final boolean isInitialized() {
         if (!hasParentPath()) {
-          
+
           return false;
         }
         if (hasNormalizedNode()) {
           if (!getNormalizedNode().isInitialized()) {
-            
+
             return false;
           }
         }
@@ -5811,7 +5821,7 @@ public final class NormalizedNodeMessages {
           getParentPathBytes() {
         java.lang.Object ref = parentPath_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           parentPath_ = b;
@@ -5960,7 +5970,7 @@ public final class NormalizedNodeMessages {
        * <code>optional .org.opendaylight.controller.mdsal.Node normalizedNode = 2;</code>
        */
       private com.google.protobuf.SingleFieldBuilder<
-          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> 
+          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
           getNormalizedNodeFieldBuilder() {
         if (normalizedNodeBuilder_ == null) {
           normalizedNodeBuilder_ = new com.google.protobuf.SingleFieldBuilder<
@@ -6431,16 +6441,16 @@ public final class NormalizedNodeMessages {
 
       public final boolean isInitialized() {
         if (!hasInstanceIdentifierPath()) {
-          
+
           return false;
         }
         if (!getInstanceIdentifierPath().isInitialized()) {
-          
+
           return false;
         }
         if (hasNormalizedNode()) {
           if (!getNormalizedNode().isInitialized()) {
-            
+
             return false;
           }
         }
@@ -6570,7 +6580,7 @@ public final class NormalizedNodeMessages {
        * <code>required .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierPath = 1;</code>
        */
       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> 
+          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>
           getInstanceIdentifierPathFieldBuilder() {
         if (instanceIdentifierPathBuilder_ == null) {
           instanceIdentifierPathBuilder_ = new com.google.protobuf.SingleFieldBuilder<
@@ -6687,7 +6697,7 @@ public final class NormalizedNodeMessages {
        * <code>optional .org.opendaylight.controller.mdsal.Node normalizedNode = 2;</code>
        */
       private com.google.protobuf.SingleFieldBuilder<
-          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> 
+          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
           getNormalizedNodeFieldBuilder() {
         if (normalizedNodeBuilder_ == null) {
           normalizedNodeBuilder_ = new com.google.protobuf.SingleFieldBuilder<
@@ -6718,7 +6728,7 @@ public final class NormalizedNodeMessages {
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.NodeMapEntry mapEntries = 1;</code>
      */
-    java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntry> 
+    java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntry>
         getMapEntriesList();
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.NodeMapEntry mapEntries = 1;</code>
@@ -6731,7 +6741,7 @@ public final class NormalizedNodeMessages {
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.NodeMapEntry mapEntries = 1;</code>
      */
-    java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntryOrBuilder> 
+    java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntryOrBuilder>
         getMapEntriesOrBuilderList();
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.NodeMapEntry mapEntries = 1;</code>
@@ -6852,7 +6862,7 @@ public final class NormalizedNodeMessages {
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.NodeMapEntry mapEntries = 1;</code>
      */
-    public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntryOrBuilder> 
+    public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntryOrBuilder>
         getMapEntriesOrBuilderList() {
       return mapEntries_;
     }
@@ -7105,7 +7115,7 @@ public final class NormalizedNodeMessages {
               mapEntriesBuilder_ = null;
               mapEntries_ = other.mapEntries_;
               bitField0_ = (bitField0_ & ~0x00000001);
-              mapEntriesBuilder_ = 
+              mapEntriesBuilder_ =
                 com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
                    getMapEntriesFieldBuilder() : null;
             } else {
@@ -7120,7 +7130,7 @@ public final class NormalizedNodeMessages {
       public final boolean isInitialized() {
         for (int i = 0; i < getMapEntriesCount(); i++) {
           if (!getMapEntries(i).isInitialized()) {
-            
+
             return false;
           }
         }
@@ -7341,7 +7351,7 @@ public final class NormalizedNodeMessages {
       /**
        * <code>repeated .org.opendaylight.controller.mdsal.NodeMapEntry mapEntries = 1;</code>
        */
-      public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntryOrBuilder> 
+      public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntryOrBuilder>
            getMapEntriesOrBuilderList() {
         if (mapEntriesBuilder_ != null) {
           return mapEntriesBuilder_.getMessageOrBuilderList();
@@ -7367,12 +7377,12 @@ public final class NormalizedNodeMessages {
       /**
        * <code>repeated .org.opendaylight.controller.mdsal.NodeMapEntry mapEntries = 1;</code>
        */
-      public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntry.Builder> 
+      public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntry.Builder>
            getMapEntriesBuilderList() {
         return getMapEntriesFieldBuilder().getBuilderList();
       }
       private com.google.protobuf.RepeatedFieldBuilder<
-          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntry, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntry.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntryOrBuilder> 
+          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntry, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntry.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapEntryOrBuilder>
           getMapEntriesFieldBuilder() {
         if (mapEntriesBuilder_ == null) {
           mapEntriesBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
index 29e54571d30b6ddbb9392c6f3edbed83f09c5db8..7cee40df7af8c7ccfbf7925128e5641a4e514c80 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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
+ *
+ */
+
 // Generated by the protocol buffer compiler.  DO NOT EDIT!
 // source: SimpleNormalizedNode.proto
 
@@ -159,7 +169,7 @@ public final class SimpleNormalizedNodeMessage {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -175,7 +185,7 @@ public final class SimpleNormalizedNodeMessage {
         getNodeIdentifierBytes() {
       java.lang.Object ref = nodeIdentifier_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         nodeIdentifier_ = b;
@@ -202,7 +212,7 @@ public final class SimpleNormalizedNodeMessage {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -218,7 +228,7 @@ public final class SimpleNormalizedNodeMessage {
         getXmlStringBytes() {
       java.lang.Object ref = xmlString_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         xmlString_ = b;
@@ -463,11 +473,11 @@ public final class SimpleNormalizedNodeMessage {
 
       public final boolean isInitialized() {
         if (!hasNodeIdentifier()) {
-          
+
           return false;
         }
         if (!hasXmlString()) {
-          
+
           return false;
         }
         return true;
@@ -521,7 +531,7 @@ public final class SimpleNormalizedNodeMessage {
           getNodeIdentifierBytes() {
         java.lang.Object ref = nodeIdentifier_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           nodeIdentifier_ = b;
@@ -595,7 +605,7 @@ public final class SimpleNormalizedNodeMessage {
           getXmlStringBytes() {
         java.lang.Object ref = xmlString_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           xmlString_ = b;
index 201883476838f3c592f63e47c08fcde5a661b29a..1a9811207387966e2ccb256899214f4cfffb8460 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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
+ *
+ */
+
 // Generated by the protocol buffer compiler.  DO NOT EDIT!
 // source: DataChangeListener.proto
 
@@ -85,7 +95,7 @@ public final class DataChangeListenerMessages {
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.InstanceIdentifier removedPaths = 6;</code>
      */
-    java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier> 
+    java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier>
         getRemovedPathsList();
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.InstanceIdentifier removedPaths = 6;</code>
@@ -98,7 +108,7 @@ public final class DataChangeListenerMessages {
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.InstanceIdentifier removedPaths = 6;</code>
      */
-    java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> 
+    java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
         getRemovedPathsOrBuilderList();
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.InstanceIdentifier removedPaths = 6;</code>
@@ -395,7 +405,7 @@ public final class DataChangeListenerMessages {
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.InstanceIdentifier removedPaths = 6;</code>
      */
-    public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> 
+    public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
         getRemovedPathsOrBuilderList() {
       return removedPaths_;
     }
@@ -810,7 +820,7 @@ public final class DataChangeListenerMessages {
               removedPathsBuilder_ = null;
               removedPaths_ = other.removedPaths_;
               bitField0_ = (bitField0_ & ~0x00000020);
-              removedPathsBuilder_ = 
+              removedPathsBuilder_ =
                 com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
                    getRemovedPathsFieldBuilder() : null;
             } else {
@@ -825,37 +835,37 @@ public final class DataChangeListenerMessages {
       public final boolean isInitialized() {
         if (hasOriginalSubTree()) {
           if (!getOriginalSubTree().isInitialized()) {
-            
+
             return false;
           }
         }
         if (hasUpdatedSubTree()) {
           if (!getUpdatedSubTree().isInitialized()) {
-            
+
             return false;
           }
         }
         if (hasOriginalData()) {
           if (!getOriginalData().isInitialized()) {
-            
+
             return false;
           }
         }
         if (hasUpdatedData()) {
           if (!getUpdatedData().isInitialized()) {
-            
+
             return false;
           }
         }
         if (hasCreatedData()) {
           if (!getCreatedData().isInitialized()) {
-            
+
             return false;
           }
         }
         for (int i = 0; i < getRemovedPathsCount(); i++) {
           if (!getRemovedPaths(i).isInitialized()) {
-            
+
             return false;
           }
         }
@@ -985,7 +995,7 @@ public final class DataChangeListenerMessages {
        * <code>optional .org.opendaylight.controller.mdsal.Node originalSubTree = 1;</code>
        */
       private com.google.protobuf.SingleFieldBuilder<
-          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> 
+          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
           getOriginalSubTreeFieldBuilder() {
         if (originalSubTreeBuilder_ == null) {
           originalSubTreeBuilder_ = new com.google.protobuf.SingleFieldBuilder<
@@ -1102,7 +1112,7 @@ public final class DataChangeListenerMessages {
        * <code>optional .org.opendaylight.controller.mdsal.Node updatedSubTree = 2;</code>
        */
       private com.google.protobuf.SingleFieldBuilder<
-          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> 
+          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
           getUpdatedSubTreeFieldBuilder() {
         if (updatedSubTreeBuilder_ == null) {
           updatedSubTreeBuilder_ = new com.google.protobuf.SingleFieldBuilder<
@@ -1219,7 +1229,7 @@ public final class DataChangeListenerMessages {
        * <code>optional .org.opendaylight.controller.mdsal.NodeMap originalData = 3;</code>
        */
       private com.google.protobuf.SingleFieldBuilder<
-          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapOrBuilder> 
+          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapOrBuilder>
           getOriginalDataFieldBuilder() {
         if (originalDataBuilder_ == null) {
           originalDataBuilder_ = new com.google.protobuf.SingleFieldBuilder<
@@ -1336,7 +1346,7 @@ public final class DataChangeListenerMessages {
        * <code>optional .org.opendaylight.controller.mdsal.NodeMap updatedData = 4;</code>
        */
       private com.google.protobuf.SingleFieldBuilder<
-          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapOrBuilder> 
+          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapOrBuilder>
           getUpdatedDataFieldBuilder() {
         if (updatedDataBuilder_ == null) {
           updatedDataBuilder_ = new com.google.protobuf.SingleFieldBuilder<
@@ -1453,7 +1463,7 @@ public final class DataChangeListenerMessages {
        * <code>optional .org.opendaylight.controller.mdsal.NodeMap createdData = 5;</code>
        */
       private com.google.protobuf.SingleFieldBuilder<
-          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapOrBuilder> 
+          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMap.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeMapOrBuilder>
           getCreatedDataFieldBuilder() {
         if (createdDataBuilder_ == null) {
           createdDataBuilder_ = new com.google.protobuf.SingleFieldBuilder<
@@ -1661,7 +1671,7 @@ public final class DataChangeListenerMessages {
       /**
        * <code>repeated .org.opendaylight.controller.mdsal.InstanceIdentifier removedPaths = 6;</code>
        */
-      public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder> 
+      public java.util.List<? extends org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifierOrBuilder>
            getRemovedPathsOrBuilderList() {
         if (removedPathsBuilder_ != null) {
           return removedPathsBuilder_.getMessageOrBuilderList();
@@ -1687,12 +1697,12 @@ public final class DataChangeListenerMessages {
       /**
        * <code>repeated .org.opendaylight.controller.mdsal.InstanceIdentifier removedPaths = 6;</code>
        */
-      public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder> 
+      public java.util.List<org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.InstanceIdentifier.Builder>
            getRemovedPathsBuilderList() {
         return getRemovedPathsFieldBuilder().getBuilderList();
       }
       private com.google.protobuf.RepeatedFieldBuilder<
-          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> 
+          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>
           getRemovedPathsFieldBuilder() {
         if (removedPathsBuilder_ == null) {
           removedPathsBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
index eaa90012dbdc58425adc8fbfa2ea4e467f0c4379..088630aa32167e648db660196345c59db21d4923 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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
+ *
+ */
+
 // Generated by the protocol buffer compiler.  DO NOT EDIT!
 // source: Persistent.proto
 
@@ -193,7 +203,7 @@ public final class PersistentMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -209,7 +219,7 @@ public final class PersistentMessages {
         getTypeBytes() {
       java.lang.Object ref = type_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         type_ = b;
@@ -541,20 +551,20 @@ public final class PersistentMessages {
 
       public final boolean isInitialized() {
         if (!hasType()) {
-          
+
           return false;
         }
         if (!hasPath()) {
-          
+
           return false;
         }
         if (!getPath().isInitialized()) {
-          
+
           return false;
         }
         if (hasData()) {
           if (!getData().isInitialized()) {
-            
+
             return false;
           }
         }
@@ -609,7 +619,7 @@ public final class PersistentMessages {
           getTypeBytes() {
         java.lang.Object ref = type_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           type_ = b;
@@ -758,7 +768,7 @@ public final class PersistentMessages {
        * <code>required .org.opendaylight.controller.mdsal.InstanceIdentifier path = 2;</code>
        */
       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> 
+          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>
           getPathFieldBuilder() {
         if (pathBuilder_ == null) {
           pathBuilder_ = new com.google.protobuf.SingleFieldBuilder<
@@ -875,7 +885,7 @@ public final class PersistentMessages {
        * <code>optional .org.opendaylight.controller.mdsal.Node data = 3;</code>
        */
       private com.google.protobuf.SingleFieldBuilder<
-          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> 
+          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
           getDataFieldBuilder() {
         if (dataBuilder_ == null) {
           dataBuilder_ = new com.google.protobuf.SingleFieldBuilder<
@@ -906,7 +916,7 @@ public final class PersistentMessages {
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.Modification modification = 1;</code>
      */
-    java.util.List<org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.Modification> 
+    java.util.List<org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.Modification>
         getModificationList();
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.Modification modification = 1;</code>
@@ -919,7 +929,7 @@ public final class PersistentMessages {
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.Modification modification = 1;</code>
      */
-    java.util.List<? extends org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.ModificationOrBuilder> 
+    java.util.List<? extends org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.ModificationOrBuilder>
         getModificationOrBuilderList();
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.Modification modification = 1;</code>
@@ -1040,7 +1050,7 @@ public final class PersistentMessages {
     /**
      * <code>repeated .org.opendaylight.controller.mdsal.Modification modification = 1;</code>
      */
-    public java.util.List<? extends org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.ModificationOrBuilder> 
+    public java.util.List<? extends org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.ModificationOrBuilder>
         getModificationOrBuilderList() {
       return modification_;
     }
@@ -1293,7 +1303,7 @@ public final class PersistentMessages {
               modificationBuilder_ = null;
               modification_ = other.modification_;
               bitField0_ = (bitField0_ & ~0x00000001);
-              modificationBuilder_ = 
+              modificationBuilder_ =
                 com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
                    getModificationFieldBuilder() : null;
             } else {
@@ -1308,7 +1318,7 @@ public final class PersistentMessages {
       public final boolean isInitialized() {
         for (int i = 0; i < getModificationCount(); i++) {
           if (!getModification(i).isInitialized()) {
-            
+
             return false;
           }
         }
@@ -1529,7 +1539,7 @@ public final class PersistentMessages {
       /**
        * <code>repeated .org.opendaylight.controller.mdsal.Modification modification = 1;</code>
        */
-      public java.util.List<? extends org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.ModificationOrBuilder> 
+      public java.util.List<? extends org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.ModificationOrBuilder>
            getModificationOrBuilderList() {
         if (modificationBuilder_ != null) {
           return modificationBuilder_.getMessageOrBuilderList();
@@ -1555,12 +1565,12 @@ public final class PersistentMessages {
       /**
        * <code>repeated .org.opendaylight.controller.mdsal.Modification modification = 1;</code>
        */
-      public java.util.List<org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.Modification.Builder> 
+      public java.util.List<org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.Modification.Builder>
            getModificationBuilderList() {
         return getModificationFieldBuilder().getBuilderList();
       }
       private com.google.protobuf.RepeatedFieldBuilder<
-          org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.Modification, org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.Modification.Builder, org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.ModificationOrBuilder> 
+          org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.Modification, org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.Modification.Builder, org.opendaylight.controller.protobuff.messages.persistent.PersistentMessages.ModificationOrBuilder>
           getModificationFieldBuilder() {
         if (modificationBuilder_ == null) {
           modificationBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
index e06dd0d42982d779b8aa40931338b88c528d6069..0f439d8c7cc7f1c84ee9fdc80bf902a36d4094eb 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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
+ *
+ */
+
 // Generated by the protocol buffer compiler.  DO NOT EDIT!
 // source: ListenerRegistration.proto
 
@@ -837,7 +847,7 @@ public final class ListenerRegistrationMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -853,7 +863,7 @@ public final class ListenerRegistrationMessages {
         getDataChangeListenerActorPathBytes() {
       java.lang.Object ref = dataChangeListenerActorPath_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         dataChangeListenerActorPath_ = b;
@@ -1146,19 +1156,19 @@ public final class ListenerRegistrationMessages {
 
       public final boolean isInitialized() {
         if (!hasInstanceIdentifierPath()) {
-          
+
           return false;
         }
         if (!hasDataChangeListenerActorPath()) {
-          
+
           return false;
         }
         if (!hasDataChangeScope()) {
-          
+
           return false;
         }
         if (!getInstanceIdentifierPath().isInitialized()) {
-          
+
           return false;
         }
         return true;
@@ -1287,7 +1297,7 @@ public final class ListenerRegistrationMessages {
        * <code>required .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierPath = 1;</code>
        */
       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> 
+          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>
           getInstanceIdentifierPathFieldBuilder() {
         if (instanceIdentifierPathBuilder_ == null) {
           instanceIdentifierPathBuilder_ = new com.google.protobuf.SingleFieldBuilder<
@@ -1329,7 +1339,7 @@ public final class ListenerRegistrationMessages {
           getDataChangeListenerActorPathBytes() {
         java.lang.Object ref = dataChangeListenerActorPath_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           dataChangeListenerActorPath_ = b;
@@ -1556,7 +1566,7 @@ public final class ListenerRegistrationMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -1572,7 +1582,7 @@ public final class ListenerRegistrationMessages {
         getListenerRegistrationPathBytes() {
       java.lang.Object ref = listenerRegistrationPath_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         listenerRegistrationPath_ = b;
@@ -1801,7 +1811,7 @@ public final class ListenerRegistrationMessages {
 
       public final boolean isInitialized() {
         if (!hasListenerRegistrationPath()) {
-          
+
           return false;
         }
         return true;
@@ -1855,7 +1865,7 @@ public final class ListenerRegistrationMessages {
           getListenerRegistrationPathBytes() {
         java.lang.Object ref = listenerRegistrationPath_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           listenerRegistrationPath_ = b;
index 7c2a47e1b0daa740f96acf355b4281f9331ec7f2..71418635910a50192fc2b046a737f0be888b84b5 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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
+ *
+ */
+
 // Generated by the protocol buffer compiler.  DO NOT EDIT!
 // source: ShardManager.proto
 
@@ -139,7 +149,7 @@ public final class ShardManagerMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -155,7 +165,7 @@ public final class ShardManagerMessages {
         getShardNameBytes() {
       java.lang.Object ref = shardName_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         shardName_ = b;
@@ -377,7 +387,7 @@ public final class ShardManagerMessages {
 
       public final boolean isInitialized() {
         if (!hasShardName()) {
-          
+
           return false;
         }
         return true;
@@ -431,7 +441,7 @@ public final class ShardManagerMessages {
           getShardNameBytes() {
         java.lang.Object ref = shardName_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           shardName_ = b;
@@ -618,7 +628,7 @@ public final class ShardManagerMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -634,7 +644,7 @@ public final class ShardManagerMessages {
         getPrimaryPathBytes() {
       java.lang.Object ref = primaryPath_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         primaryPath_ = b;
@@ -856,7 +866,7 @@ public final class ShardManagerMessages {
 
       public final boolean isInitialized() {
         if (!hasPrimaryPath()) {
-          
+
           return false;
         }
         return true;
@@ -910,7 +920,7 @@ public final class ShardManagerMessages {
           getPrimaryPathBytes() {
         java.lang.Object ref = primaryPath_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           primaryPath_ = b;
@@ -1097,7 +1107,7 @@ public final class ShardManagerMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -1113,7 +1123,7 @@ public final class ShardManagerMessages {
         getShardNameBytes() {
       java.lang.Object ref = shardName_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         shardName_ = b;
@@ -1335,7 +1345,7 @@ public final class ShardManagerMessages {
 
       public final boolean isInitialized() {
         if (!hasShardName()) {
-          
+
           return false;
         }
         return true;
@@ -1389,7 +1399,7 @@ public final class ShardManagerMessages {
           getShardNameBytes() {
         java.lang.Object ref = shardName_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           shardName_ = b;
index 3f354ba40eeea6751b1410c47a5bcf7b39db86a6..68bf32533642fb391facf4c346942cc42c448195 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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
+ *
+ */
+
 // Generated by the protocol buffer compiler.  DO NOT EDIT!
 // source: ShardTransactionChain.proto
 
@@ -1066,7 +1076,7 @@ public final class ShardTransactionChainMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -1082,7 +1092,7 @@ public final class ShardTransactionChainMessages {
         getTransactionChainPathBytes() {
       java.lang.Object ref = transactionChainPath_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         transactionChainPath_ = b;
@@ -1304,7 +1314,7 @@ public final class ShardTransactionChainMessages {
 
       public final boolean isInitialized() {
         if (!hasTransactionChainPath()) {
-          
+
           return false;
         }
         return true;
@@ -1358,7 +1368,7 @@ public final class ShardTransactionChainMessages {
           getTransactionChainPathBytes() {
         java.lang.Object ref = transactionChainPath_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           transactionChainPath_ = b;
index ee2c70423e14fcaa8775d285f22cd2a8bb02f324..52411f322b96b9b6c897a3ff870b1b3b7cd439f9 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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
+ *
+ */
+
 // Generated by the protocol buffer compiler.  DO NOT EDIT!
 // source: ShardTransaction.proto
 
@@ -757,7 +767,7 @@ public final class ShardTransactionMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -773,7 +783,7 @@ public final class ShardTransactionMessages {
         getTransactionIdBytes() {
       java.lang.Object ref = transactionId_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         transactionId_ = b;
@@ -995,7 +1005,7 @@ public final class ShardTransactionMessages {
 
       public final boolean isInitialized() {
         if (!hasTransactionId()) {
-          
+
           return false;
         }
         return true;
@@ -1049,7 +1059,7 @@ public final class ShardTransactionMessages {
           getTransactionIdBytes() {
         java.lang.Object ref = transactionId_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           transactionId_ = b;
@@ -1256,7 +1266,7 @@ public final class ShardTransactionMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -1272,7 +1282,7 @@ public final class ShardTransactionMessages {
         getTransactionActorPathBytes() {
       java.lang.Object ref = transactionActorPath_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         transactionActorPath_ = b;
@@ -1299,7 +1309,7 @@ public final class ShardTransactionMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -1315,7 +1325,7 @@ public final class ShardTransactionMessages {
         getTransactionIdBytes() {
       java.lang.Object ref = transactionId_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         transactionId_ = b;
@@ -1560,11 +1570,11 @@ public final class ShardTransactionMessages {
 
       public final boolean isInitialized() {
         if (!hasTransactionActorPath()) {
-          
+
           return false;
         }
         if (!hasTransactionId()) {
-          
+
           return false;
         }
         return true;
@@ -1618,7 +1628,7 @@ public final class ShardTransactionMessages {
           getTransactionActorPathBytes() {
         java.lang.Object ref = transactionActorPath_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           transactionActorPath_ = b;
@@ -1692,7 +1702,7 @@ public final class ShardTransactionMessages {
           getTransactionIdBytes() {
         java.lang.Object ref = transactionId_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           transactionId_ = b;
@@ -2188,7 +2198,7 @@ public final class ShardTransactionMessages {
       if (ref instanceof java.lang.String) {
         return (java.lang.String) ref;
       } else {
-        com.google.protobuf.ByteString bs = 
+        com.google.protobuf.ByteString bs =
             (com.google.protobuf.ByteString) ref;
         java.lang.String s = bs.toStringUtf8();
         if (bs.isValidUtf8()) {
@@ -2204,7 +2214,7 @@ public final class ShardTransactionMessages {
         getActorPathBytes() {
       java.lang.Object ref = actorPath_;
       if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b = 
+        com.google.protobuf.ByteString b =
             com.google.protobuf.ByteString.copyFromUtf8(
                 (java.lang.String) ref);
         actorPath_ = b;
@@ -2426,7 +2436,7 @@ public final class ShardTransactionMessages {
 
       public final boolean isInitialized() {
         if (!hasActorPath()) {
-          
+
           return false;
         }
         return true;
@@ -2480,7 +2490,7 @@ public final class ShardTransactionMessages {
           getActorPathBytes() {
         java.lang.Object ref = actorPath_;
         if (ref instanceof String) {
-          com.google.protobuf.ByteString b = 
+          com.google.protobuf.ByteString b =
               com.google.protobuf.ByteString.copyFromUtf8(
                   (java.lang.String) ref);
           actorPath_ = b;
@@ -2902,11 +2912,11 @@ public final class ShardTransactionMessages {
 
       public final boolean isInitialized() {
         if (!hasInstanceIdentifierPathArguments()) {
-          
+
           return false;
         }
         if (!getInstanceIdentifierPathArguments().isInitialized()) {
-          
+
           return false;
         }
         return true;
@@ -3035,7 +3045,7 @@ public final class ShardTransactionMessages {
        * <code>required .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierPathArguments = 1;</code>
        */
       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> 
+          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>
           getInstanceIdentifierPathArgumentsFieldBuilder() {
         if (instanceIdentifierPathArgumentsBuilder_ == null) {
           instanceIdentifierPathArgumentsBuilder_ = new com.google.protobuf.SingleFieldBuilder<
@@ -3734,11 +3744,11 @@ public final class ShardTransactionMessages {
 
       public final boolean isInitialized() {
         if (!hasInstanceIdentifierPathArguments()) {
-          
+
           return false;
         }
         if (!getInstanceIdentifierPathArguments().isInitialized()) {
-          
+
           return false;
         }
         return true;
@@ -3867,7 +3877,7 @@ public final class ShardTransactionMessages {
        * <code>required .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierPathArguments = 1;</code>
        */
       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> 
+          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>
           getInstanceIdentifierPathArgumentsFieldBuilder() {
         if (instanceIdentifierPathArgumentsBuilder_ == null) {
           instanceIdentifierPathArgumentsBuilder_ = new com.google.protobuf.SingleFieldBuilder<
@@ -4256,7 +4266,7 @@ public final class ShardTransactionMessages {
       public final boolean isInitialized() {
         if (hasNormalizedNode()) {
           if (!getNormalizedNode().isInitialized()) {
-            
+
             return false;
           }
         }
@@ -4386,7 +4396,7 @@ public final class ShardTransactionMessages {
        * <code>optional .org.opendaylight.controller.mdsal.Node normalizedNode = 1;</code>
        */
       private com.google.protobuf.SingleFieldBuilder<
-          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> 
+          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
           getNormalizedNodeFieldBuilder() {
         if (normalizedNodeBuilder_ == null) {
           normalizedNodeBuilder_ = new com.google.protobuf.SingleFieldBuilder<
@@ -4859,19 +4869,19 @@ public final class ShardTransactionMessages {
 
       public final boolean isInitialized() {
         if (!hasInstanceIdentifierPathArguments()) {
-          
+
           return false;
         }
         if (!hasNormalizedNode()) {
-          
+
           return false;
         }
         if (!getInstanceIdentifierPathArguments().isInitialized()) {
-          
+
           return false;
         }
         if (!getNormalizedNode().isInitialized()) {
-          
+
           return false;
         }
         return true;
@@ -5000,7 +5010,7 @@ public final class ShardTransactionMessages {
        * <code>required .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierPathArguments = 1;</code>
        */
       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> 
+          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>
           getInstanceIdentifierPathArgumentsFieldBuilder() {
         if (instanceIdentifierPathArgumentsBuilder_ == null) {
           instanceIdentifierPathArgumentsBuilder_ = new com.google.protobuf.SingleFieldBuilder<
@@ -5117,7 +5127,7 @@ public final class ShardTransactionMessages {
        * <code>required .org.opendaylight.controller.mdsal.Node normalizedNode = 2;</code>
        */
       private com.google.protobuf.SingleFieldBuilder<
-          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> 
+          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
           getNormalizedNodeFieldBuilder() {
         if (normalizedNodeBuilder_ == null) {
           normalizedNodeBuilder_ = new com.google.protobuf.SingleFieldBuilder<
@@ -5899,19 +5909,19 @@ public final class ShardTransactionMessages {
 
       public final boolean isInitialized() {
         if (!hasInstanceIdentifierPathArguments()) {
-          
+
           return false;
         }
         if (!hasNormalizedNode()) {
-          
+
           return false;
         }
         if (!getInstanceIdentifierPathArguments().isInitialized()) {
-          
+
           return false;
         }
         if (!getNormalizedNode().isInitialized()) {
-          
+
           return false;
         }
         return true;
@@ -6040,7 +6050,7 @@ public final class ShardTransactionMessages {
        * <code>required .org.opendaylight.controller.mdsal.InstanceIdentifier instanceIdentifierPathArguments = 1;</code>
        */
       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> 
+          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>
           getInstanceIdentifierPathArgumentsFieldBuilder() {
         if (instanceIdentifierPathArgumentsBuilder_ == null) {
           instanceIdentifierPathArgumentsBuilder_ = new com.google.protobuf.SingleFieldBuilder<
@@ -6157,7 +6167,7 @@ public final class ShardTransactionMessages {
        * <code>required .org.opendaylight.controller.mdsal.Node normalizedNode = 2;</code>
        */
       private com.google.protobuf.SingleFieldBuilder<
-          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder> 
+          org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node.Builder, org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.NodeOrBuilder>
           getNormalizedNodeFieldBuilder() {
         if (normalizedNodeBuilder_ == null) {
           normalizedNodeBuilder_ = new com.google.protobuf.SingleFieldBuilder<
index 4ccbc97f351721e08897cee463829d4cf09c451c..1b85d46fc6ebdfa9b13de079db728b9dadf2beac 100644 (file)
@@ -1,9 +1,11 @@
 /*
- * 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
+ *  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;
@@ -15,9 +17,9 @@ import org.opendaylight.controller.cluster.datastore.node.utils.NodeIdentifierFa
 import org.opendaylight.controller.cluster.datastore.node.utils.NormalizedNodeGetter;
 import org.opendaylight.controller.cluster.datastore.node.utils.NormalizedNodeNavigator;
 import org.opendaylight.controller.cluster.datastore.util.TestModel;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Container;
 import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages.Node;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
@@ -32,127 +34,147 @@ public class NormalizedNodeToNodeCodecTest {
 
 
 
-    private SchemaContext schemaContext;
+  private SchemaContext schemaContext;
 
-    @Before
-    public void setUp(){
-        schemaContext = TestModel.createTestContext();
-        assertNotNull("Schema context must not be null.", schemaContext);
-    }
+  @Before
+  public void setUp() {
+    schemaContext = TestModel.createTestContext();
+    assertNotNull("Schema context must not be null.", schemaContext);
+  }
 
-    private YangInstanceIdentifier instanceIdentifierFromString(String s){
+  private YangInstanceIdentifier instanceIdentifierFromString(String s) {
 
-        String[] ids = s.split("/");
+    String[] ids = s.split("/");
 
-        List<YangInstanceIdentifier.PathArgument> pathArguments = new ArrayList<>();
-        for(String nodeId : ids){
-            if(!"".equals(nodeId)) {
-                pathArguments.add(NodeIdentifierFactory.getArgument(nodeId));
-            }
-        }
-        final YangInstanceIdentifier instanceIdentifier = YangInstanceIdentifier.create(pathArguments);
-        return instanceIdentifier;
+    List<YangInstanceIdentifier.PathArgument> pathArguments = new ArrayList<>();
+    for (String nodeId : ids) {
+      if (!"".equals(nodeId)) {
+        pathArguments.add(NodeIdentifierFactory.getArgument(nodeId));
+      }
     }
+    final YangInstanceIdentifier instanceIdentifier =
+        YangInstanceIdentifier.create(pathArguments);
+    return instanceIdentifier;
+  }
 
 
-    @Test
-    public void testNormalizeNodeAttributesToProtoBuffNode(){
-        final NormalizedNode<?, ?> documentOne = TestModel.createTestContainer();
-        String id = "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test" +
-            "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)outer-list" +
-            "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)outer-list[{(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id=2}]" +
-            "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id";
+  @Test
+  public void testNormalizeNodeAttributesToProtoBuffNode() {
+    final NormalizedNode<?, ?> documentOne = TestModel.createTestContainer();
+    String id =
+        "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test"
+            + "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)outer-list"
+            + "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)outer-list[{(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id=2}]"
+            + "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id";
 
-        NormalizedNodeGetter normalizedNodeGetter = new NormalizedNodeGetter(id);
-        new NormalizedNodeNavigator(normalizedNodeGetter).navigate(
-            YangInstanceIdentifier.builder().build().toString(), documentOne);
+    NormalizedNodeGetter normalizedNodeGetter = new NormalizedNodeGetter(id);
+    new NormalizedNodeNavigator(normalizedNodeGetter).navigate(
+        YangInstanceIdentifier.builder().build().toString(), documentOne);
 
-        // Validate the value of id can be retrieved from the normalized node
-        NormalizedNode output = normalizedNodeGetter.getOutput();
-        assertNotNull(output);
+    // Validate the value of id can be retrieved from the normalized node
+    NormalizedNode output = normalizedNodeGetter.getOutput();
+    assertNotNull(output);
 
 
-      NormalizedNodeToNodeCodec codec = new NormalizedNodeToNodeCodec(schemaContext);
-      Container container = codec.encode(instanceIdentifierFromString(id),output);
+    NormalizedNodeToNodeCodec codec =
+        new NormalizedNodeToNodeCodec(schemaContext);
+    Container container =
+        codec.encode(instanceIdentifierFromString(id), output);
 
-       assertNotNull(container);
-       assertEquals(id, container.getParentPath()+"/"+container.getNormalizedNode().getPath()) ;
+    assertNotNull(container);
+    assertEquals(id, container.getParentPath() + "/"
+        + container.getNormalizedNode().getPath());
 
-      // Decode the normalized node from the ProtocolBuffer form
-      //first get the node representation of normalized node
-      final Node node = container.getNormalizedNode();
+    // Decode the normalized node from the ProtocolBuffer form
+    // first get the node representation of normalized node
+    final Node node = container.getNormalizedNode();
 
-      NormalizedNode<?,?> normalizedNode = codec.decode(instanceIdentifierFromString(id),node);
+    NormalizedNode<?, ?> normalizedNode =
+        codec.decode(instanceIdentifierFromString(id), node);
 
-      assertEquals(normalizedNode.getValue().toString(),output.getValue().toString());
-    }
+    assertEquals(normalizedNode.getValue().toString(), output.getValue()
+        .toString());
+  }
 
-    @Test
-    public void testThatANormalizedNodeToProtoBuffNodeEncodeDecode() throws Exception {
-        final NormalizedNode<?, ?> documentOne = TestModel.createTestContainer();
+  @Test
+  public void testThatANormalizedNodeToProtoBuffNodeEncodeDecode()
+      throws Exception {
+    final NormalizedNode<?, ?> documentOne = TestModel.createTestContainer();
 
-        final NormalizedNodeToNodeCodec normalizedNodeToNodeCodec = new NormalizedNodeToNodeCodec(schemaContext);
+    final NormalizedNodeToNodeCodec normalizedNodeToNodeCodec =
+        new NormalizedNodeToNodeCodec(schemaContext);
 
-        Container container = normalizedNodeToNodeCodec.encode(YangInstanceIdentifier.builder().build(), documentOne);
+    Container container =
+        normalizedNodeToNodeCodec.encode(YangInstanceIdentifier.builder()
+            .build(), documentOne);
 
 
-        final NormalizedNode<?, ?> decode = normalizedNodeToNodeCodec.decode(instanceIdentifierFromString("/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test"),container.getNormalizedNode());
-        assertNotNull(decode != null);
+    final NormalizedNode<?, ?> decode =
+        normalizedNodeToNodeCodec
+            .decode(
+                instanceIdentifierFromString("/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test"),
+                container.getNormalizedNode());
+    assertNotNull(decode != null);
 
-        //let us ensure that the return decode normalized node encode returns same container
-        Container containerResult =  normalizedNodeToNodeCodec.encode(YangInstanceIdentifier.builder().build(), decode);
+    // let us ensure that the return decode normalized node encode returns same container
+    Container containerResult =
+        normalizedNodeToNodeCodec.encode(YangInstanceIdentifier.builder()
+            .build(), decode);
 
-        assertEquals(container.getParentPath(),containerResult.getParentPath());
-        assertEquals(container.getNormalizedNode().getChildCount(),container.getNormalizedNode().getChildCount());
+    assertEquals(container.getParentPath(), containerResult.getParentPath());
+    assertEquals(container.getNormalizedNode().getChildCount(), container
+        .getNormalizedNode().getChildCount());
 
-        Assert.assertEquals(containerResult.getNormalizedNode().getChildCount(),container.getNormalizedNode().getChildCount());
+    Assert.assertEquals(containerResult.getNormalizedNode().getChildCount(),
+        container.getNormalizedNode().getChildCount());
 
-        //check first level children are proper
-        List<Node>childrenResult = containerResult.getNormalizedNode().getChildList();
-        List<Node>childrenOriginal = container.getNormalizedNode().getChildList();
+    // check first level children are proper
+    List<Node> childrenResult =
+        containerResult.getNormalizedNode().getChildList();
+    List<Node> childrenOriginal = container.getNormalizedNode().getChildList();
 
-        System.out.println("-------------------------------------------------");
+    System.out.println("-------------------------------------------------");
 
-        System.out.println(childrenOriginal.toString());
+    System.out.println(childrenOriginal.toString());
 
-        System.out.println("-------------------------------------------------");
+    System.out.println("-------------------------------------------------");
 
-        System.out.println(childrenResult.toString());
+    System.out.println(childrenResult.toString());
 
-       boolean bFound;
-        for(Node resultChild: childrenResult){
-           bFound = false;
-          for(Node originalChild:childrenOriginal){
-            if(originalChild.getPath().equals(resultChild.getPath())
-                && resultChild.getType().equals(resultChild.getType())){
-               bFound=true;
-               break;
-            }
-          }
-          Assert.assertTrue(bFound);
+    boolean bFound;
+    for (Node resultChild : childrenResult) {
+      bFound = false;
+      for (Node originalChild : childrenOriginal) {
+        if (originalChild.getPath().equals(resultChild.getPath())
+            && resultChild.getType().equals(resultChild.getType())) {
+          bFound = true;
+          break;
         }
-
+      }
+      Assert.assertTrue(bFound);
     }
 
-    @Test
-    public void addAugmentations(){
-        String stringId = "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test" +
-            "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)augmented-list" +
-            "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)augmented-list[{(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id=1}]";
+  }
 
-        YangInstanceIdentifier identifier = instanceIdentifierFromString(stringId);
+  @Test
+  public void addAugmentations() {
+    String stringId =
+        "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test"
+            + "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)augmented-list"
+            + "/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)augmented-list[{(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id=1}]";
 
-        MapEntryNode uno = TestModel.createAugmentedListEntry(1, "Uno");
+    YangInstanceIdentifier identifier = instanceIdentifierFromString(stringId);
 
-        NormalizedNodeToNodeCodec codec =
-            new NormalizedNodeToNodeCodec(schemaContext);
+    MapEntryNode uno = TestModel.createAugmentedListEntry(1, "Uno");
 
-        Container encode = codec
-            .encode(identifier, uno);
+    NormalizedNodeToNodeCodec codec =
+        new NormalizedNodeToNodeCodec(schemaContext);
 
-        System.out.println(encode.getNormalizedNode());
+    Container encode = codec.encode(identifier, uno);
 
-        codec.decode(identifier, encode.getNormalizedNode());
-    }
+    System.out.println(encode.getNormalizedNode());
+
+    codec.decode(identifier, encode.getNormalizedNode());
+  }
 
 }
index 4b0bde83e0c2b467ddf42fcb53a90e1eb0a682ac..4da7d8c483e175de518cd0a9f8514a689f589db8 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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;
 
 import junit.framework.Assert;
@@ -6,15 +16,16 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 
 public class NodeIdentifierFactoryTest {
 
-    @Test
-    public void validateAugmentationIdentifier(){
-        YangInstanceIdentifier.PathArgument argument = NodeIdentifierFactory
-            .getArgument(
-                "AugmentationIdentifier{childNames=[(urn:opendaylight:flow:table:statistics?revision=2013-12-15)flow-table-statistics]}");
+  @Test
+  public void validateAugmentationIdentifier() {
+    YangInstanceIdentifier.PathArgument argument =
+        NodeIdentifierFactory
+            .getArgument("AugmentationIdentifier{childNames=[(urn:opendaylight:flow:table:statistics?revision=2013-12-15)flow-table-statistics]}");
 
-        Assert.assertTrue(argument instanceof YangInstanceIdentifier.AugmentationIdentifier);
+    Assert
+        .assertTrue(argument instanceof YangInstanceIdentifier.AugmentationIdentifier);
 
 
-    }
+  }
 
 }
index bb246fb1e49fc020052f98bfef633297e7e9169b..136748e3416ffa176f60d03cf489e20df0967ced 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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.util;
 
 import org.junit.Assert;
@@ -13,129 +23,139 @@ import java.util.List;
 
 public class InstanceIdentifierUtilsTest {
 
-    private static QName TEST_QNAME = QName.create("(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test");
-    private static QName NODE_WITH_VALUE_QNAME = QName.create("(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)value");
-    private static QName NODE_WITH_PREDICATES_QNAME = QName.create("(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)pred");
-    private static QName NAME_QNAME = QName.create("(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)name");
+  private static QName TEST_QNAME =
+      QName
+          .create("(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test");
+  private static QName NODE_WITH_VALUE_QNAME =
+      QName
+          .create("(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)value");
+  private static QName NODE_WITH_PREDICATES_QNAME =
+      QName
+          .create("(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)pred");
+  private static QName NAME_QNAME =
+      QName
+          .create("(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)name");
 
-    @Test
-    public void testSerializationOfNodeIdentifier(){
-        YangInstanceIdentifier.PathArgument p1 =
-            new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME);
+  @Test
+  public void testSerializationOfNodeIdentifier() {
+    YangInstanceIdentifier.PathArgument p1 =
+        new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME);
 
-        List<YangInstanceIdentifier.PathArgument> arguments = new ArrayList<>();
+    List<YangInstanceIdentifier.PathArgument> arguments = new ArrayList<>();
 
-        arguments.add(p1);
+    arguments.add(p1);
 
-        YangInstanceIdentifier expected = YangInstanceIdentifier.create(arguments);
+    YangInstanceIdentifier expected = YangInstanceIdentifier.create(arguments);
 
-        NormalizedNodeMessages.InstanceIdentifier instanceIdentifier =
-            InstanceIdentifierUtils.toSerializable(expected);
+    NormalizedNodeMessages.InstanceIdentifier instanceIdentifier =
+        InstanceIdentifierUtils.toSerializable(expected);
 
-        YangInstanceIdentifier actual =
-            InstanceIdentifierUtils.fromSerializable(instanceIdentifier);
+    YangInstanceIdentifier actual =
+        InstanceIdentifierUtils.fromSerializable(instanceIdentifier);
 
 
-        Assert.assertEquals(expected.getLastPathArgument(),
-            actual.getLastPathArgument());
+    Assert.assertEquals(expected.getLastPathArgument(),
+        actual.getLastPathArgument());
 
 
-    }
+  }
 
-    @Test
-    public void testSerializationOfNodeWithValue(){
+  @Test
+  public void testSerializationOfNodeWithValue() {
 
-        withValue((short) 1);
-        withValue((long) 2);
-        withValue(3);
-        withValue(true);
+    withValue((short) 1);
+    withValue((long) 2);
+    withValue(3);
+    withValue(true);
 
-    }
+  }
 
-    private void withValue(Object value){
-        YangInstanceIdentifier.PathArgument p1 =
-            new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME);
+  private void withValue(Object value) {
+    YangInstanceIdentifier.PathArgument p1 =
+        new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME);
 
-        YangInstanceIdentifier.PathArgument p2 =
-            new YangInstanceIdentifier.NodeWithValue(NODE_WITH_VALUE_QNAME, value);
+    YangInstanceIdentifier.PathArgument p2 =
+        new YangInstanceIdentifier.NodeWithValue(NODE_WITH_VALUE_QNAME, value);
 
 
-        List<YangInstanceIdentifier.PathArgument> arguments = new ArrayList<>();
+    List<YangInstanceIdentifier.PathArgument> arguments = new ArrayList<>();
 
-        arguments.add(p1);
-        arguments.add(p2);
+    arguments.add(p1);
+    arguments.add(p2);
 
-        YangInstanceIdentifier expected = YangInstanceIdentifier.create(arguments);
+    YangInstanceIdentifier expected = YangInstanceIdentifier.create(arguments);
 
-        NormalizedNodeMessages.InstanceIdentifier instanceIdentifier =
-            InstanceIdentifierUtils.toSerializable(expected);
+    NormalizedNodeMessages.InstanceIdentifier instanceIdentifier =
+        InstanceIdentifierUtils.toSerializable(expected);
 
-        YangInstanceIdentifier actual =
-            InstanceIdentifierUtils.fromSerializable(instanceIdentifier);
+    YangInstanceIdentifier actual =
+        InstanceIdentifierUtils.fromSerializable(instanceIdentifier);
 
 
-        Assert.assertEquals(expected.getLastPathArgument(),
-            actual.getLastPathArgument());
-    }
+    Assert.assertEquals(expected.getLastPathArgument(),
+        actual.getLastPathArgument());
+  }
 
 
-    @Test
-    public void testSerializationOfNodeIdentifierWithPredicates(){
+  @Test
+  public void testSerializationOfNodeIdentifierWithPredicates() {
 
-        withPredicates((short) 1);
-        withPredicates((long) 2);
-        withPredicates(3);
-        withPredicates(true);
+    withPredicates((short) 1);
+    withPredicates((long) 2);
+    withPredicates(3);
+    withPredicates(true);
 
-    }
+  }
 
-    private void withPredicates(Object value){
-        YangInstanceIdentifier.PathArgument p1 =
-            new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME);
+  private void withPredicates(Object value) {
+    YangInstanceIdentifier.PathArgument p1 =
+        new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME);
 
-        YangInstanceIdentifier.PathArgument p2 =
-            new YangInstanceIdentifier.NodeIdentifierWithPredicates(NODE_WITH_PREDICATES_QNAME, NAME_QNAME, value);
+    YangInstanceIdentifier.PathArgument p2 =
+        new YangInstanceIdentifier.NodeIdentifierWithPredicates(
+            NODE_WITH_PREDICATES_QNAME, NAME_QNAME, value);
 
 
-        List<YangInstanceIdentifier.PathArgument> arguments = new ArrayList<>();
+    List<YangInstanceIdentifier.PathArgument> arguments = new ArrayList<>();
 
-        arguments.add(p1);
-        arguments.add(p2);
+    arguments.add(p1);
+    arguments.add(p2);
 
-        YangInstanceIdentifier expected = YangInstanceIdentifier.create(arguments);
+    YangInstanceIdentifier expected = YangInstanceIdentifier.create(arguments);
 
-        NormalizedNodeMessages.InstanceIdentifier instanceIdentifier =
-            InstanceIdentifierUtils.toSerializable(expected);
+    NormalizedNodeMessages.InstanceIdentifier instanceIdentifier =
+        InstanceIdentifierUtils.toSerializable(expected);
 
-        YangInstanceIdentifier actual =
-            InstanceIdentifierUtils.fromSerializable(instanceIdentifier);
+    YangInstanceIdentifier actual =
+        InstanceIdentifierUtils.fromSerializable(instanceIdentifier);
 
 
-        Assert.assertEquals(expected.getLastPathArgument(),
-            actual.getLastPathArgument());
-    }
+    Assert.assertEquals(expected.getLastPathArgument(),
+        actual.getLastPathArgument());
+  }
 
-    @Test
-    public void testAugmentationIdentifier(){
-        YangInstanceIdentifier.PathArgument p1 =
-            new YangInstanceIdentifier.AugmentationIdentifier(new HashSet(Arrays.asList(TEST_QNAME)));
+  @Test
+  public void testAugmentationIdentifier() {
+    YangInstanceIdentifier.PathArgument p1 =
+        new YangInstanceIdentifier.AugmentationIdentifier(new HashSet(
+            Arrays.asList(TEST_QNAME)));
 
-        List<YangInstanceIdentifier.PathArgument> arguments = new ArrayList<>();
+    List<YangInstanceIdentifier.PathArgument> arguments = new ArrayList<>();
 
-        arguments.add(p1);
+    arguments.add(p1);
 
-        YangInstanceIdentifier expected = YangInstanceIdentifier.create(arguments);
+    YangInstanceIdentifier expected = YangInstanceIdentifier.create(arguments);
 
-        NormalizedNodeMessages.InstanceIdentifier instanceIdentifier =
-            InstanceIdentifierUtils.toSerializable(expected);
+    NormalizedNodeMessages.InstanceIdentifier instanceIdentifier =
+        InstanceIdentifierUtils.toSerializable(expected);
 
-        YangInstanceIdentifier actual =
-            InstanceIdentifierUtils.fromSerializable(instanceIdentifier);
+    YangInstanceIdentifier actual =
+        InstanceIdentifierUtils.fromSerializable(instanceIdentifier);
 
 
-        Assert.assertEquals(expected.getLastPathArgument(),
-            actual.getLastPathArgument());
+    Assert.assertEquals(expected.getLastPathArgument(),
+        actual.getLastPathArgument());
 
-    }
+  }
 
 }
index fb28704952ac2d6b93a613bf9e4f73dcce011034..853b3e264bdc9b4b58eed7e1ca95363eaa64e6be 100644 (file)
@@ -1,9 +1,11 @@
 /*
- * 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
+ *  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.util;
 
@@ -71,8 +73,8 @@ import java.util.Set;
 
 
 /**
- * Two of the testcases in the yangtools/yang-data-impl are leveraged (with  modification) to
- * create the serialization of NormalizedNode using the ProtocolBuffer
+ * Two of the testcases in the yangtools/yang-data-impl are leveraged (with modification) to create
+ * the serialization of NormalizedNode using the ProtocolBuffer
  *
  * @syedbahm
  *
@@ -80,403 +82,402 @@ import java.util.Set;
 
 
 public class NormalizedNodeXmlConverterTest {
-    private static final Logger logger = LoggerFactory
-        .getLogger(NormalizedNodeXmlConverterTest.class);
-    public static final String NAMESPACE =
-        "urn:opendaylight:params:xml:ns:yang:controller:test";
-    private static Date revision;
-    private ContainerNode expectedNode;
-    private ContainerSchemaNode containerNode;
-    private String xmlPath;
-
-    static {
-        try {
-            revision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-03-13");
-        } catch (ParseException e) {
-            throw new RuntimeException(e);
-        }
-    }
-
-    public static DataSchemaNode getSchemaNode(final SchemaContext context,
-        final String moduleName, final String childNodeName) {
-        for (Module module : context.getModules()) {
-            if (module.getName().equals(moduleName)) {
-                DataSchemaNode found =
-                    findChildNode(module.getChildNodes(), childNodeName);
-                Preconditions.checkState(found != null, "Unable to find %s",
-                    childNodeName);
-                return found;
-            }
-        }
-        throw new IllegalStateException("Unable to find child node "
-            + childNodeName);
+  private static final Logger logger = LoggerFactory
+      .getLogger(NormalizedNodeXmlConverterTest.class);
+  public static final String NAMESPACE =
+      "urn:opendaylight:params:xml:ns:yang:controller:test";
+  private static Date revision;
+  private ContainerNode expectedNode;
+  private ContainerSchemaNode containerNode;
+  private String xmlPath;
+
+  static {
+    try {
+      revision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-03-13");
+    } catch (ParseException e) {
+      throw new RuntimeException(e);
     }
-
-    static DataSchemaNode findChildNode(final Collection<DataSchemaNode> children, final String name) {
-        List<DataNodeContainer> containers = Lists.newArrayList();
-
-        for (DataSchemaNode dataSchemaNode : children) {
-            if (dataSchemaNode.getQName().getLocalName().equals(name)) {
-                return dataSchemaNode;
-            }
-            if (dataSchemaNode instanceof DataNodeContainer) {
-                containers.add((DataNodeContainer) dataSchemaNode);
-            } else if (dataSchemaNode instanceof ChoiceNode) {
-                containers.addAll(((ChoiceNode) dataSchemaNode).getCases());
-            }
-        }
-
-        for (DataNodeContainer container : containers) {
-            DataSchemaNode retVal = findChildNode(container.getChildNodes(), name);
-            if (retVal != null) {
-                return retVal;
-            }
-        }
-
-        return null;
+  }
+
+  public static DataSchemaNode getSchemaNode(final SchemaContext context,
+      final String moduleName, final String childNodeName) {
+    for (Module module : context.getModules()) {
+      if (module.getName().equals(moduleName)) {
+        DataSchemaNode found =
+            findChildNode(module.getChildNodes(), childNodeName);
+        Preconditions.checkState(found != null, "Unable to find %s",
+            childNodeName);
+        return found;
+      }
     }
-
-    public static YangInstanceIdentifier.NodeIdentifier getNodeIdentifier(
-        final String localName) {
-        return new YangInstanceIdentifier.NodeIdentifier(QName.create(
-            URI.create(NAMESPACE), revision, localName));
+    throw new IllegalStateException("Unable to find child node "
+        + childNodeName);
+  }
+
+  static DataSchemaNode findChildNode(
+      final Collection<DataSchemaNode> children, final String name) {
+    List<DataNodeContainer> containers = Lists.newArrayList();
+
+    for (DataSchemaNode dataSchemaNode : children) {
+      if (dataSchemaNode.getQName().getLocalName().equals(name)) {
+        return dataSchemaNode;
+      }
+      if (dataSchemaNode instanceof DataNodeContainer) {
+        containers.add((DataNodeContainer) dataSchemaNode);
+      } else if (dataSchemaNode instanceof ChoiceNode) {
+        containers.addAll(((ChoiceNode) dataSchemaNode).getCases());
+      }
     }
 
-    public static YangInstanceIdentifier.AugmentationIdentifier getAugmentIdentifier(
-        final String... childNames) {
-        Set<QName> qn = Sets.newHashSet();
-
-        for (String childName : childNames) {
-            qn.add(getNodeIdentifier(childName).getNodeType());
-        }
-
-        return new YangInstanceIdentifier.AugmentationIdentifier(qn);
+    for (DataNodeContainer container : containers) {
+      DataSchemaNode retVal = findChildNode(container.getChildNodes(), name);
+      if (retVal != null) {
+        return retVal;
+      }
     }
 
+    return null;
+  }
 
-    public static ContainerNode augmentChoiceExpectedNode() {
-
-        DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> b =
-            Builders.containerBuilder();
-        b.withNodeIdentifier(getNodeIdentifier("container"));
-
-        b.withChild(Builders
-            .choiceBuilder()
-            .withNodeIdentifier(getNodeIdentifier("ch2"))
-            .withChild(
-                Builders.leafBuilder()
-                    .withNodeIdentifier(getNodeIdentifier("c2Leaf")).withValue("2")
-                    .build())
-            .withChild(
-                Builders
-                    .choiceBuilder()
-                    .withNodeIdentifier(getNodeIdentifier("c2DeepChoice"))
-                    .withChild(
-                        Builders
-                            .leafBuilder()
-                            .withNodeIdentifier(
-                                getNodeIdentifier("c2DeepChoiceCase1Leaf2"))
-                            .withValue("2").build()).build()).build());
-
-        b.withChild(Builders
-            .choiceBuilder()
-            .withNodeIdentifier(getNodeIdentifier("ch3"))
-            .withChild(
-                Builders.leafBuilder()
-                    .withNodeIdentifier(getNodeIdentifier("c3Leaf")).withValue("3")
-                    .build()).build());
-
-        b.withChild(Builders
-            .augmentationBuilder()
-            .withNodeIdentifier(getAugmentIdentifier("augLeaf"))
-            .withChild(
-                Builders.leafBuilder()
-                    .withNodeIdentifier(getNodeIdentifier("augLeaf"))
-                    .withValue("augment").build()).build());
-
-        b.withChild(Builders
-            .augmentationBuilder()
-            .withNodeIdentifier(getAugmentIdentifier("ch"))
-            .withChild(
-                Builders
-                    .choiceBuilder()
-                    .withNodeIdentifier(getNodeIdentifier("ch"))
-                    .withChild(
-                        Builders.leafBuilder()
-                            .withNodeIdentifier(getNodeIdentifier("c1Leaf"))
-                            .withValue("1").build())
-                    .withChild(
-                        Builders
-                            .augmentationBuilder()
-                            .withNodeIdentifier(
-                                getAugmentIdentifier("c1Leaf_AnotherAugment",
-                                    "deepChoice"))
-                            .withChild(
-                                Builders
-                                    .leafBuilder()
-                                    .withNodeIdentifier(
-                                        getNodeIdentifier("c1Leaf_AnotherAugment"))
-                                    .withValue("1").build())
-                            .withChild(
-                                Builders
-                                    .choiceBuilder()
-                                    .withNodeIdentifier(
-                                        getNodeIdentifier("deepChoice"))
-                                    .withChild(
-                                        Builders
-                                            .leafBuilder()
-                                            .withNodeIdentifier(
-                                                getNodeIdentifier("deepLeafc1"))
-                                            .withValue("1").build()).build())
-                            .build()).build()).build());
-
-        return b.build();
-    }
-
+  public static YangInstanceIdentifier.NodeIdentifier getNodeIdentifier(
+      final String localName) {
+    return new YangInstanceIdentifier.NodeIdentifier(QName.create(
+        URI.create(NAMESPACE), revision, localName));
+  }
 
+  public static YangInstanceIdentifier.AugmentationIdentifier getAugmentIdentifier(
+      final String... childNames) {
+    Set<QName> qn = Sets.newHashSet();
 
-    public void init(final String yangPath, final String xmlPath, final ContainerNode expectedNode)
-        throws Exception {
-        SchemaContext schema = parseTestSchema(yangPath);
-        this.xmlPath = xmlPath;
-        this.containerNode =
-            (ContainerSchemaNode) getSchemaNode(schema, "test", "container");
-        this.expectedNode = expectedNode;
+    for (String childName : childNames) {
+      qn.add(getNodeIdentifier(childName).getNodeType());
     }
 
-    SchemaContext parseTestSchema(final String yangPath) throws Exception {
-
-        YangParserImpl yangParserImpl = new YangParserImpl();
-        InputStream stream =
-            NormalizedNodeXmlConverterTest.class.getResourceAsStream(yangPath);
-        ArrayList<InputStream> al = new ArrayList<InputStream>();
-        al.add(stream);
-        Set<Module> modules = yangParserImpl.parseYangModelsFromStreams(al);
-        return yangParserImpl.resolveSchemaContext(modules);
-
+    return new YangInstanceIdentifier.AugmentationIdentifier(qn);
+  }
+
+
+  public static ContainerNode augmentChoiceExpectedNode() {
+
+    DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> b =
+        Builders.containerBuilder();
+    b.withNodeIdentifier(getNodeIdentifier("container"));
+
+    b.withChild(Builders
+        .choiceBuilder()
+        .withNodeIdentifier(getNodeIdentifier("ch2"))
+        .withChild(
+            Builders.leafBuilder()
+                .withNodeIdentifier(getNodeIdentifier("c2Leaf")).withValue("2")
+                .build())
+        .withChild(
+            Builders
+                .choiceBuilder()
+                .withNodeIdentifier(getNodeIdentifier("c2DeepChoice"))
+                .withChild(
+                    Builders
+                        .leafBuilder()
+                        .withNodeIdentifier(
+                            getNodeIdentifier("c2DeepChoiceCase1Leaf2"))
+                        .withValue("2").build()).build()).build());
+
+    b.withChild(Builders
+        .choiceBuilder()
+        .withNodeIdentifier(getNodeIdentifier("ch3"))
+        .withChild(
+            Builders.leafBuilder()
+                .withNodeIdentifier(getNodeIdentifier("c3Leaf")).withValue("3")
+                .build()).build());
+
+    b.withChild(Builders
+        .augmentationBuilder()
+        .withNodeIdentifier(getAugmentIdentifier("augLeaf"))
+        .withChild(
+            Builders.leafBuilder()
+                .withNodeIdentifier(getNodeIdentifier("augLeaf"))
+                .withValue("augment").build()).build());
+
+    b.withChild(Builders
+        .augmentationBuilder()
+        .withNodeIdentifier(getAugmentIdentifier("ch"))
+        .withChild(
+            Builders
+                .choiceBuilder()
+                .withNodeIdentifier(getNodeIdentifier("ch"))
+                .withChild(
+                    Builders.leafBuilder()
+                        .withNodeIdentifier(getNodeIdentifier("c1Leaf"))
+                        .withValue("1").build())
+                .withChild(
+                    Builders
+                        .augmentationBuilder()
+                        .withNodeIdentifier(
+                            getAugmentIdentifier("c1Leaf_AnotherAugment",
+                                "deepChoice"))
+                        .withChild(
+                            Builders
+                                .leafBuilder()
+                                .withNodeIdentifier(
+                                    getNodeIdentifier("c1Leaf_AnotherAugment"))
+                                .withValue("1").build())
+                        .withChild(
+                            Builders
+                                .choiceBuilder()
+                                .withNodeIdentifier(
+                                    getNodeIdentifier("deepChoice"))
+                                .withChild(
+                                    Builders
+                                        .leafBuilder()
+                                        .withNodeIdentifier(
+                                            getNodeIdentifier("deepLeafc1"))
+                                        .withValue("1").build()).build())
+                        .build()).build()).build());
+
+    return b.build();
+  }
+
+
+
+  public void init(final String yangPath, final String xmlPath,
+      final ContainerNode expectedNode) throws Exception {
+    SchemaContext schema = parseTestSchema(yangPath);
+    this.xmlPath = xmlPath;
+    this.containerNode =
+        (ContainerSchemaNode) getSchemaNode(schema, "test", "container");
+    this.expectedNode = expectedNode;
+  }
+
+  SchemaContext parseTestSchema(final String yangPath) throws Exception {
+
+    YangParserImpl yangParserImpl = new YangParserImpl();
+    InputStream stream =
+        NormalizedNodeXmlConverterTest.class.getResourceAsStream(yangPath);
+    ArrayList<InputStream> al = new ArrayList<InputStream>();
+    al.add(stream);
+    Set<Module> modules = yangParserImpl.parseYangModelsFromStreams(al);
+    return yangParserImpl.resolveSchemaContext(modules);
+
+  }
+
+
+  @Test
+  public void testConversionWithAugmentChoice() throws Exception {
+    init("/augment_choice.yang", "/augment_choice.xml",
+        augmentChoiceExpectedNode());
+    Document doc = loadDocument(xmlPath);
+
+    ContainerNode built =
+        DomToNormalizedNodeParserFactory
+            .getInstance(DomUtils.defaultValueCodecProvider())
+            .getContainerNodeParser()
+            .parse(Collections.singletonList(doc.getDocumentElement()),
+                containerNode);
+
+    if (expectedNode != null) {
+      junit.framework.Assert.assertEquals(expectedNode, built);
     }
 
+    logger.info("{}", built);
 
-    @Test
-    public void testConversionWithAugmentChoice() throws Exception {
-        init("/augment_choice.yang", "/augment_choice.xml",
-            augmentChoiceExpectedNode());
-        Document doc = loadDocument(xmlPath);
+    Iterable<Element> els =
+        DomFromNormalizedNodeSerializerFactory
+            .getInstance(XmlDocumentUtils.getDocument(),
+                DomUtils.defaultValueCodecProvider())
+            .getContainerNodeSerializer().serialize(containerNode, built);
 
-        ContainerNode built =
-            DomToNormalizedNodeParserFactory
-                .getInstance(DomUtils.defaultValueCodecProvider())
-                .getContainerNodeParser()
-                .parse(Collections.singletonList(doc.getDocumentElement()),
-                    containerNode);
+    Element el = els.iterator().next();
 
-        if (expectedNode != null) {
-            junit.framework.Assert.assertEquals(expectedNode, built);
-        }
+    XMLUnit.setIgnoreWhitespace(true);
+    XMLUnit.setIgnoreComments(true);
 
-        logger.info("{}", built);
+    System.out.println(toString(doc.getDocumentElement()));
+    System.out.println(toString(el));
 
-        Iterable<Element> els =
-            DomFromNormalizedNodeSerializerFactory
-                .getInstance(XmlDocumentUtils.getDocument(),
-                    DomUtils.defaultValueCodecProvider())
-                .getContainerNodeSerializer().serialize(containerNode, built);
+    new Diff(XMLUnit.buildControlDocument(toString(doc.getDocumentElement())),
+        XMLUnit.buildTestDocument(toString(el))).similar();
+  }
 
-        Element el = els.iterator().next();
+  private static ContainerNode listLeafListWithAttributes() {
+    DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> b =
+        Builders.containerBuilder();
+    b.withNodeIdentifier(getNodeIdentifier("container"));
 
-        XMLUnit.setIgnoreWhitespace(true);
-        XMLUnit.setIgnoreComments(true);
+    CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder =
+        Builders.mapBuilder().withNodeIdentifier(getNodeIdentifier("list"));
 
-        System.out.println(toString(doc.getDocumentElement()));
-        System.out.println(toString(el));
+    Map<QName, Object> predicates = Maps.newHashMap();
+    predicates.put(getNodeIdentifier("uint32InList").getNodeType(), 3L);
 
-        new Diff(
-            XMLUnit.buildControlDocument(toString(doc.getDocumentElement())),
-            XMLUnit.buildTestDocument(toString(el))).similar();
-    }
+    DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> list1Builder =
+        Builders.mapEntryBuilder().withNodeIdentifier(
+            new YangInstanceIdentifier.NodeIdentifierWithPredicates(
+                getNodeIdentifier("list").getNodeType(), predicates));
+    NormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier, Object, LeafNode<Object>> uint32InListBuilder =
+        Builders.leafBuilder().withNodeIdentifier(
+            getNodeIdentifier("uint32InList"));
 
-    private static ContainerNode listLeafListWithAttributes() {
-        DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> b =
-            Builders.containerBuilder();
-        b.withNodeIdentifier(getNodeIdentifier("container"));
+    list1Builder.withChild(uint32InListBuilder.withValue(3L).build());
 
-        CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder =
-            Builders.mapBuilder().withNodeIdentifier(getNodeIdentifier("list"));
+    listBuilder.withChild(list1Builder.build());
+    b.withChild(listBuilder.build());
 
-        Map<QName, Object> predicates = Maps.newHashMap();
-        predicates.put(getNodeIdentifier("uint32InList").getNodeType(), 3L);
+    NormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier, Object, LeafNode<Object>> booleanBuilder =
+        Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("boolean"));
+    booleanBuilder.withValue(false);
+    b.withChild(booleanBuilder.build());
 
-        DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> list1Builder =
-            Builders.mapEntryBuilder().withNodeIdentifier(
-                new YangInstanceIdentifier.NodeIdentifierWithPredicates(
-                    getNodeIdentifier("list").getNodeType(), predicates));
-        NormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier, Object, LeafNode<Object>> uint32InListBuilder =
-            Builders.leafBuilder().withNodeIdentifier(
-                getNodeIdentifier("uint32InList"));
+    ListNodeBuilder<Object, LeafSetEntryNode<Object>> leafListBuilder =
+        Builders.leafSetBuilder().withNodeIdentifier(
+            getNodeIdentifier("leafList"));
 
-        list1Builder.withChild(uint32InListBuilder.withValue(3L).build());
+    NormalizedNodeBuilder<YangInstanceIdentifier.NodeWithValue, Object, LeafSetEntryNode<Object>> leafList1Builder =
+        Builders.leafSetEntryBuilder().withNodeIdentifier(
+            new YangInstanceIdentifier.NodeWithValue(getNodeIdentifier(
+                "leafList").getNodeType(), "a"));
 
-        listBuilder.withChild(list1Builder.build());
-        b.withChild(listBuilder.build());
+    leafList1Builder.withValue("a");
 
-        NormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier, Object, LeafNode<Object>> booleanBuilder =
-            Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("boolean"));
-        booleanBuilder.withValue(false);
-        b.withChild(booleanBuilder.build());
+    leafListBuilder.withChild(leafList1Builder.build());
+    b.withChild(leafListBuilder.build());
 
-        ListNodeBuilder<Object, LeafSetEntryNode<Object>> leafListBuilder =
-            Builders.leafSetBuilder().withNodeIdentifier(
-                getNodeIdentifier("leafList"));
+    return b.build();
+  }
 
-        NormalizedNodeBuilder<YangInstanceIdentifier.NodeWithValue, Object, LeafSetEntryNode<Object>> leafList1Builder =
-            Builders.leafSetEntryBuilder().withNodeIdentifier(
-                new YangInstanceIdentifier.NodeWithValue(getNodeIdentifier("leafList")
-                    .getNodeType(), "a"));
 
-        leafList1Builder.withValue("a");
+  @Test
+  public void testConversionWithAttributes() throws Exception {
+    init("/test.yang", "/simple_xml_with_attributes.xml",
+        listLeafListWithAttributes());
+    Document doc = loadDocument(xmlPath);
 
-        leafListBuilder.withChild(leafList1Builder.build());
-        b.withChild(leafListBuilder.build());
+    ContainerNode built =
+        DomToNormalizedNodeParserFactory
+            .getInstance(DomUtils.defaultValueCodecProvider())
+            .getContainerNodeParser()
+            .parse(Collections.singletonList(doc.getDocumentElement()),
+                containerNode);
 
-        return b.build();
+    if (expectedNode != null) {
+      junit.framework.Assert.assertEquals(expectedNode, built);
     }
 
+    logger.info("{}", built);
 
-    @Test
-    public void testConversionWithAttributes() throws Exception {
-        init("/test.yang", "/simple_xml_with_attributes.xml",
-            listLeafListWithAttributes());
-        Document doc = loadDocument(xmlPath);
+    Iterable<Element> els =
+        DomFromNormalizedNodeSerializerFactory
+            .getInstance(XmlDocumentUtils.getDocument(),
+                DomUtils.defaultValueCodecProvider())
+            .getContainerNodeSerializer().serialize(containerNode, built);
 
-        ContainerNode built =
-            DomToNormalizedNodeParserFactory
-                .getInstance(DomUtils.defaultValueCodecProvider())
-                .getContainerNodeParser()
-                .parse(Collections.singletonList(doc.getDocumentElement()),
-                    containerNode);
+    Element el = els.iterator().next();
 
-        if (expectedNode != null) {
-            junit.framework.Assert.assertEquals(expectedNode, built);
-        }
+    XMLUnit.setIgnoreWhitespace(true);
+    XMLUnit.setIgnoreComments(true);
 
-        logger.info("{}", built);
+    System.out.println(toString(doc.getDocumentElement()));
+    System.out.println(toString(el));
 
-        Iterable<Element> els =
-            DomFromNormalizedNodeSerializerFactory
-                .getInstance(XmlDocumentUtils.getDocument(),
-                    DomUtils.defaultValueCodecProvider())
-                .getContainerNodeSerializer().serialize(containerNode, built);
+    new Diff(XMLUnit.buildControlDocument(toString(doc.getDocumentElement())),
+        XMLUnit.buildTestDocument(toString(el))).similar();
+  }
 
-        Element el = els.iterator().next();
 
-        XMLUnit.setIgnoreWhitespace(true);
-        XMLUnit.setIgnoreComments(true);
+  private Document loadDocument(final String xmlPath) throws Exception {
+    InputStream resourceAsStream =
+        NormalizedNodeXmlConverterTest.class.getResourceAsStream(xmlPath);
 
-        System.out.println(toString(doc.getDocumentElement()));
-        System.out.println(toString(el));
+    Document currentConfigElement = readXmlToDocument(resourceAsStream);
+    Preconditions.checkNotNull(currentConfigElement);
+    return currentConfigElement;
+  }
 
-        new Diff(
-            XMLUnit.buildControlDocument(toString(doc.getDocumentElement())),
-            XMLUnit.buildTestDocument(toString(el))).similar();
-    }
+  private static final DocumentBuilderFactory BUILDERFACTORY;
 
+  static {
+    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+    factory.setNamespaceAware(true);
+    factory.setCoalescing(true);
+    factory.setIgnoringElementContentWhitespace(true);
+    factory.setIgnoringComments(true);
+    BUILDERFACTORY = factory;
+  }
 
-    private Document loadDocument(final String xmlPath) throws Exception {
-        InputStream resourceAsStream =
-            NormalizedNodeXmlConverterTest.class.getResourceAsStream(xmlPath);
-
-        Document currentConfigElement = readXmlToDocument(resourceAsStream);
-        Preconditions.checkNotNull(currentConfigElement);
-        return currentConfigElement;
-    }
-
-    private static final DocumentBuilderFactory BUILDERFACTORY;
-
-    static {
-        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
-        factory.setNamespaceAware(true);
-        factory.setCoalescing(true);
-        factory.setIgnoringElementContentWhitespace(true);
-        factory.setIgnoringComments(true);
-        BUILDERFACTORY = factory;
+  private Document readXmlToDocument(final InputStream xmlContent)
+      throws IOException, SAXException {
+    DocumentBuilder dBuilder;
+    try {
+      dBuilder = BUILDERFACTORY.newDocumentBuilder();
+    } catch (ParserConfigurationException e) {
+      throw new RuntimeException("Failed to parse XML document", e);
     }
-
-    private Document readXmlToDocument(final InputStream xmlContent)
-        throws IOException, SAXException {
-        DocumentBuilder dBuilder;
-        try {
-            dBuilder = BUILDERFACTORY.newDocumentBuilder();
-        } catch (ParserConfigurationException e) {
-            throw new RuntimeException("Failed to parse XML document", e);
-        }
-        Document doc = dBuilder.parse(xmlContent);
-
-        doc.getDocumentElement().normalize();
-        return doc;
-    }
-
-    public static String toString(final Element xml) {
-        try {
-            Transformer transformer =
-                TransformerFactory.newInstance().newTransformer();
-            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
-
-            StreamResult result = new StreamResult(new StringWriter());
-            DOMSource source = new DOMSource(xml);
-            transformer.transform(source, result);
-
-            return result.getWriter().toString();
-        } catch (IllegalArgumentException | TransformerFactoryConfigurationError
-            | TransformerException e) {
-            throw new RuntimeException("Unable to serialize xml element " + xml, e);
-        }
+    Document doc = dBuilder.parse(xmlContent);
+
+    doc.getDocumentElement().normalize();
+    return doc;
+  }
+
+  public static String toString(final Element xml) {
+    try {
+      Transformer transformer =
+          TransformerFactory.newInstance().newTransformer();
+      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+
+      StreamResult result = new StreamResult(new StringWriter());
+      DOMSource source = new DOMSource(xml);
+      transformer.transform(source, result);
+
+      return result.getWriter().toString();
+    } catch (IllegalArgumentException | TransformerFactoryConfigurationError
+        | TransformerException e) {
+      throw new RuntimeException("Unable to serialize xml element " + xml, e);
     }
+  }
 
-    @Test
-    public void testConversionToNormalizedXml() throws Exception {
-        SimpleNormalizedNodeMessage.NormalizedNodeXml nnXml =
-            EncoderDecoderUtil.encode(parseTestSchema("/augment_choice.yang"),
-                augmentChoiceExpectedNode());
-        Document expectedDoc = loadDocument("/augment_choice.xml");
-        Document convertedDoc =
-            EncoderDecoderUtil.factory.newDocumentBuilder().parse(
-                new ByteArrayInputStream(nnXml.getXmlString().getBytes("utf-8")));
-        System.out.println(toString(convertedDoc.getDocumentElement()));
-        XMLUnit.setIgnoreWhitespace(true);
-        XMLUnit.setIgnoreComments(true);
-        new Diff(XMLUnit.buildControlDocument(toString(expectedDoc
-            .getDocumentElement())),
-            XMLUnit.buildTestDocument(toString(convertedDoc
-                .getDocumentElement()))).similar();
-        System.out.println(toString(expectedDoc.getDocumentElement()));
-
-    }
-
-
-    @Test
-    public void testConversionFromXmlToNormalizedNode() throws Exception {
-        SimpleNormalizedNodeMessage.NormalizedNodeXml nnXml =
-            EncoderDecoderUtil.encode(parseTestSchema("/test.yang"),
-                listLeafListWithAttributes());
-        Document expectedDoc = loadDocument("/simple_xml_with_attributes.xml");
-        Document convertedDoc =
-            EncoderDecoderUtil.factory.newDocumentBuilder().parse(
-                new ByteArrayInputStream(nnXml.getXmlString().getBytes("utf-8")));
-        System.out.println(toString(convertedDoc.getDocumentElement()));
-        XMLUnit.setIgnoreWhitespace(true);
-        XMLUnit.setIgnoreComments(true);
-        new Diff(XMLUnit.buildControlDocument(toString(expectedDoc
-            .getDocumentElement())),
-            XMLUnit.buildTestDocument(toString(convertedDoc
-                .getDocumentElement()))).similar();
-        System.out.println(toString(expectedDoc.getDocumentElement()));
-
-        // now we will try to convert xml back to normalize node.
-        ContainerNode cn =
-            (ContainerNode) EncoderDecoderUtil.decode(
-                parseTestSchema("/test.yang"), nnXml);
-        junit.framework.Assert.assertEquals(listLeafListWithAttributes(), cn);
-
-    }
+  @Test
+  public void testConversionToNormalizedXml() throws Exception {
+    SimpleNormalizedNodeMessage.NormalizedNodeXml nnXml =
+        EncoderDecoderUtil.encode(parseTestSchema("/augment_choice.yang"),
+            augmentChoiceExpectedNode());
+    Document expectedDoc = loadDocument("/augment_choice.xml");
+    Document convertedDoc =
+        EncoderDecoderUtil.factory.newDocumentBuilder().parse(
+            new ByteArrayInputStream(nnXml.getXmlString().getBytes("utf-8")));
+    System.out.println(toString(convertedDoc.getDocumentElement()));
+    XMLUnit.setIgnoreWhitespace(true);
+    XMLUnit.setIgnoreComments(true);
+    new Diff(XMLUnit.buildControlDocument(toString(expectedDoc
+        .getDocumentElement())),
+        XMLUnit.buildTestDocument(toString(convertedDoc.getDocumentElement())))
+        .similar();
+    System.out.println(toString(expectedDoc.getDocumentElement()));
+
+  }
+
+
+  @Test
+  public void testConversionFromXmlToNormalizedNode() throws Exception {
+    SimpleNormalizedNodeMessage.NormalizedNodeXml nnXml =
+        EncoderDecoderUtil.encode(parseTestSchema("/test.yang"),
+            listLeafListWithAttributes());
+    Document expectedDoc = loadDocument("/simple_xml_with_attributes.xml");
+    Document convertedDoc =
+        EncoderDecoderUtil.factory.newDocumentBuilder().parse(
+            new ByteArrayInputStream(nnXml.getXmlString().getBytes("utf-8")));
+    System.out.println(toString(convertedDoc.getDocumentElement()));
+    XMLUnit.setIgnoreWhitespace(true);
+    XMLUnit.setIgnoreComments(true);
+    new Diff(XMLUnit.buildControlDocument(toString(expectedDoc
+        .getDocumentElement())),
+        XMLUnit.buildTestDocument(toString(convertedDoc.getDocumentElement())))
+        .similar();
+    System.out.println(toString(expectedDoc.getDocumentElement()));
+
+    // now we will try to convert xml back to normalize node.
+    ContainerNode cn =
+        (ContainerNode) EncoderDecoderUtil.decode(
+            parseTestSchema("/test.yang"), nnXml);
+    junit.framework.Assert.assertEquals(listLeafListWithAttributes(), cn);
+
+  }
 
 }
index bef4057aa2596b891000698a943864983bb91d51..3eeb06f93ca6cead53174dac1cd4f436b15fd46f 100644 (file)
@@ -1,3 +1,13 @@
+/*
+ *
+ *  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.util;
 
 import org.opendaylight.yangtools.yang.common.QName;
@@ -34,453 +44,427 @@ import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.ma
 
 public class TestModel {
 
-    public static final QName TEST_QNAME = QName.create(
-        "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test",
-        "2014-03-13", "test");
-
-    public static final QName AUG_NAME_QNAME = QName.create(
-        "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:aug",
-        "2014-03-13", "name");
-
-    public static final QName AUG_CONT_QNAME = QName.create(
-        "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:aug",
-        "2014-03-13", "cont");
-
-
-    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_REF_QNAME =
-        QName.create(TEST_QNAME, "some-ref");
-    public static final QName MYIDENTITY_QNAME =
-        QName.create(TEST_QNAME, "myidentity");
-    public static final QName SWITCH_FEATURES_QNAME =
-        QName.create(TEST_QNAME, "switch-features");
-
-    public static final QName AUGMENTED_LIST_QNAME =
-        QName.create(TEST_QNAME, "augmented-list");
-
-    public static final QName OUTER_LIST_QNAME = QName.create(TEST_QNAME,
-        "outer-list");
-    public static final QName INNER_LIST_QNAME = QName.create(TEST_QNAME,
-        "inner-list");
-    public static final QName OUTER_CHOICE_QNAME = QName.create(TEST_QNAME,
-        "outer-choice");
-    public static final QName ID_QNAME = QName.create(TEST_QNAME, "id");
-    public static final QName NAME_QNAME = QName.create(TEST_QNAME, "name");
-    public static final QName VALUE_QNAME = QName.create(TEST_QNAME, "value");
-    private static final String DATASTORE_TEST_YANG =
-        "/odl-datastore-test.yang";
-    private static final String DATASTORE_AUG_YANG =
-        "/odl-datastore-augmentation.yang";
-    private static final String DATASTORE_TEST_NOTIFICATION_YANG =
-        "/odl-datastore-test-notification.yang";
-
-
-    public static final YangInstanceIdentifier TEST_PATH = YangInstanceIdentifier
-        .of(TEST_QNAME);
-    public static final YangInstanceIdentifier DESC_PATH = YangInstanceIdentifier
-        .builder(TEST_PATH).node(DESC_QNAME).build();
-    public static final YangInstanceIdentifier OUTER_LIST_PATH = YangInstanceIdentifier
-        .builder(TEST_PATH).node(OUTER_LIST_QNAME).build();
-    public static final QName TWO_QNAME = QName.create(TEST_QNAME, "two");
-    public static final QName THREE_QNAME = QName.create(TEST_QNAME, "three");
-
-    private static final Integer ONE_ID = 1;
-    private static final Integer TWO_ID = 2;
-    private static final String TWO_ONE_NAME = "one";
-    private static final String TWO_TWO_NAME = "two";
-    private static final String DESC = "Hello there";
-
-    // Family specific constants
-    public static final QName FAMILY_QNAME =
-        QName
-            .create(
-                "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:notification-test",
-                "2014-04-17", "family");
-    public static final QName CHILDREN_QNAME = QName.create(FAMILY_QNAME,
-        "children");
-    public static final QName GRAND_CHILDREN_QNAME = QName.create(FAMILY_QNAME,
-        "grand-children");
-    public static final QName CHILD_NUMBER_QNAME = QName.create(FAMILY_QNAME,
-        "child-number");
-    public static final QName CHILD_NAME_QNAME = QName.create(FAMILY_QNAME,
-        "child-name");
-    public static final QName GRAND_CHILD_NUMBER_QNAME = QName.create(
-        FAMILY_QNAME, "grand-child-number");
-    public static final QName GRAND_CHILD_NAME_QNAME =
-        QName.create(FAMILY_QNAME,
-            "grand-child-name");
-
-    public static final YangInstanceIdentifier FAMILY_PATH = YangInstanceIdentifier
-        .of(FAMILY_QNAME);
-    public static final YangInstanceIdentifier FAMILY_DESC_PATH = YangInstanceIdentifier
-        .builder(FAMILY_PATH).node(DESC_QNAME).build();
-    public static final YangInstanceIdentifier CHILDREN_PATH = YangInstanceIdentifier
-        .builder(FAMILY_PATH).node(CHILDREN_QNAME).build();
-
-    private static final Integer FIRST_CHILD_ID = 1;
-    private static final Integer SECOND_CHILD_ID = 2;
-
-    private static final String FIRST_CHILD_NAME = "first child";
-    private static final String SECOND_CHILD_NAME = "second child";
-
-    private static final Integer FIRST_GRAND_CHILD_ID = 1;
-    private static final Integer SECOND_GRAND_CHILD_ID = 2;
-
-    private static final String FIRST_GRAND_CHILD_NAME = "first grand child";
-    private static final String SECOND_GRAND_CHILD_NAME = "second grand child";
-
-    // first child
-    private static final YangInstanceIdentifier CHILDREN_1_PATH = YangInstanceIdentifier
-        .builder(CHILDREN_PATH)
-        .nodeWithKey(CHILDREN_QNAME, CHILD_NUMBER_QNAME, FIRST_CHILD_ID) //
-        .build();
-    private static final YangInstanceIdentifier CHILDREN_1_NAME_PATH =
-        YangInstanceIdentifier.builder(CHILDREN_PATH)
-            .nodeWithKey(CHILDREN_QNAME, CHILD_NAME_QNAME, FIRST_CHILD_NAME) //
-            .build();
+  public static final QName TEST_QNAME = QName.create(
+      "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test",
+      "2014-03-13", "test");
+
+  public static final QName AUG_NAME_QNAME = QName.create(
+      "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:aug",
+      "2014-03-13", "name");
+
+  public static final QName AUG_CONT_QNAME = QName.create(
+      "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:aug",
+      "2014-03-13", "cont");
+
+
+  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_REF_QNAME = QName.create(TEST_QNAME,
+      "some-ref");
+  public static final QName MYIDENTITY_QNAME = QName.create(TEST_QNAME,
+      "myidentity");
+  public static final QName SWITCH_FEATURES_QNAME = QName.create(TEST_QNAME,
+      "switch-features");
+
+  public static final QName AUGMENTED_LIST_QNAME = QName.create(TEST_QNAME,
+      "augmented-list");
+
+  public static final QName OUTER_LIST_QNAME = QName.create(TEST_QNAME,
+      "outer-list");
+  public static final QName INNER_LIST_QNAME = QName.create(TEST_QNAME,
+      "inner-list");
+  public static final QName OUTER_CHOICE_QNAME = QName.create(TEST_QNAME,
+      "outer-choice");
+  public static final QName ID_QNAME = QName.create(TEST_QNAME, "id");
+  public static final QName NAME_QNAME = QName.create(TEST_QNAME, "name");
+  public static final QName VALUE_QNAME = QName.create(TEST_QNAME, "value");
+  private static final String DATASTORE_TEST_YANG = "/odl-datastore-test.yang";
+  private static final String DATASTORE_AUG_YANG =
+      "/odl-datastore-augmentation.yang";
+  private static final String DATASTORE_TEST_NOTIFICATION_YANG =
+      "/odl-datastore-test-notification.yang";
+
+
+  public static final YangInstanceIdentifier TEST_PATH = YangInstanceIdentifier
+      .of(TEST_QNAME);
+  public static final YangInstanceIdentifier DESC_PATH = YangInstanceIdentifier
+      .builder(TEST_PATH).node(DESC_QNAME).build();
+  public static final YangInstanceIdentifier OUTER_LIST_PATH =
+      YangInstanceIdentifier.builder(TEST_PATH).node(OUTER_LIST_QNAME).build();
+  public static final QName TWO_QNAME = QName.create(TEST_QNAME, "two");
+  public static final QName THREE_QNAME = QName.create(TEST_QNAME, "three");
+
+  private static final Integer ONE_ID = 1;
+  private static final Integer TWO_ID = 2;
+  private static final String TWO_ONE_NAME = "one";
+  private static final String TWO_TWO_NAME = "two";
+  private static final String DESC = "Hello there";
+
+  // Family specific constants
+  public static final QName FAMILY_QNAME =
+      QName
+          .create(
+              "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:notification-test",
+              "2014-04-17", "family");
+  public static final QName CHILDREN_QNAME = QName.create(FAMILY_QNAME,
+      "children");
+  public static final QName GRAND_CHILDREN_QNAME = QName.create(FAMILY_QNAME,
+      "grand-children");
+  public static final QName CHILD_NUMBER_QNAME = QName.create(FAMILY_QNAME,
+      "child-number");
+  public static final QName CHILD_NAME_QNAME = QName.create(FAMILY_QNAME,
+      "child-name");
+  public static final QName GRAND_CHILD_NUMBER_QNAME = QName.create(
+      FAMILY_QNAME, "grand-child-number");
+  public static final QName GRAND_CHILD_NAME_QNAME = QName.create(FAMILY_QNAME,
+      "grand-child-name");
+
+  public static final YangInstanceIdentifier FAMILY_PATH =
+      YangInstanceIdentifier.of(FAMILY_QNAME);
+  public static final YangInstanceIdentifier FAMILY_DESC_PATH =
+      YangInstanceIdentifier.builder(FAMILY_PATH).node(DESC_QNAME).build();
+  public static final YangInstanceIdentifier CHILDREN_PATH =
+      YangInstanceIdentifier.builder(FAMILY_PATH).node(CHILDREN_QNAME).build();
+
+  private static final Integer FIRST_CHILD_ID = 1;
+  private static final Integer SECOND_CHILD_ID = 2;
+
+  private static final String FIRST_CHILD_NAME = "first child";
+  private static final String SECOND_CHILD_NAME = "second child";
+
+  private static final Integer FIRST_GRAND_CHILD_ID = 1;
+  private static final Integer SECOND_GRAND_CHILD_ID = 2;
+
+  private static final String FIRST_GRAND_CHILD_NAME = "first grand child";
+  private static final String SECOND_GRAND_CHILD_NAME = "second grand child";
+
+  // first child
+  private static final YangInstanceIdentifier CHILDREN_1_PATH =
+      YangInstanceIdentifier.builder(CHILDREN_PATH)
+          .nodeWithKey(CHILDREN_QNAME, CHILD_NUMBER_QNAME, FIRST_CHILD_ID) //
+          .build();
+  private static final YangInstanceIdentifier CHILDREN_1_NAME_PATH =
+      YangInstanceIdentifier.builder(CHILDREN_PATH)
+          .nodeWithKey(CHILDREN_QNAME, CHILD_NAME_QNAME, FIRST_CHILD_NAME) //
+          .build();
+
+  private static final YangInstanceIdentifier CHILDREN_2_PATH =
+      YangInstanceIdentifier.builder(CHILDREN_PATH)
+          .nodeWithKey(CHILDREN_QNAME, CHILD_NUMBER_QNAME, SECOND_CHILD_ID) //
+          .build();
+  private static final YangInstanceIdentifier CHILDREN_2_NAME_PATH =
+      YangInstanceIdentifier.builder(CHILDREN_PATH)
+          .nodeWithKey(CHILDREN_QNAME, CHILD_NAME_QNAME, SECOND_CHILD_NAME) //
+          .build();
+
+
+  private static final YangInstanceIdentifier GRAND_CHILD_1_PATH =
+      YangInstanceIdentifier
+          .builder(CHILDREN_1_PATH)
+          .node(GRAND_CHILDREN_QNAME)
+          //
+          .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME,
+              FIRST_GRAND_CHILD_ID) //
+          .build();
+
+  private static final YangInstanceIdentifier GRAND_CHILD_1_NAME_PATH =
+      YangInstanceIdentifier
+          .builder(CHILDREN_1_PATH)
+          .node(GRAND_CHILDREN_QNAME)
+          //
+          .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NAME_QNAME,
+              FIRST_GRAND_CHILD_NAME) //
+          .build();
+
+  private static final YangInstanceIdentifier GRAND_CHILD_2_PATH =
+      YangInstanceIdentifier
+          .builder(CHILDREN_2_PATH)
+          .node(GRAND_CHILDREN_QNAME)
+          //
+          .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME,
+              SECOND_GRAND_CHILD_ID) //
+          .build();
+
+  private static final YangInstanceIdentifier GRAND_CHILD_2_NAME_PATH =
+      YangInstanceIdentifier
+          .builder(CHILDREN_2_PATH)
+          .node(GRAND_CHILDREN_QNAME)
+          //
+          .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NAME_QNAME,
+              SECOND_GRAND_CHILD_NAME) //
+          .build();
+
+  private static final YangInstanceIdentifier DESC_PATH_ID =
+      YangInstanceIdentifier.builder(DESC_PATH).build();
+  private static final YangInstanceIdentifier OUTER_LIST_1_PATH =
+      YangInstanceIdentifier.builder(OUTER_LIST_PATH)
+          .nodeWithKey(OUTER_LIST_QNAME, ID_QNAME, ONE_ID) //
+          .build();
+
+  private static final YangInstanceIdentifier OUTER_LIST_2_PATH =
+      YangInstanceIdentifier.builder(OUTER_LIST_PATH)
+          .nodeWithKey(OUTER_LIST_QNAME, ID_QNAME, TWO_ID) //
+          .build();
+
+  private static final YangInstanceIdentifier TWO_TWO_PATH =
+      YangInstanceIdentifier.builder(OUTER_LIST_2_PATH).node(INNER_LIST_QNAME) //
+          .nodeWithKey(INNER_LIST_QNAME, NAME_QNAME, TWO_TWO_NAME) //
+          .build();
+
+  private static final YangInstanceIdentifier TWO_TWO_VALUE_PATH =
+      YangInstanceIdentifier.builder(TWO_TWO_PATH).node(VALUE_QNAME) //
+          .build();
+
+  private static final MapEntryNode BAR_NODE = mapEntryBuilder(
+      OUTER_LIST_QNAME, ID_QNAME, TWO_ID) //
+      .withChild(mapNodeBuilder(INNER_LIST_QNAME) //
+          .withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_ONE_NAME)) //
+          .withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_TWO_NAME)) //
+          .build()) //
+      .build();
+
+  public static final InputStream getDatastoreTestInputStream() {
+    return getInputStream(DATASTORE_TEST_YANG);
+  }
+
+  public static final InputStream getDatastoreAugInputStream() {
+    return getInputStream(DATASTORE_AUG_YANG);
+  }
+
+  public static final InputStream getDatastoreTestNotificationInputStream() {
+    return getInputStream(DATASTORE_TEST_NOTIFICATION_YANG);
+  }
+
+  private static InputStream getInputStream(final String resourceName) {
+    return TestModel.class.getResourceAsStream(resourceName);
+  }
+
+  public static SchemaContext createTestContext() {
+    List<InputStream> inputStreams = new ArrayList<>();
+    inputStreams.add(getDatastoreTestInputStream());
+    inputStreams.add(getDatastoreAugInputStream());
+    inputStreams.add(getDatastoreTestNotificationInputStream());
+
+    YangParserImpl parser = new YangParserImpl();
+    Set<Module> modules = parser.parseYangModelsFromStreams(inputStreams);
+    return parser.resolveSchemaContext(modules);
+  }
+
+  /**
+   * Returns a test document
+   * <p/>
+   *
+   * <pre>
+   * test
+   *     outer-list
+   *          id 1
+   *     outer-list
+   *          id 2
+   *          inner-list
+   *                  name "one"
+   *          inner-list
+   *                  name "two"
+   *
+   * </pre>
+   *
+   * @return
+   */
+  public static NormalizedNode<?, ?> createDocumentOne(
+      SchemaContext schemaContext) {
+    return ImmutableContainerNodeBuilder
+        .create()
+        .withNodeIdentifier(
+            new YangInstanceIdentifier.NodeIdentifier(schemaContext.getQName()))
+        .withChild(createTestContainer()).build();
+
+  }
+
+  public static ContainerNode createTestContainer() {
+
+
+    // Create a list of shoes
+    // This is to test leaf list entry
+    final LeafSetEntryNode<Object> nike =
+        ImmutableLeafSetEntryNodeBuilder
+            .create()
+            .withNodeIdentifier(
+                new YangInstanceIdentifier.NodeWithValue(QName.create(
+                    TEST_QNAME, "shoe"), "nike")).withValue("nike").build();
+
+    final LeafSetEntryNode<Object> puma =
+        ImmutableLeafSetEntryNodeBuilder
+            .create()
+            .withNodeIdentifier(
+                new YangInstanceIdentifier.NodeWithValue(QName.create(
+                    TEST_QNAME, "shoe"), "puma")).withValue("puma").build();
 
-    private static final YangInstanceIdentifier CHILDREN_2_PATH = YangInstanceIdentifier
-        .builder(CHILDREN_PATH)
-        .nodeWithKey(CHILDREN_QNAME, CHILD_NUMBER_QNAME, SECOND_CHILD_ID) //
-        .build();
-    private static final YangInstanceIdentifier CHILDREN_2_NAME_PATH =
-        YangInstanceIdentifier.builder(CHILDREN_PATH)
-            .nodeWithKey(CHILDREN_QNAME, CHILD_NAME_QNAME, SECOND_CHILD_NAME) //
+    final LeafSetNode<Object> shoes =
+        ImmutableLeafSetNodeBuilder
+            .create()
+            .withNodeIdentifier(
+                new YangInstanceIdentifier.NodeIdentifier(QName.create(
+                    TEST_QNAME, "shoe"))).withChild(nike).withChild(puma)
             .build();
 
 
-    private static final YangInstanceIdentifier GRAND_CHILD_1_PATH =
-        YangInstanceIdentifier.builder(CHILDREN_1_PATH)
-            .node(GRAND_CHILDREN_QNAME)
-                //
-            .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME,
-                FIRST_GRAND_CHILD_ID) //
-            .build();
+    // Test a leaf-list where each entry contains an identity
+    final LeafSetEntryNode<Object> cap1 =
+        ImmutableLeafSetEntryNodeBuilder
+            .create()
+            .withNodeIdentifier(
+                new YangInstanceIdentifier.NodeWithValue(QName.create(
+                    TEST_QNAME, "capability"), DESC_QNAME))
+            .withValue(DESC_QNAME).build();
 
-    private static final YangInstanceIdentifier GRAND_CHILD_1_NAME_PATH =
-        YangInstanceIdentifier.builder(CHILDREN_1_PATH)
-            .node(GRAND_CHILDREN_QNAME)
-                //
-            .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NAME_QNAME,
-                FIRST_GRAND_CHILD_NAME) //
-            .build();
+    final LeafSetNode<Object> capabilities =
+        ImmutableLeafSetNodeBuilder
+            .create()
+            .withNodeIdentifier(
+                new YangInstanceIdentifier.NodeIdentifier(QName.create(
+                    TEST_QNAME, "capability"))).withChild(cap1).build();
 
-    private static final YangInstanceIdentifier GRAND_CHILD_2_PATH =
-        YangInstanceIdentifier.builder(CHILDREN_2_PATH)
-            .node(GRAND_CHILDREN_QNAME)
-                //
-            .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME,
-                SECOND_GRAND_CHILD_ID) //
-            .build();
+    ContainerNode switchFeatures =
+        ImmutableContainerNodeBuilder
+            .create()
+            .withNodeIdentifier(
+                new YangInstanceIdentifier.NodeIdentifier(SWITCH_FEATURES_QNAME))
+            .withChild(capabilities).build();
 
-    private static final YangInstanceIdentifier GRAND_CHILD_2_NAME_PATH =
-        YangInstanceIdentifier.builder(CHILDREN_2_PATH)
-            .node(GRAND_CHILDREN_QNAME)
-                //
-            .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NAME_QNAME,
-                SECOND_GRAND_CHILD_NAME) //
+    // Create a leaf list with numbers
+    final LeafSetEntryNode<Object> five =
+        ImmutableLeafSetEntryNodeBuilder
+            .create()
+            .withNodeIdentifier(
+                (new YangInstanceIdentifier.NodeWithValue(QName.create(
+                    TEST_QNAME, "number"), 5))).withValue(5).build();
+    final LeafSetEntryNode<Object> fifteen =
+        ImmutableLeafSetEntryNodeBuilder
+            .create()
+            .withNodeIdentifier(
+                (new YangInstanceIdentifier.NodeWithValue(QName.create(
+                    TEST_QNAME, "number"), 15))).withValue(15).build();
+    final LeafSetNode<Object> numbers =
+        ImmutableLeafSetNodeBuilder
+            .create()
+            .withNodeIdentifier(
+                new YangInstanceIdentifier.NodeIdentifier(QName.create(
+                    TEST_QNAME, "number"))).withChild(five).withChild(fifteen)
             .build();
 
-    private static final YangInstanceIdentifier DESC_PATH_ID = YangInstanceIdentifier
-        .builder(DESC_PATH).build();
-    private static final YangInstanceIdentifier OUTER_LIST_1_PATH =
-        YangInstanceIdentifier.builder(OUTER_LIST_PATH)
-            .nodeWithKey(OUTER_LIST_QNAME, ID_QNAME, ONE_ID) //
-            .build();
 
-    private static final YangInstanceIdentifier OUTER_LIST_2_PATH =
-        YangInstanceIdentifier.builder(OUTER_LIST_PATH)
-            .nodeWithKey(OUTER_LIST_QNAME, ID_QNAME, TWO_ID) //
-            .build();
+    // Create augmentations
+    MapEntryNode mapEntry = createAugmentedListEntry(1, "First Test");
 
-    private static final YangInstanceIdentifier TWO_TWO_PATH = YangInstanceIdentifier
-        .builder(OUTER_LIST_2_PATH).node(INNER_LIST_QNAME) //
-        .nodeWithKey(INNER_LIST_QNAME, NAME_QNAME, TWO_TWO_NAME) //
-        .build();
 
-    private static final YangInstanceIdentifier TWO_TWO_VALUE_PATH =
-        YangInstanceIdentifier.builder(TWO_TWO_PATH).node(VALUE_QNAME) //
-            .build();
+    // Create the document
+    return ImmutableContainerNodeBuilder
+        .create()
+        .withNodeIdentifier(
+            new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME))
+        .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))
 
-    private static final MapEntryNode BAR_NODE = mapEntryBuilder(
-        OUTER_LIST_QNAME, ID_QNAME, TWO_ID) //
-        .withChild(mapNodeBuilder(INNER_LIST_QNAME) //
-            .withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_ONE_NAME)) //
-            .withChild(mapEntry(INNER_LIST_QNAME, NAME_QNAME, TWO_TWO_NAME)) //
-            .build()) //
-        .build();
-
-    public static final InputStream getDatastoreTestInputStream() {
-        return getInputStream(DATASTORE_TEST_YANG);
-    }
-
-    public static final InputStream getDatastoreAugInputStream() {
-        return getInputStream(DATASTORE_AUG_YANG);
-    }
-
-    public static final InputStream getDatastoreTestNotificationInputStream() {
-        return getInputStream(DATASTORE_TEST_NOTIFICATION_YANG);
-    }
-
-    private static InputStream getInputStream(final String resourceName) {
-        return TestModel.class.getResourceAsStream(resourceName);
-    }
-
-    public static SchemaContext createTestContext() {
-        List<InputStream> inputStreams = new ArrayList<>();
-        inputStreams.add(getDatastoreTestInputStream());
-        inputStreams.add(getDatastoreAugInputStream());
-        inputStreams.add(getDatastoreTestNotificationInputStream());
-
-        YangParserImpl parser = new YangParserImpl();
-        Set<Module> modules = parser.parseYangModelsFromStreams(inputStreams);
-        return parser.resolveSchemaContext(modules);
-    }
-
-    /**
-     * Returns a test document
-     * <p/>
-     * <pre>
-     * test
-     *     outer-list
-     *          id 1
-     *     outer-list
-     *          id 2
-     *          inner-list
-     *                  name "one"
-     *          inner-list
-     *                  name "two"
-     *
-     * </pre>
-     *
-     * @return
-     */
-    public static NormalizedNode<?, ?> createDocumentOne(
-        SchemaContext schemaContext) {
-        return ImmutableContainerNodeBuilder
-            .create()
-            .withNodeIdentifier(
-                new YangInstanceIdentifier.NodeIdentifier(schemaContext.getQName()))
-            .withChild(createTestContainer()).build();
-
-    }
-
-    public static ContainerNode createTestContainer() {
-
-
-        // Create a list of shoes
-        // This is to test leaf list entry
-        final LeafSetEntryNode<Object> nike =
-            ImmutableLeafSetEntryNodeBuilder
-                .create()
-                .withNodeIdentifier(
-                    new YangInstanceIdentifier.NodeWithValue(
-                        QName.create(TEST_QNAME,
-                            "shoe"), "nike")
-                ).withValue("nike").build();
-
-        final LeafSetEntryNode<Object> puma =
-            ImmutableLeafSetEntryNodeBuilder
-                .create()
-                .withNodeIdentifier(
-                    new YangInstanceIdentifier.NodeWithValue(
-                        QName.create(TEST_QNAME,
-                            "shoe"), "puma")
-                ).withValue("puma").build();
-
-        final LeafSetNode<Object> 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<Object> cap1 =
-            ImmutableLeafSetEntryNodeBuilder
-                .create()
-                .withNodeIdentifier(
-                    new YangInstanceIdentifier.NodeWithValue(
-                        QName.create(TEST_QNAME,
-                            "capability"), DESC_QNAME)
-                ).withValue(DESC_QNAME).build();
-
-        final LeafSetNode<Object> 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();
+        // .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();
+
+  }
 
-        // Create a leaf list with numbers
-        final LeafSetEntryNode<Object> five =
-            ImmutableLeafSetEntryNodeBuilder
-                .create()
-                .withNodeIdentifier(
-                    (new YangInstanceIdentifier.NodeWithValue(
-                        QName.create(TEST_QNAME,
-                            "number"), 5))
-                ).withValue(5).build();
-        final LeafSetEntryNode<Object> fifteen =
-            ImmutableLeafSetEntryNodeBuilder
-                .create()
-                .withNodeIdentifier(
-                    (new YangInstanceIdentifier.NodeWithValue(
-                        QName.create(TEST_QNAME,
-                            "number"), 15))
-                ).withValue(15).build();
-        final LeafSetNode<Object> 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 the document
-        return ImmutableContainerNodeBuilder
+  public static MapEntryNode createAugmentedListEntry(int id, String name) {
+
+    Set<QName> childAugmentations = new HashSet<>();
+    childAugmentations.add(AUG_CONT_QNAME);
+
+    ContainerNode augCont =
+        ImmutableContainerNodeBuilder
             .create()
             .withNodeIdentifier(
-                new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME))
-            .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();
-
-    }
-
-    public static MapEntryNode createAugmentedListEntry(int id, String name) {
-
-        Set<QName> childAugmentations = new HashSet<>();
-        childAugmentations.add(AUG_CONT_QNAME);
-
-        ContainerNode augCont = ImmutableContainerNodeBuilder
-            .create()
-            .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(AUG_CONT_QNAME))
-            .withChild(ImmutableNodes.leafNode(AUG_NAME_QNAME, name))
-            .build();
+                new YangInstanceIdentifier.NodeIdentifier(AUG_CONT_QNAME))
+            .withChild(ImmutableNodes.leafNode(AUG_NAME_QNAME, name)).build();
 
 
-        final YangInstanceIdentifier.AugmentationIdentifier augmentationIdentifier =
-            new YangInstanceIdentifier.AugmentationIdentifier(childAugmentations);
+    final YangInstanceIdentifier.AugmentationIdentifier augmentationIdentifier =
+        new YangInstanceIdentifier.AugmentationIdentifier(childAugmentations);
 
-        final AugmentationNode augmentationNode =
-            Builders.augmentationBuilder()
-                .withNodeIdentifier(augmentationIdentifier)
-                .withChild(augCont)
-                .build();
+    final AugmentationNode augmentationNode =
+        Builders.augmentationBuilder()
+            .withNodeIdentifier(augmentationIdentifier).withChild(augCont)
+            .build();
 
-        return ImmutableMapEntryNodeBuilder.create()
-            .withNodeIdentifier(
-                new YangInstanceIdentifier.NodeIdentifierWithPredicates(
-                    AUGMENTED_LIST_QNAME, ID_QNAME, id))
-            .withChild(ImmutableNodes.leafNode(ID_QNAME, id))
-            .withChild(augmentationNode).build();
-    }
-
-
-    public static ContainerNode createFamily() {
-        final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode>
-            familyContainerBuilder =
-            ImmutableContainerNodeBuilder.create().withNodeIdentifier(
-                new YangInstanceIdentifier.NodeIdentifier(FAMILY_QNAME));
-
-        final CollectionNodeBuilder<MapEntryNode, MapNode> childrenBuilder =
-            mapNodeBuilder(CHILDREN_QNAME);
-
-        final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode>
-            firstChildBuilder =
-            mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, FIRST_CHILD_ID);
-        final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode>
-            secondChildBuilder =
-            mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME,
-                SECOND_CHILD_ID);
-
-        final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode>
-            firstGrandChildBuilder =
-            mapEntryBuilder(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME,
-                FIRST_GRAND_CHILD_ID);
-        final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode>
-            secondGrandChildBuilder =
-            mapEntryBuilder(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME,
-                SECOND_GRAND_CHILD_ID);
-
-        firstGrandChildBuilder
-            .withChild(
-                ImmutableNodes.leafNode(GRAND_CHILD_NUMBER_QNAME,
-                    FIRST_GRAND_CHILD_ID)
-            ).withChild(
+    return ImmutableMapEntryNodeBuilder
+        .create()
+        .withNodeIdentifier(
+            new YangInstanceIdentifier.NodeIdentifierWithPredicates(
+                AUGMENTED_LIST_QNAME, ID_QNAME, id))
+        .withChild(ImmutableNodes.leafNode(ID_QNAME, id))
+        .withChild(augmentationNode).build();
+  }
+
+
+  public static ContainerNode createFamily() {
+    final DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> familyContainerBuilder =
+        ImmutableContainerNodeBuilder.create().withNodeIdentifier(
+            new YangInstanceIdentifier.NodeIdentifier(FAMILY_QNAME));
+
+    final CollectionNodeBuilder<MapEntryNode, MapNode> childrenBuilder =
+        mapNodeBuilder(CHILDREN_QNAME);
+
+    final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> firstChildBuilder =
+        mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, FIRST_CHILD_ID);
+    final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> secondChildBuilder =
+        mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, SECOND_CHILD_ID);
+
+    final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> firstGrandChildBuilder =
+        mapEntryBuilder(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME,
+            FIRST_GRAND_CHILD_ID);
+    final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> secondGrandChildBuilder =
+        mapEntryBuilder(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME,
+            SECOND_GRAND_CHILD_ID);
+
+    firstGrandChildBuilder
+        .withChild(
+            ImmutableNodes.leafNode(GRAND_CHILD_NUMBER_QNAME,
+                FIRST_GRAND_CHILD_ID)).withChild(
             ImmutableNodes.leafNode(GRAND_CHILD_NAME_QNAME,
-                FIRST_GRAND_CHILD_NAME)
-        );
-
-        secondGrandChildBuilder.withChild(
-            ImmutableNodes
-                .leafNode(GRAND_CHILD_NUMBER_QNAME, SECOND_GRAND_CHILD_ID)
-        )
-            .withChild(
-                ImmutableNodes.leafNode(GRAND_CHILD_NAME_QNAME,
-                    SECOND_GRAND_CHILD_NAME)
-            );
-
-        firstChildBuilder
-            .withChild(
-                ImmutableNodes.leafNode(CHILD_NUMBER_QNAME, FIRST_CHILD_ID))
-            .withChild(
-                ImmutableNodes.leafNode(CHILD_NAME_QNAME, FIRST_CHILD_NAME))
-            .withChild(
-                mapNodeBuilder(GRAND_CHILDREN_QNAME).withChild(
-                    firstGrandChildBuilder.build()).build()
-            );
-
-
-        secondChildBuilder
-            .withChild(
-                ImmutableNodes.leafNode(CHILD_NUMBER_QNAME, SECOND_CHILD_ID))
-            .withChild(
-                ImmutableNodes.leafNode(CHILD_NAME_QNAME, SECOND_CHILD_NAME))
-            .withChild(
-                mapNodeBuilder(GRAND_CHILDREN_QNAME).withChild(
-                    firstGrandChildBuilder.build()).build()
-            );
-
-        childrenBuilder.withChild(firstChildBuilder.build());
-        childrenBuilder.withChild(secondChildBuilder.build());
-
-        return familyContainerBuilder.withChild(childrenBuilder.build())
-            .build();
-    }
+                FIRST_GRAND_CHILD_NAME));
+
+    secondGrandChildBuilder.withChild(
+        ImmutableNodes
+            .leafNode(GRAND_CHILD_NUMBER_QNAME, SECOND_GRAND_CHILD_ID))
+        .withChild(
+            ImmutableNodes.leafNode(GRAND_CHILD_NAME_QNAME,
+                SECOND_GRAND_CHILD_NAME));
+
+    firstChildBuilder
+        .withChild(ImmutableNodes.leafNode(CHILD_NUMBER_QNAME, FIRST_CHILD_ID))
+        .withChild(ImmutableNodes.leafNode(CHILD_NAME_QNAME, FIRST_CHILD_NAME))
+        .withChild(
+            mapNodeBuilder(GRAND_CHILDREN_QNAME).withChild(
+                firstGrandChildBuilder.build()).build());
+
+
+    secondChildBuilder
+        .withChild(ImmutableNodes.leafNode(CHILD_NUMBER_QNAME, SECOND_CHILD_ID))
+        .withChild(ImmutableNodes.leafNode(CHILD_NAME_QNAME, SECOND_CHILD_NAME))
+        .withChild(
+            mapNodeBuilder(GRAND_CHILDREN_QNAME).withChild(
+                firstGrandChildBuilder.build()).build());
+
+    childrenBuilder.withChild(firstChildBuilder.build());
+    childrenBuilder.withChild(secondChildBuilder.build());
+
+    return familyContainerBuilder.withChild(childrenBuilder.build()).build();
+  }
 
 }
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/AbstractMessagesTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/AbstractMessagesTest.java
new file mode 100644 (file)
index 0000000..c6c4afd
--- /dev/null
@@ -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.protobuff.messages;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+
+/**
+ * @author: syedbahm Date: 7/31/14
+ */
+public abstract class AbstractMessagesTest {
+  public final String VERSION_COMPATIBILTY_TEST_DATA_PATH = "."
+      + File.separator + "src" + File.separator + "test" + File.separator
+      + "resources" + File.separator + "version-compatibility-serialized-data";
+  private File file;
+  private File testDataFile;
+
+  protected AbstractMessagesTest() {
+    init();
+  }
+
+  protected void init() {
+    file = new File(getTestFileName());
+    testDataFile =
+        new File(VERSION_COMPATIBILTY_TEST_DATA_PATH + File.separator
+            + getTestFileName() + "Data");
+  }
+
+
+
+  abstract public void verifySerialization() throws Exception;
+
+
+  protected void writeToFile(
+      com.google.protobuf.GeneratedMessage.Builder<?> builder) throws Exception {
+
+    FileOutputStream output = new FileOutputStream(file);
+    builder.build().writeTo(output);
+    output.close();;
+
+  }
+
+  protected com.google.protobuf.GeneratedMessage readFromFile(
+      com.google.protobuf.Parser<?> parser) throws Exception {
+    com.google.protobuf.GeneratedMessage message =
+        (com.google.protobuf.GeneratedMessage) parser
+            .parseFrom(new FileInputStream(file));
+
+    /*Note: we will delete only the test file -- comment below if you want to capture the
+       version-compatibility-serialized-data test data file.The file will be generated at root of the
+       sal-protocolbuffer-encoding
+       and you need to move it to test/resources/version-compatbility-serialized-data folder renaming the file to include suffix <TestFileName>"Data"
+    */
+     file.delete();
+    return message;
+  }
+
+  protected com.google.protobuf.GeneratedMessage readFromTestDataFile(
+      com.google.protobuf.Parser<?> parser) throws Exception {
+    return (com.google.protobuf.GeneratedMessage) parser
+        .parseFrom(new FileInputStream(testDataFile));
+  }
+
+
+  public abstract String getTestFileName();
+
+
+}
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/ShardManagerMessagesTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/ShardManagerMessagesTest.java
deleted file mode 100644 (file)
index b0758da..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-package org.opendaylight.controller.protobuff.messages;
-
-/**
- * This test case is present to ensure that if others have used proper version of protocol buffer.
- *
- * If a different version of protocol buffer is used then it would generate different java sources
- * and would result in breaking of this test case.
- *
- * @author: syedbahm Date: 6/20/14
- *
- */
-
-import org.junit.Assert;
-import org.junit.Test;
-import org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-
-public class ShardManagerMessagesTest {
-
-  @Test
-  public void verifySerialization() throws Exception {
-    ShardManagerMessages.FindPrimary.Builder builder =
-        ShardManagerMessages.FindPrimary.newBuilder();
-    builder.setShardName("Inventory");
-    File testFile = new File("./test");
-    FileOutputStream output = new FileOutputStream(testFile);
-    builder.build().writeTo(output);
-    output.close();
-
-    // Here we will read the same and check we got back what we had saved
-    ShardManagerMessages.FindPrimary findPrimary =
-        ShardManagerMessages.FindPrimary
-            .parseFrom(new FileInputStream(testFile));
-    Assert.assertEquals("Inventory", findPrimary.getShardName());
-
-    testFile.delete();
-
-  }
-}
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/cohort3pc/ThreePhaseCommitCohortMessagesTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/cohort3pc/ThreePhaseCommitCohortMessagesTest.java
new file mode 100644 (file)
index 0000000..a01ccb8
--- /dev/null
@@ -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.protobuff.messages.cohort3pc;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.opendaylight.controller.protobuff.messages.AbstractMessagesTest;
+
+/**
+ * This test case is present to ensure that if others have used proper version of protocol buffer
+ * for the cohort.proto messages
+ *
+ * If a different version of protocol buffer and there is change in serializaiton format
+ * this test would break as we are comparing with protocol buffer 2.5 generated
+ * serialized data.
+ *
+ * @author: syedbahm
+ *
+ */
+
+
+public class ThreePhaseCommitCohortMessagesTest extends AbstractMessagesTest {
+
+
+  @Test
+  public void verifySerialization() throws Exception {
+
+
+
+    ThreePhaseCommitCohortMessages.CanCommitTransactionReply.Builder builder =
+        ThreePhaseCommitCohortMessages.CanCommitTransactionReply.newBuilder();
+    builder.setCanCommit(true);
+
+    writeToFile((com.google.protobuf.GeneratedMessage.Builder<?>) builder);
+
+    // Here we will read from the just serialized data
+
+    ThreePhaseCommitCohortMessages.CanCommitTransactionReply newCanCommitTransactionReply =
+        (ThreePhaseCommitCohortMessages.CanCommitTransactionReply) readFromFile(ThreePhaseCommitCohortMessages.CanCommitTransactionReply.PARSER);
+
+    Assert.assertTrue(newCanCommitTransactionReply.getCanCommit());
+
+
+    // Here we will read the same from our test-data file and check we got back what we had saved
+    // earlier
+    ThreePhaseCommitCohortMessages.CanCommitTransactionReply originalCanCommitTransactionReply =
+        (ThreePhaseCommitCohortMessages.CanCommitTransactionReply) readFromTestDataFile(ThreePhaseCommitCohortMessages.CanCommitTransactionReply.PARSER);
+
+    Assert.assertEquals(newCanCommitTransactionReply.getCanCommit(),
+        originalCanCommitTransactionReply.getCanCommit());
+
+  }
+
+  @Override
+  public String getTestFileName() {
+    return ThreePhaseCommitCohortMessagesTest.class.getSimpleName();
+  }
+
+
+}
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/common/NormalizedNodeMessagesTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/common/NormalizedNodeMessagesTest.java
new file mode 100644 (file)
index 0000000..c68ecea
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ *
+ *  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.protobuff.messages.common;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.opendaylight.controller.protobuff.messages.AbstractMessagesTest;
+
+/**
+ * This test case is present to ensure that if others have used proper version of protocol buffer
+ * for the common.proto messages
+ *
+ * If a different version of protocol buffer and there is change in serializaiton format
+ * this test would break as we are comparing with protocol buffer 2.5 generated
+ * serialized data.
+ *
+ * @author: syedbahm
+ *
+ */
+
+public class NormalizedNodeMessagesTest extends AbstractMessagesTest {
+
+  @Override
+  @Test
+  public void verifySerialization() throws Exception {
+    NormalizedNodeMessages.Attribute.Builder builder =
+        NormalizedNodeMessages.Attribute.newBuilder();
+    builder.setName("test");
+    builder.setType("fake");
+    builder.setValue("testValue");
+    writeToFile((com.google.protobuf.GeneratedMessage.Builder<?>) builder);
+
+    NormalizedNodeMessages.Attribute attributeNew =
+        (NormalizedNodeMessages.Attribute) readFromFile(NormalizedNodeMessages.Attribute.PARSER);
+    Assert.assertEquals("test", attributeNew.getName());
+    Assert.assertEquals("fake", attributeNew.getType());
+    Assert.assertEquals("testValue", attributeNew.getValue());
+
+    NormalizedNodeMessages.Attribute attributeOriginal =
+        (NormalizedNodeMessages.Attribute) readFromTestDataFile(NormalizedNodeMessages.Attribute.PARSER);
+    Assert.assertEquals(attributeNew.getName(), attributeOriginal.getName());
+  }
+
+  @Override
+  public String getTestFileName() {
+    return NormalizedNodeMessagesTest.class.getSimpleName();
+  }
+
+
+}
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/datachange/notification/DataChangeListenerMessagesTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/datachange/notification/DataChangeListenerMessagesTest.java
new file mode 100644 (file)
index 0000000..e933928
--- /dev/null
@@ -0,0 +1,78 @@
+/*
+ *
+ *  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.protobuff.messages.datachange.notification;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.opendaylight.controller.protobuff.messages.AbstractMessagesTest;
+import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages;
+import org.opendaylight.yangtools.yang.common.QName;
+
+/**
+ * This test case is present to ensure that if others have used proper version of protocol buffer
+ * for the DataChangeListener.proto messages
+ *
+ * If a different version of protocol buffer and there is change in serializaiton format
+ * this test would break as we are comparing with protocol buffer 2.5 generated
+ * serialized data.
+ *
+ * @author: syedbahm
+ *
+ */
+
+public class DataChangeListenerMessagesTest extends AbstractMessagesTest {
+
+  private final String namespace = "urn:protobuff", revision = "2014-07-31",
+      localName = "test";
+
+  @Override
+  @Test
+  public void verifySerialization() throws Exception {
+    NormalizedNodeMessages.InstanceIdentifier.Builder instanceIdentifierBuilder =
+        NormalizedNodeMessages.InstanceIdentifier.newBuilder();
+    NormalizedNodeMessages.PathArgument.Builder pathArgument =
+        NormalizedNodeMessages.PathArgument.newBuilder();
+    pathArgument.setNodeType(NormalizedNodeMessages.QName.newBuilder()
+        .setValue(QName.create(namespace, revision, localName).toString())
+        .build());
+    pathArgument.setValue("test");
+    instanceIdentifierBuilder.addArguments(pathArgument.build());
+
+    NormalizedNodeMessages.InstanceIdentifier expectedOne =
+        instanceIdentifierBuilder.build();
+    DataChangeListenerMessages.DataChanged.Builder builder =
+        DataChangeListenerMessages.DataChanged.newBuilder();
+    builder.addRemovedPaths(expectedOne);
+
+    writeToFile((com.google.protobuf.GeneratedMessage.Builder<?>) builder);
+
+    DataChangeListenerMessages.DataChanged dataChangedNew =
+        (DataChangeListenerMessages.DataChanged) readFromFile(DataChangeListenerMessages.DataChanged.PARSER);
+    Assert.assertEquals(expectedOne.getArgumentsCount(), dataChangedNew
+        .getRemovedPaths(0).getArgumentsCount());
+    Assert.assertEquals(expectedOne.getArguments(0).getType(), dataChangedNew
+        .getRemovedPaths(0).getArguments(0).getType());
+
+    DataChangeListenerMessages.DataChanged dataChangedOriginal =
+        (DataChangeListenerMessages.DataChanged) readFromTestDataFile(DataChangeListenerMessages.DataChanged.PARSER);
+    Assert.assertEquals(dataChangedNew.getRemovedPathsCount(),
+        dataChangedOriginal.getRemovedPathsCount());
+    Assert.assertEquals(dataChangedNew.getRemovedPaths(0).getArguments(0)
+        .getValue(), dataChangedOriginal.getRemovedPaths(0).getArguments(0)
+        .getValue());
+
+  }
+
+  @Override
+  public String getTestFileName() {
+    return DataChangeListenerMessages.class.getSimpleName();
+  }
+}
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/persistent/PersistentMessagesTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/persistent/PersistentMessagesTest.java
new file mode 100644 (file)
index 0000000..a8ade30
--- /dev/null
@@ -0,0 +1,82 @@
+/*
+ *
+ *  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.protobuff.messages.persistent;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.opendaylight.controller.protobuff.messages.AbstractMessagesTest;
+import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages;
+import org.opendaylight.yangtools.yang.common.QName;
+
+
+/**
+ * This test case is present to ensure that if others have used proper version of protocol buffer
+ * for the peristent.proto messages
+ *
+ * If a different version of protocol buffer and there is change in serializaiton format
+ * this test would break as we are comparing with protocol buffer 2.5 generated
+ * serialized data.
+ *
+ * @author: syedbahm
+ *
+ */
+
+public class PersistentMessagesTest extends AbstractMessagesTest {
+
+  private final String namespace = "urn:protobuff", revision = "2014-07-31",
+      localName = "test";
+
+  @Override
+  @Test
+  public void verifySerialization() throws Exception {
+    NormalizedNodeMessages.InstanceIdentifier.Builder instanceIdentifierBuilder =
+        NormalizedNodeMessages.InstanceIdentifier.newBuilder();
+    NormalizedNodeMessages.PathArgument.Builder pathArgument =
+        NormalizedNodeMessages.PathArgument.newBuilder();
+    pathArgument.setNodeType(NormalizedNodeMessages.QName.newBuilder()
+        .setValue(QName.create(namespace, revision, localName).toString())
+        .build());
+    pathArgument.setValue("test");
+    instanceIdentifierBuilder.addArguments(pathArgument.build());
+    NormalizedNodeMessages.InstanceIdentifier expectedOne =
+        instanceIdentifierBuilder.build();
+
+    PersistentMessages.Modification.Builder builder =
+        PersistentMessages.Modification.newBuilder();
+    builder.setType("test");
+    builder.setPath(expectedOne);
+
+    writeToFile((com.google.protobuf.GeneratedMessage.Builder<?>) builder);
+
+    PersistentMessages.Modification modificationNew =
+        (PersistentMessages.Modification) readFromFile(PersistentMessages.Modification.PARSER);
+    Assert.assertEquals("test", modificationNew.getType());
+    Assert.assertEquals(expectedOne.getArguments(0).getValue(), modificationNew
+        .getPath().getArguments(0).getValue());
+    Assert.assertEquals(expectedOne.getArguments(0).getType(), modificationNew
+        .getPath().getArguments(0).getType());
+
+    // we will compare with the serialized data that we had shipped
+    PersistentMessages.Modification modificationOriginal =
+        (PersistentMessages.Modification) readFromTestDataFile(PersistentMessages.Modification.PARSER);
+    Assert.assertEquals(modificationOriginal.getPath().getArguments(0)
+        .getValue(), modificationNew.getPath().getArguments(0).getValue());
+    Assert.assertEquals(modificationOriginal.getPath().getArguments(0)
+        .getType(), modificationNew.getPath().getArguments(0).getType());
+
+
+  }
+
+  @Override
+  public String getTestFileName() {
+    return PersistentMessagesTest.class.getSimpleName();
+  }
+}
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/registration/ListenerRegistrationMessagesTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/registration/ListenerRegistrationMessagesTest.java
new file mode 100644 (file)
index 0000000..1d50872
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ *
+ *  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.protobuff.messages.registration;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.opendaylight.controller.protobuff.messages.AbstractMessagesTest;
+
+/**
+ * This test case is present to ensure that if others have used proper version of protocol buffer
+ * for the ListenerRegistration.proto messages
+ *
+ * If a different version of protocol buffer and there is change in serializaiton format
+ * this test would break as we are comparing with protocol buffer 2.5 generated
+ * serialized data.
+ *
+ * @author: syedbahm
+ *
+ */
+
+public class ListenerRegistrationMessagesTest extends AbstractMessagesTest {
+
+  @Override
+  @Test
+  public void verifySerialization() throws Exception {
+    String testListenerRegistrationPath =
+        "(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:notification-test?revision=2014-04-15)family";
+    ListenerRegistrationMessages.RegisterChangeListenerReply.Builder builder =
+        ListenerRegistrationMessages.RegisterChangeListenerReply.newBuilder();
+    builder.setListenerRegistrationPath(testListenerRegistrationPath);
+
+    writeToFile((com.google.protobuf.GeneratedMessage.Builder<?>) builder);
+
+    ListenerRegistrationMessages.RegisterChangeListenerReply rclrNew =
+        (ListenerRegistrationMessages.RegisterChangeListenerReply) readFromFile(ListenerRegistrationMessages.RegisterChangeListenerReply.PARSER);
+    Assert.assertEquals(testListenerRegistrationPath,
+        rclrNew.getListenerRegistrationPath());
+
+    ListenerRegistrationMessages.RegisterChangeListenerReply rclrOriginal =
+        (ListenerRegistrationMessages.RegisterChangeListenerReply) readFromTestDataFile(ListenerRegistrationMessages.RegisterChangeListenerReply.PARSER);
+    Assert.assertEquals(rclrOriginal.getListenerRegistrationPath(),
+        rclrNew.getListenerRegistrationPath());
+
+  }
+
+  @Override
+  public String getTestFileName() {
+    return ListenerRegistrationMessages.class.getSimpleName();
+  }
+}
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/shard/ShardManagerMessagesTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/shard/ShardManagerMessagesTest.java
new file mode 100644 (file)
index 0000000..45dcd12
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ *
+ *  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.protobuff.messages.shard;
+
+/**
+ * This test case is present to ensure that if others have used proper version of protocol buffer
+ * for the ShardManager.proto messages
+ *
+ * If a different version of protocol buffer and there is change in serializaiton format
+ * this test would break as we are comparing with protocol buffer 2.5 generated
+ * serialized data.
+ *
+ * @author: syedbahm
+ *
+ */
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.opendaylight.controller.protobuff.messages.AbstractMessagesTest;
+
+public class ShardManagerMessagesTest extends AbstractMessagesTest {
+
+  @Test
+  public void verifySerialization() throws Exception {
+    ShardManagerMessages.FindPrimary.Builder builder =
+        ShardManagerMessages.FindPrimary.newBuilder();
+    builder.setShardName("Inventory");
+
+    writeToFile((com.google.protobuf.GeneratedMessage.Builder<?>) builder);
+
+
+    // Here we will read the same and check we got back what we had saved
+    ShardManagerMessages.FindPrimary findPrimaryNew =
+        (ShardManagerMessages.FindPrimary) readFromFile(ShardManagerMessages.FindPrimary.PARSER);
+
+    Assert.assertEquals("Inventory", findPrimaryNew.getShardName());
+
+    // Here we compare with the version we had shipped to catch any protobuff compiler version
+    // changes
+    ShardManagerMessages.FindPrimary findPrimaryOriginal =
+        (ShardManagerMessages.FindPrimary) readFromTestDataFile(ShardManagerMessages.FindPrimary.PARSER);
+
+    Assert.assertEquals(findPrimaryNew.getShardName(),
+        findPrimaryOriginal.getShardName());
+
+  }
+
+  @Override
+  public String getTestFileName() {
+    return ShardManagerMessagesTest.class.getSimpleName();
+  }
+
+}
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionChainMessagesTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionChainMessagesTest.java
new file mode 100644 (file)
index 0000000..c0e91ab
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ *
+ *  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.protobuff.messages.transaction;
+
+import org.junit.Assert;
+import org.junit.Test;
+import org.opendaylight.controller.protobuff.messages.AbstractMessagesTest;
+import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages;
+import org.opendaylight.yangtools.yang.common.QName;
+
+/**
+ * This test case is present to ensure that if others have used proper version of protocol buffer
+ * for the ShardTransactionChain.proto messages
+ *
+ * If a different version of protocol buffer and there is change in serializaiton format
+ * this test would break as we are comparing with protocol buffer 2.5 generated
+ * serialized data.
+ *
+ * @author: syedbahm
+ *
+ */
+
+
+public class ShardTransactionChainMessagesTest extends AbstractMessagesTest {
+
+  @Override
+  @Test
+  public void verifySerialization() throws Exception {
+    String testTransactionChainPath =
+        "/actor/path";
+
+    ShardTransactionChainMessages.CreateTransactionChainReply.Builder builder =
+        ShardTransactionChainMessages.CreateTransactionChainReply.newBuilder();
+    builder.setTransactionChainPath(testTransactionChainPath);
+
+    writeToFile((com.google.protobuf.GeneratedMessage.Builder<?>) builder);
+
+    // Here we will read the same and check we got back what we had saved
+    ShardTransactionChainMessages.CreateTransactionChainReply replyNew =
+        (ShardTransactionChainMessages.CreateTransactionChainReply) readFromFile(ShardTransactionChainMessages.CreateTransactionChainReply.PARSER);
+
+    Assert.assertEquals(replyNew.getTransactionChainPath(),testTransactionChainPath);
+
+    // the following will compare with the version we had shipped
+    ShardTransactionChainMessages.CreateTransactionChainReply replyOriginal =
+        (ShardTransactionChainMessages.CreateTransactionChainReply) readFromTestDataFile(ShardTransactionChainMessages.CreateTransactionChainReply.PARSER);
+
+
+    Assert.assertEquals(replyOriginal.getTransactionChainPath(),
+        replyNew.getTransactionChainPath());
+
+  }
+
+  @Override
+  public String getTestFileName() {
+    return ShardTransactionChainMessagesTest.class.getSimpleName();
+  }
+
+
+
+}
index 2b1ee5630c0c0665cc7a25f9a7b89630d9e4ff9c..6b538dab0da711250ab867e00a7ca42f80d45395 100644 (file)
@@ -1,10 +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.protobuff.messages.transaction;
 
+import org.junit.Assert;
+import org.junit.Test;
+import org.opendaylight.controller.protobuff.messages.AbstractMessagesTest;
+import org.opendaylight.controller.protobuff.messages.common.NormalizedNodeMessages;
+import org.opendaylight.yangtools.yang.common.QName;
+
 /**
+ * This test case is present to ensure that if others have used proper version of protocol buffer
+ * for the ShardTransaction.proto messages
+ *
+ * If a different version of protocol buffer and there is change in serializaiton format
+ * this test would break as we are comparing with protocol buffer 2.5 generated
+ * serialized data.
+ *
  * @author: syedbahm
- * Date: 7/7/14
+ *
  */
-public class ShardTransactionMessagesTest {
+
+
+public class ShardTransactionMessagesTest extends AbstractMessagesTest {
+
+  private final String namespace = "urn:protobuff", revision = "2014-07-31",
+      localName = "test";
+
+  @Test
+  public void verifySerialization() throws Exception {
+    NormalizedNodeMessages.InstanceIdentifier.Builder instanceIdentifierBuilder =
+        NormalizedNodeMessages.InstanceIdentifier.newBuilder();
+    NormalizedNodeMessages.PathArgument.Builder pathArgument =
+        NormalizedNodeMessages.PathArgument.newBuilder();
+    pathArgument.setNodeType(NormalizedNodeMessages.QName.newBuilder()
+        .setValue(QName.create(namespace, revision, localName).toString())
+        .build());
+    pathArgument.setValue("test");
+    instanceIdentifierBuilder.addArguments(pathArgument.build());
+    ShardTransactionMessages.ReadData.Builder builder =
+        ShardTransactionMessages.ReadData.newBuilder();
+    NormalizedNodeMessages.InstanceIdentifier expectedOne =
+        instanceIdentifierBuilder.build();
+    builder.setInstanceIdentifierPathArguments(expectedOne);
+
+    writeToFile((com.google.protobuf.GeneratedMessage.Builder<?>) builder);
+
+    // Here we will read the same and check we got back what we had saved
+    ShardTransactionMessages.ReadData readDataNew =
+        (ShardTransactionMessages.ReadData) readFromFile(ShardTransactionMessages.ReadData.PARSER);
+
+
+    Assert.assertEquals(expectedOne.getArgumentsCount(), readDataNew
+        .getInstanceIdentifierPathArguments().getArgumentsCount());
+    Assert.assertEquals(expectedOne.getArguments(0), readDataNew
+        .getInstanceIdentifierPathArguments().getArguments(0));
+
+
+    // the following will compare with the version we had shipped
+    ShardTransactionMessages.ReadData readDataOriginal =
+        (ShardTransactionMessages.ReadData) readFromTestDataFile(ShardTransactionMessages.ReadData.PARSER);
+
+
+    Assert.assertEquals(readDataNew.getInstanceIdentifierPathArguments()
+        .getArguments(0), readDataOriginal.getInstanceIdentifierPathArguments()
+        .getArguments(0));
+
+  }
+
+  @Override
+  public String getTestFileName() {
+    return ShardTransactionMessagesTest.class.getSimpleName();
+  }
+
 
 
 }
index c5a581cecca69b69b739a0d60d820334aaa16c0d..7de3d077b4af59c33a7e54bc8ec4aeea0d6d23f5 100644 (file)
@@ -1,3 +1,13 @@
+<!--
+  ~ /*
+  ~  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
+  ~  */
+  -->
+
 <container xmlns="urn:opendaylight:params:xml:ns:yang:controller:test">
 
     <c2Leaf>2</c2Leaf>
index 0316d7a4a82ad8259fdbcb5b40790a5ec435b086..934d876747c6e8a83f00fcb890437d98cdaaf839 100644 (file)
@@ -1,3 +1,13 @@
+<!--
+  ~ /*
+  ~  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
+  ~  */
+  -->
+
 <container xmlns="urn:opendaylight:params:xml:ns:yang:controller:test" name="test" xmlns:foo="http://www.foo.com/"
            foo:baz="baz">
 
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/DataChangeListenerMessagesData b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/DataChangeListenerMessagesData
new file mode 100644 (file)
index 0000000..883bcad
--- /dev/null
@@ -0,0 +1,4 @@
+23
+1
+\ 4test\1a)
+'(urn:protobuff?revision=2014-07-31)test
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ListenerRegistrationMessagesData b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ListenerRegistrationMessagesData
new file mode 100644 (file)
index 0000000..1718a01
--- /dev/null
@@ -0,0 +1,2 @@
+
+m(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:notification-test?revision=2014-04-15)family
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/NormalizedNodeMessagesTestData b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/NormalizedNodeMessagesTestData
new file mode 100644 (file)
index 0000000..c4ec377
--- /dev/null
@@ -0,0 +1,2 @@
+
+\ 4test\12 testValue\1a\ 4fake
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/PersistentMessagesTestData b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/PersistentMessagesTestData
new file mode 100644 (file)
index 0000000..efb8e15
--- /dev/null
@@ -0,0 +1,5 @@
+
+\ 4test\123
+1
+\ 4test\1a)
+'(urn:protobuff?revision=2014-07-31)test
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ShardManagerMessagesTestData b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ShardManagerMessagesTestData
new file mode 100644 (file)
index 0000000..82eea07
--- /dev/null
@@ -0,0 +1,2 @@
+
+       Inventory
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ShardTransactionChainMessagesTestData b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ShardTransactionChainMessagesTestData
new file mode 100644 (file)
index 0000000..577d9c4
--- /dev/null
@@ -0,0 +1,2 @@
+
+\v/actor/path
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ShardTransactionMessagesTestData b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ShardTransactionMessagesTestData
new file mode 100644 (file)
index 0000000..db43fa4
--- /dev/null
@@ -0,0 +1,5 @@
+
+3
+1
+\ 4test\1a)
+'(urn:protobuff?revision=2014-07-31)test
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ThreePhaseCommitCohortMessagesTestData b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/ThreePhaseCommitCohortMessagesTestData
new file mode 100644 (file)
index 0000000..e19a122
--- /dev/null
@@ -0,0 +1 @@
+\b\ 1
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/readme.txt b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/version-compatibility-serialized-data/readme.txt
new file mode 100644 (file)
index 0000000..06a561e
--- /dev/null
@@ -0,0 +1,18 @@
+This directory contains one serialized test data file for one of the messages in each .proto file.
+These files are utilized as part of the  test cases, mostly to fail the test cases in case some engineer has used
+a different version of protocol buffer than what we ship with (Protocol Buffer 2.5.0) to generate the messages source f
+file.
+
+1. If you see protocolbuffer version/invalid message exception in the test case
+  1. ensure you are using the right version of protocol buffer/protoc compiler i.e protocol
+
+2. If you have knowingly updated an existing .proto message than please update the corresponding version-compatibility-serialized-data
+file. You can get the file by commenting out the test file deletion in AbstractMessagesTest look for comments
+
+ /* we will delete only the test file -- comment below if you want to capture the
+       version-compatibility-serialized-data test data file.The file will be generated at root of the sal-protocolbuffer-encoding
+       and you need to move it to version-compatbility-serialized-data folder renaming the file to include suffix <TestFileName>"Data"
+  */
+
+3. If you are creating a new .proto file -- Follow an existing test case e.g. ThreePhaseCommitCohortMessagesTest to
+   check how the test case is created and create the corresponding serialized test data file in version-compatibility-serialized-data
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/ActorConstants.java b/opendaylight/md-sal/sal-remoterpc-connector/src/main/java/org/opendaylight/controller/remote/rpc/ActorConstants.java
new file mode 100644 (file)
index 0000000..1f1a0f5
--- /dev/null
@@ -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.remote.rpc;
+
+
+public class ActorConstants {
+  public static final String RPC_BROKER = "rpc-broker";
+  public static final String RPC_REGISTRY = "rpc-registry";
+  public static final String RPC_MANAGER = "rpc";
+
+  public static final String RPC_BROKER_PATH= "/user/rpc/rpc-broker";
+  public static final String RPC_REGISTRY_PATH = "/user/rpc/rpc-registry";
+}
index 3df572d7c27226511eaa08e096d4477807099f6f..ac50b8fe5b0fcdcbfb9f78ef495308586a4a313c 100644 (file)
@@ -68,7 +68,7 @@ public class RemoteRpcProvider implements AutoCloseable, Provider, SchemaContext
     SchemaService schemaService = brokerSession.getService(SchemaService.class);
     schemaContext = schemaService.getGlobalContext();
 
-    rpcManager = actorSystem.actorOf(RpcManager.props(clusterWrapper, schemaContext, brokerSession, rpcProvisionRegistry), "rpc");
+    rpcManager = actorSystem.actorOf(RpcManager.props(clusterWrapper, schemaContext, brokerSession, rpcProvisionRegistry), ActorConstants.RPC_MANAGER);
 
     LOG.debug("Rpc actors are created.");
   }
index 4925a17c137f12512a598f28240f907216356acc..5c56455bd0c208a40709b4a221fb6a22ed0b65a1 100644 (file)
@@ -72,14 +72,14 @@ public class RpcManager extends AbstractUntypedActor {
   private void createRpcActors() {
     LOG.debug("Create rpc registry and broker actors");
 
-    rpcRegistry = getContext().actorOf(RpcRegistry.props(clusterWrapper), "rpc-registry");
-    rpcBroker = getContext().actorOf(RpcBroker.props(brokerSession, rpcRegistry, schemaContext), "rpc-broker");
+    rpcRegistry = getContext().actorOf(RpcRegistry.props(clusterWrapper), ActorConstants.RPC_REGISTRY);
+    rpcBroker = getContext().actorOf(RpcBroker.props(brokerSession, rpcRegistry, schemaContext), ActorConstants.RPC_BROKER);
   }
 
   private void startListeners() {
     LOG.debug("Registers rpc listeners");
 
-    String rpcBrokerPath = clusterWrapper.getAddress().toString() + "/user/rpc/rpc-broker";
+    String rpcBrokerPath = clusterWrapper.getAddress().toString() + ActorConstants.RPC_BROKER_PATH;
     rpcListener = new RpcListener(rpcRegistry, rpcBrokerPath);
     routeChangeListener = new RoutedRpcListener(rpcRegistry, rpcBrokerPath);
     rpcImplementation = new RemoteRpcImplementation(rpcBroker, schemaContext);
index 7cb505aa98d3d8c81c70cae5bfd5292f4da5ffd2..e36060cc13ece309f04f10adebdb74a62f158146 100644 (file)
@@ -14,6 +14,7 @@ import akka.cluster.ClusterEvent;
 import akka.cluster.Member;
 import akka.japi.Creator;
 import org.opendaylight.controller.remote.rpc.AbstractUntypedActor;
+import org.opendaylight.controller.remote.rpc.ActorConstants;
 import org.opendaylight.controller.remote.rpc.messages.AddRoutedRpc;
 import org.opendaylight.controller.remote.rpc.messages.AddRpc;
 import org.opendaylight.controller.remote.rpc.messages.GetRoutedRpc;
@@ -171,7 +172,7 @@ public class RpcRegistry extends AbstractUntypedActor {
         }
         if(i == index) {
           if(!currentNodeAddress.equals(member.address())) {
-            actor = this.context().actorSelection(member.address() + "/user/rpc-registry");
+            actor = this.context().actorSelection(member.address() + ActorConstants.RPC_REGISTRY_PATH);
             break;
           } else if(index < memberSize-1){ // pick the next element in the set
             index++;
@@ -180,7 +181,7 @@ public class RpcRegistry extends AbstractUntypedActor {
         i++;
       }
       if(actor == null && previousMember != null) {
-        actor = this.context().actorSelection(previousMember.address() + "/user/rpc-registry");
+        actor = this.context().actorSelection(previousMember.address() + ActorConstants.RPC_REGISTRY_PATH);
       }
     }
     return actor;
index bef1be2ed1d491ce5c9b7051d5489d7eff8ef96d..2fa99819d5f833a27c0de9d6fa02053e955b87ce 100644 (file)
@@ -20,13 +20,13 @@ import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
 import org.opendaylight.controller.sal.streams.websockets.WebSocketServer;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.PortNumber;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
 
 public class RestconfProviderImpl implements Provider, AutoCloseable, RestConnector {
 
     public final static String NOT_INITALIZED_MSG = "Restconf is not initialized yet. Please try again later";
 
-    private ListenerRegistration<SchemaServiceListener> listenerRegistration;
+    private ListenerRegistration<SchemaContextListener> listenerRegistration;
     private PortNumber port;
     public void setWebsocketPort(PortNumber port) {
         this.port = port;
@@ -42,7 +42,7 @@ public class RestconfProviderImpl implements Provider, AutoCloseable, RestConnec
         BrokerFacade.getInstance().setDomDataBroker( domDataBroker);
 
         SchemaService schemaService = session.getService(SchemaService.class);
-        listenerRegistration = schemaService.registerSchemaServiceListener(ControllerContext.getInstance());
+        listenerRegistration = schemaService.registerSchemaContextListener(ControllerContext.getInstance());
         ControllerContext.getInstance().setSchemas(schemaService.getGlobalContext());
         ControllerContext.getInstance().setMountService(session.getService(DOMMountPointService.class));
 
index 6db4e63d10f74216cf041f847c5c43be6b573d47..39f4eef657bd0d06d42c7dd7c6cbbb222a97c856 100644 (file)
@@ -506,9 +506,9 @@ public class ControllerContext implements SchemaContextListener {
         DataSchemaNode ret = container.getDataChildByName(name);
         if (ret == null) {
             for (final DataSchemaNode node : container.getChildNodes()) {
-                if ((node instanceof ChoiceCaseNode)) {
-                    final ChoiceCaseNode caseNode = ((ChoiceCaseNode) node);
-                    DataSchemaNode childByQName = ControllerContext.childByQName(caseNode, name);
+                if ((node instanceof ChoiceNode)) {
+                    final ChoiceNode choiceNode = ((ChoiceNode) node);
+                    DataSchemaNode childByQName = ControllerContext.childByQName(choiceNode, name);
                     if (childByQName != null) {
                         return childByQName;
                     }
index b911369cf049d1dd07869aaa8accd257d0d56c9f..17565a6b8c082d314f5b4e90715be18ca3536a8c 100644 (file)
@@ -91,7 +91,7 @@ public class Notificator {
             result = result.substring(1);
         }
         if (result.endsWith("/")) {
-            result = result.substring(0, result.length());
+            result = result.substring(0, result.length()-1);
         }
         return result;
     }
index c601647a2eb93e63afafeb2123318e277de2a957..ae7d3234808bdd00059fce9403419eb923f8a8fd 100644 (file)
@@ -15,6 +15,7 @@
     <module>toaster</module>
     <module>toaster-consumer</module>
     <module>toaster-provider</module>
+    <module>toaster-config</module>
     <module>l2switch</module>
   </modules>
   <scm>
diff --git a/opendaylight/md-sal/samples/toaster-config/pom.xml b/opendaylight/md-sal/samples/toaster-config/pom.xml
new file mode 100644 (file)
index 0000000..b30c4ba
--- /dev/null
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+  <modelVersion>4.0.0</modelVersion>
+  <parent>
+    <groupId>org.opendaylight.controller.samples</groupId>
+    <artifactId>sal-samples</artifactId>
+    <version>1.1-SNAPSHOT</version>
+  </parent>
+  <artifactId>toaster-config</artifactId>
+  <description>Configuration files for toaster</description>
+  <packaging>jar</packaging>
+  <build>
+    <plugins>
+        <plugin>
+        <groupId>org.codehaus.mojo</groupId>
+        <artifactId>build-helper-maven-plugin</artifactId>
+        <executions>
+          <execution>
+            <id>attach-artifacts</id>
+            <goals>
+              <goal>attach-artifact</goal>
+            </goals>
+            <phase>package</phase>
+            <configuration>
+              <artifacts>
+                <artifact>
+                  <file>${project.build.directory}/classes/initial/03-toaster-sample.xml</file>
+                  <type>xml</type>
+                  <classifier>config</classifier>
+                </artifact>
+              </artifacts>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+    </plugins>
+  </build>
+</project>
similarity index 99%
rename from opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/03-toaster-sample.xml
rename to opendaylight/md-sal/samples/toaster-config/src/main/resources/initial/03-toaster-sample.xml
index 3958e185605e155f8b4b092e927ff5e8a679cbd1..2e8c7d5ce6ee3f2093f6bc0340bda56e634d2d63 100644 (file)
@@ -26,7 +26,7 @@
                         <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">binding:binding-async-data-broker</type>
                         <name>binding-data-broker</name>
                     </data-broker>
-                    
+
                     <notification-service>
                         <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">
                             binding:binding-notification-service
@@ -54,7 +54,7 @@
                     </notification-service>
                 </module>
             </modules>
-            
+
             <services xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
                 <service>
                     <type xmlns:kitchen="urn:opendaylight:params:xml:ns:yang:controller:config:kitchen-service:impl">
diff --git a/opendaylight/netconf/netconf-config/pom.xml b/opendaylight/netconf/netconf-config/pom.xml
new file mode 100644 (file)
index 0000000..db5d14d
--- /dev/null
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+  <modelVersion>4.0.0</modelVersion>
+  <parent>
+    <groupId>org.opendaylight.controller</groupId>
+    <artifactId>netconf-subsystem</artifactId>
+    <version>0.2.5-SNAPSHOT</version>
+  </parent>
+  <artifactId>netconf-config</artifactId>
+  <description>Configuration files for netconf</description>
+  <packaging>jar</packaging>
+  <build>
+    <plugins>
+        <plugin>
+        <groupId>org.codehaus.mojo</groupId>
+        <artifactId>build-helper-maven-plugin</artifactId>
+        <executions>
+          <execution>
+            <id>attach-artifacts</id>
+            <goals>
+              <goal>attach-artifact</goal>
+            </goals>
+            <phase>package</phase>
+            <configuration>
+              <artifacts>
+                <artifact>
+                  <file>${project.build.directory}/classes/initial/01-netconf.xml</file>
+                  <type>xml</type>
+                  <classifier>config</classifier>
+                </artifact>
+              </artifacts>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+    </plugins>
+  </build>
+</project>
diff --git a/opendaylight/netconf/netconf-connector-config/pom.xml b/opendaylight/netconf/netconf-connector-config/pom.xml
new file mode 100644 (file)
index 0000000..d9cc5ea
--- /dev/null
@@ -0,0 +1,46 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ 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
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+  <modelVersion>4.0.0</modelVersion>
+  <parent>
+    <groupId>org.opendaylight.controller</groupId>
+    <artifactId>netconf-subsystem</artifactId>
+    <version>0.2.5-SNAPSHOT</version>
+  </parent>
+  <artifactId>netconf-connector-config</artifactId>
+  <description>Configuration files for netconf-connector</description>
+  <packaging>jar</packaging>
+  <build>
+    <plugins>
+        <plugin>
+        <groupId>org.codehaus.mojo</groupId>
+        <artifactId>build-helper-maven-plugin</artifactId>
+        <executions>
+          <execution>
+            <id>attach-artifacts</id>
+            <goals>
+              <goal>attach-artifact</goal>
+            </goals>
+            <phase>package</phase>
+            <configuration>
+              <artifacts>
+                <artifact>
+                  <file>${project.build.directory}/classes/initial/99-netconf-connector.xml</file>
+                  <type>xml</type>
+                  <classifier>config</classifier>
+                </artifact>
+              </artifacts>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+    </plugins>
+  </build>
+</project>
index 937949a17e5827bbe74d22eb5071904b3a71906d..c72705d50ebd8f505feaac092331fcbafc1ee41b 100644 (file)
@@ -20,6 +20,7 @@
   <modules>
     <module>netconf-api</module>
     <module>netconf-cli</module>
+    <module>netconf-config</module>
     <module>netconf-impl</module>
     <module>config-netconf-connector</module>
     <module>netconf-util</module>
@@ -32,6 +33,7 @@
     <module>netconf-monitoring</module>
     <module>ietf-netconf-monitoring</module>
     <module>ietf-netconf-monitoring-extension</module>
+    <module>netconf-connector-config</module>
   </modules>
 
   <dependencies>
index 1e2cd47c9c2d923ac09f3cbc50fc60b9c2a519f0..45070ca8b01e64331381f67f28b367e2f80bc483 100644 (file)
@@ -8,23 +8,26 @@
 
 package org.opendaylight.controller.networkconfig.neutron.implementation;
 
-import java.util.Hashtable;
-import java.util.Dictionary;
-
 import org.apache.felix.dm.Component;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 import org.opendaylight.controller.clustering.services.IClusterContainerServices;
 import org.opendaylight.controller.configuration.IConfigurationContainerAware;
 import org.opendaylight.controller.configuration.IConfigurationContainerService;
+import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallCRUD;
+import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallPolicyCRUD;
+import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallRuleCRUD;
 import org.opendaylight.controller.networkconfig.neutron.INeutronFloatingIPCRUD;
 import org.opendaylight.controller.networkconfig.neutron.INeutronNetworkCRUD;
 import org.opendaylight.controller.networkconfig.neutron.INeutronPortCRUD;
 import org.opendaylight.controller.networkconfig.neutron.INeutronRouterCRUD;
-import org.opendaylight.controller.networkconfig.neutron.INeutronSubnetCRUD;
 import org.opendaylight.controller.networkconfig.neutron.INeutronSecurityGroupCRUD;
 import org.opendaylight.controller.networkconfig.neutron.INeutronSecurityRuleCRUD;
+import org.opendaylight.controller.networkconfig.neutron.INeutronSubnetCRUD;
 import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Dictionary;
+import java.util.Hashtable;
 
 public class Activator extends ComponentActivatorAbstractBase {
     protected static final Logger logger = LoggerFactory
@@ -68,7 +71,10 @@ public class Activator extends ComponentActivatorAbstractBase {
                 NeutronSubnetInterface.class,
                 NeutronNetworkInterface.class,
                 NeutronSecurityGroupInterface.class,
-                NeutronSecurityRuleInterface.class};
+                NeutronSecurityRuleInterface.class,
+                NeutronFirewallInterface.class,
+                NeutronFirewallPolicyInterface.class,
+                NeutronFirewallRuleInterface.class};
         return res;
     }
 
@@ -199,5 +205,53 @@ public class Activator extends ComponentActivatorAbstractBase {
                 "setConfigurationContainerService",
                 "unsetConfigurationContainerService").setRequired(true));
         }
+        if (imp.equals(NeutronFirewallInterface.class)) {
+            // export the service
+            c.setInterface(
+                    new String[] { INeutronFirewallCRUD.class.getName(),
+                            IConfigurationContainerAware.class.getName()}, null);
+            Dictionary<String, String> props = new Hashtable<String, String>();
+            props.put("salListenerName", "neutron");
+            c.add(createContainerServiceDependency(containerName)
+                    .setService(IClusterContainerServices.class)
+                    .setCallbacks("setClusterContainerService",
+                            "unsetClusterContainerService").setRequired(true));
+            c.add(createContainerServiceDependency(containerName).setService(
+                    IConfigurationContainerService.class).setCallbacks(
+                    "setConfigurationContainerService",
+                    "unsetConfigurationContainerService").setRequired(true));
+        }
+        if (imp.equals(NeutronFirewallPolicyInterface.class)) {
+            // export the service
+            c.setInterface(
+                    new String[] { INeutronFirewallPolicyCRUD.class.getName(),
+                            IConfigurationContainerAware.class.getName()}, null);
+            Dictionary<String, String> props = new Hashtable<String, String>();
+            props.put("salListenerName", "neutron");
+            c.add(createContainerServiceDependency(containerName)
+                    .setService(IClusterContainerServices.class)
+                    .setCallbacks("setClusterContainerService",
+                            "unsetClusterContainerService").setRequired(true));
+            c.add(createContainerServiceDependency(containerName).setService(
+                    IConfigurationContainerService.class).setCallbacks(
+                    "setConfigurationContainerService",
+                    "unsetConfigurationContainerService").setRequired(true));
+        }
+        if (imp.equals(NeutronFirewallRuleInterface.class)) {
+            // export the service
+            c.setInterface(
+                    new String[] { INeutronFirewallRuleCRUD.class.getName(),
+                            IConfigurationContainerAware.class.getName()}, null);
+            Dictionary<String, String> props = new Hashtable<String, String>();
+            props.put("salListenerName", "neutron");
+            c.add(createContainerServiceDependency(containerName)
+                    .setService(IClusterContainerServices.class)
+                    .setCallbacks("setClusterContainerService",
+                            "unsetClusterContainerService").setRequired(true));
+            c.add(createContainerServiceDependency(containerName).setService(
+                    IConfigurationContainerService.class).setCallbacks(
+                    "setConfigurationContainerService",
+                    "unsetConfigurationContainerService").setRequired(true));
+        }
     }
 }
diff --git a/opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/NeutronFirewallInterface.java b/opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/NeutronFirewallInterface.java
new file mode 100644 (file)
index 0000000..60476a1
--- /dev/null
@@ -0,0 +1,264 @@
+/*
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * 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.networkconfig.neutron.implementation;
+
+import org.apache.felix.dm.Component;
+import org.opendaylight.controller.clustering.services.CacheConfigException;
+import org.opendaylight.controller.clustering.services.CacheExistException;
+import org.opendaylight.controller.clustering.services.IClusterContainerServices;
+import org.opendaylight.controller.clustering.services.IClusterServices;
+import org.opendaylight.controller.configuration.ConfigurationObject;
+import org.opendaylight.controller.configuration.IConfigurationContainerAware;
+import org.opendaylight.controller.configuration.IConfigurationContainerService;
+import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallCRUD;
+import org.opendaylight.controller.networkconfig.neutron.NeutronFirewall;
+import org.opendaylight.controller.sal.utils.IObjectReader;
+import org.opendaylight.controller.sal.utils.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Dictionary;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.concurrent.ConcurrentMap;
+
+public class NeutronFirewallInterface implements INeutronFirewallCRUD, IConfigurationContainerAware, IObjectReader {
+    private static final Logger logger = LoggerFactory.getLogger(NeutronFirewallInterface.class);
+    private static final String FILE_NAME = "neutron.firewall.conf";
+    private String containerName = null;
+
+    private IClusterContainerServices clusterContainerService = null;
+    private IConfigurationContainerService configurationService;
+    private ConcurrentMap<String, NeutronFirewall> firewallDB;
+
+    // methods needed for creating caches
+    void setClusterContainerService(IClusterContainerServices s) {
+        logger.debug("Cluster Service set");
+        clusterContainerService = s;
+    }
+
+    void unsetClusterContainerService(IClusterContainerServices s) {
+        if (clusterContainerService == s) {
+            logger.debug("Cluster Service removed!");
+            clusterContainerService = null;
+        }
+    }
+
+    public void setConfigurationContainerService(IConfigurationContainerService service) {
+        logger.trace("Configuration service set: {}", service);
+        configurationService = service;
+    }
+
+    public void unsetConfigurationContainerService(IConfigurationContainerService service) {
+        logger.trace("Configuration service removed: {}", service);
+        configurationService = null;
+    }
+
+    private void allocateCache() {
+        if (this.clusterContainerService == null) {
+            logger.error("un-initialized clusterContainerService, can't create cache");
+            return;
+        }
+        logger.debug("Creating Cache for Neutron Firewall");
+        try {
+            // neutron caches
+            this.clusterContainerService.createCache("neutronFirewalls",
+                    EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
+        } catch (CacheConfigException cce) {
+            logger.error("Cache couldn't be created for Neutron Firewall -  check cache mode");
+        } catch (CacheExistException cce) {
+            logger.error("Cache for Neutron Firewall already exists, destroy and recreate");
+        }
+        logger.debug("Cache successfully created for Neutron Firewall");
+    }
+
+    @SuppressWarnings ({"unchecked"})
+    private void retrieveCache() {
+        if (clusterContainerService == null) {
+            logger.error("un-initialized clusterContainerService, can't retrieve cache");
+            return;
+        }
+
+        logger.debug("Retrieving cache for Neutron Firewall");
+        firewallDB = (ConcurrentMap<String, NeutronFirewall>) clusterContainerService
+                .getCache("neutronFirewalls");
+        if (firewallDB == null) {
+            logger.error("Cache couldn't be retrieved for Neutron Firewall");
+        }
+        logger.debug("Cache was successfully retrieved for Neutron Firewall");
+    }
+
+    private void destroyCache() {
+        if (clusterContainerService == null) {
+            logger.error("un-initialized clusterMger, can't destroy cache");
+            return;
+        }
+        logger.debug("Destroying Cache for HostTracker");
+        clusterContainerService.destroyCache("neutronFirewalls");
+    }
+
+    private void startUp() {
+        allocateCache();
+        retrieveCache();
+        loadConfiguration();
+    }
+
+    /**
+     * Function called by the dependency manager when all the required
+     * dependencies are satisfied
+     */
+    void init(Component c) {
+        Dictionary<?, ?> props = c.getServiceProperties();
+        if (props != null) {
+            this.containerName = (String) props.get("containerName");
+            logger.debug("Running containerName: {}", this.containerName);
+        } else {
+            // In the Global instance case the containerName is empty
+            this.containerName = "";
+        }
+        startUp();
+    }
+
+    /**
+     * Function called by the dependency manager when at least one dependency
+     * become unsatisfied or when the component is shutting down because for
+     * example bundle is being stopped.
+     */
+    void destroy() {
+        destroyCache();
+    }
+
+    /**
+     * Function called by dependency manager after "init ()" is called and after
+     * the services provided by the class are registered in the service registry
+     */
+    void start() {
+    }
+
+    /**
+     * Function called by the dependency manager before the services exported by
+     * the component are unregistered, this will be followed by a "destroy ()"
+     * calls
+     */
+    void stop() {
+    }
+
+    // this method uses reflection to update an object from it's delta.
+
+    private boolean overwrite(Object target, Object delta) {
+        Method[] methods = target.getClass().getMethods();
+
+        for (Method toMethod : methods) {
+            if (toMethod.getDeclaringClass().equals(target.getClass())
+                    && toMethod.getName().startsWith("set")) {
+
+                String toName = toMethod.getName();
+                String fromName = toName.replace("set", "get");
+
+                try {
+                    Method fromMethod = delta.getClass().getMethod(fromName);
+                    Object value = fromMethod.invoke(delta, (Object[]) null);
+                    if (value != null) {
+                        toMethod.invoke(target, value);
+                    }
+                } catch (Exception e) {
+                    e.printStackTrace();
+                    return false;
+                }
+            }
+        }
+        return true;
+    }
+
+    @Override
+    public boolean neutronFirewallExists(String uuid) {
+        return firewallDB.containsKey(uuid);
+    }
+
+    @Override
+    public NeutronFirewall getNeutronFirewall(String uuid) {
+        if (!neutronFirewallExists(uuid)) {
+            logger.debug("No Firewall Have Been Defined");
+            return null;
+        }
+        return firewallDB.get(uuid);
+    }
+
+    @Override
+    public List<NeutronFirewall> getAllNeutronFirewalls() {
+        Set<NeutronFirewall> allFirewalls = new HashSet<NeutronFirewall>();
+        for (Entry<String, NeutronFirewall> entry : firewallDB.entrySet()) {
+            NeutronFirewall firewall = entry.getValue();
+            allFirewalls.add(firewall);
+        }
+        logger.debug("Exiting getFirewalls, Found {} OpenStackFirewall", allFirewalls.size());
+        List<NeutronFirewall> ans = new ArrayList<NeutronFirewall>();
+        ans.addAll(allFirewalls);
+        return ans;
+    }
+
+    @Override
+    public boolean addNeutronFirewall(NeutronFirewall input) {
+        if (neutronFirewallExists(input.getFirewallUUID())) {
+            return false;
+        }
+        firewallDB.putIfAbsent(input.getFirewallUUID(), input);
+        return true;
+    }
+
+    @Override
+    public boolean removeNeutronFirewall(String uuid) {
+        if (!neutronFirewallExists(uuid)) {
+            return false;
+        }
+        firewallDB.remove(uuid);
+        return true;
+    }
+
+    @Override
+    public boolean updateNeutronFirewall(String uuid, NeutronFirewall delta) {
+        if (!neutronFirewallExists(uuid)) {
+            return false;
+        }
+        NeutronFirewall target = firewallDB.get(uuid);
+        return overwrite(target, delta);
+    }
+
+    @Override
+    public boolean neutronFirewallInUse(String firewallUUID) {
+        return !neutronFirewallExists(firewallUUID);
+    }
+
+    private void loadConfiguration() {
+        for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, FILE_NAME)) {
+            NeutronFirewall nn = (NeutronFirewall) conf;
+            firewallDB.put(nn.getFirewallUUID(), nn);
+        }
+    }
+
+    @Override
+    public Status saveConfiguration() {
+        return configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(firewallDB.values()),
+                FILE_NAME);
+    }
+
+    @Override
+    public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
+        return ois.readObject();
+    }
+
+}
\ No newline at end of file
diff --git a/opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/NeutronFirewallPolicyInterface.java b/opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/NeutronFirewallPolicyInterface.java
new file mode 100644 (file)
index 0000000..8459262
--- /dev/null
@@ -0,0 +1,268 @@
+/*
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * 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.networkconfig.neutron.implementation;
+
+import org.apache.felix.dm.Component;
+import org.opendaylight.controller.clustering.services.CacheConfigException;
+import org.opendaylight.controller.clustering.services.CacheExistException;
+import org.opendaylight.controller.clustering.services.IClusterContainerServices;
+import org.opendaylight.controller.clustering.services.IClusterServices;
+import org.opendaylight.controller.configuration.ConfigurationObject;
+import org.opendaylight.controller.configuration.IConfigurationContainerAware;
+import org.opendaylight.controller.configuration.IConfigurationContainerService;
+import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallPolicyCRUD;
+import org.opendaylight.controller.networkconfig.neutron.NeutronFirewallPolicy;
+import org.opendaylight.controller.sal.utils.IObjectReader;
+import org.opendaylight.controller.sal.utils.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Dictionary;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.concurrent.ConcurrentMap;
+
+public class NeutronFirewallPolicyInterface implements INeutronFirewallPolicyCRUD, IConfigurationContainerAware, IObjectReader {
+    private static final Logger logger = LoggerFactory.getLogger(NeutronFirewallPolicyInterface.class);
+    private static final String FILE_NAME ="neutron.firewallpolicy.conf";
+    private String containerName = null;
+
+    private IClusterContainerServices clusterContainerService = null;
+    private IConfigurationContainerService configurationService;
+    private ConcurrentMap<String, NeutronFirewallPolicy> firewallPolicyDB;
+
+    // methods needed for creating caches
+    void setClusterContainerService(IClusterContainerServices s) {
+        logger.debug("Cluster Service set");
+        clusterContainerService = s;
+    }
+
+    void unsetClusterContainerService(IClusterContainerServices s) {
+        if (clusterContainerService == s) {
+            logger.debug("Cluster Service removed!");
+            clusterContainerService = null;
+        }
+    }
+
+    public void setConfigurationContainerService(IConfigurationContainerService service) {
+        logger.trace("Configuration service set: {}", service);
+        configurationService = service;
+    }
+
+    public void unsetConfigurationContainerService(IConfigurationContainerService service) {
+        logger.trace("Configuration service removed: {}", service);
+        configurationService = null;
+    }
+
+    private void allocateCache() {
+        if (this.clusterContainerService == null) {
+            logger.error("un-initialized clusterContainerService, can't create cache");
+            return;
+        }
+        logger.debug("Creating Cache for Neutron Firewall Rule");
+        try {
+            // neutron caches
+            this.clusterContainerService.createCache("neutronFirewallPolicies",
+                    EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
+        } catch (CacheConfigException cce) {
+            logger.error("Cache couldn't be created for Neutron Firewall Rule -  check cache mode");
+        } catch (CacheExistException cce) {
+            logger.error("Cache for Neutron Firewall Rule already exists, destroy and recreate");
+        }
+        logger.debug("Cache successfully created for Neutron Firewall Rule");
+    }
+
+    @SuppressWarnings({ "unchecked" })
+    private void retrieveCache() {
+        if (clusterContainerService == null) {
+            logger.error("un-initialized clusterContainerService, can't retrieve cache");
+            return;
+        }
+
+        logger.debug("Retrieving cache for Neutron Firewall Rule");
+        firewallPolicyDB = (ConcurrentMap<String, NeutronFirewallPolicy>) clusterContainerService
+                .getCache("neutronFirewallPolicies");
+        if (firewallPolicyDB == null) {
+            logger.error("Cache couldn't be retrieved for Neutron Firewall Rule");
+        }
+        logger.debug("Cache was successfully retrieved for Neutron Firewall Rule");
+    }
+
+    private void destroyCache() {
+        if (clusterContainerService == null) {
+            logger.error("un-initialized clusterMger, can't destroy cache");
+            return;
+        }
+        logger.debug("Destroying Cache for HostTracker");
+        clusterContainerService.destroyCache("neutronFirewallPolicies");
+    }
+
+    private void startUp() {
+        allocateCache();
+        retrieveCache();
+        loadConfiguration();
+    }
+
+    /**
+     * Function called by the dependency manager when all the required
+     * dependencies are satisfied
+     *
+     */
+    void init(Component c) {
+        Dictionary<?, ?> props = c.getServiceProperties();
+        if (props != null) {
+            this.containerName = (String) props.get("containerName");
+            logger.debug("Running containerName: {}", this.containerName);
+        } else {
+            // In the Global instance case the containerName is empty
+            this.containerName = "";
+        }
+        startUp();
+    }
+
+    /**
+     * Function called by the dependency manager when at least one dependency
+     * become unsatisfied or when the component is shutting down because for
+     * example bundle is being stopped.
+     *
+     */
+    void destroy() {
+        destroyCache();
+    }
+
+    /**
+     * Function called by dependency manager after "init ()" is called and after
+     * the services provided by the class are registered in the service registry
+     *
+     */
+    void start() {
+    }
+
+    /**
+     * Function called by the dependency manager before the services exported by
+     * the component are unregistered, this will be followed by a "destroy ()"
+     * calls
+     *
+     */
+    void stop() {
+    }
+
+    // this method uses reflection to update an object from it's delta.
+
+    private boolean overwrite(Object target, Object delta) {
+        Method[] methods = target.getClass().getMethods();
+
+        for(Method toMethod: methods){
+            if(toMethod.getDeclaringClass().equals(target.getClass())
+                    && toMethod.getName().startsWith("set")){
+
+                String toName = toMethod.getName();
+                String fromName = toName.replace("set", "get");
+
+                try {
+                    Method fromMethod = delta.getClass().getMethod(fromName);
+                    Object value = fromMethod.invoke(delta, (Object[])null);
+                    if(value != null){
+                        toMethod.invoke(target, value);
+                    }
+                } catch (Exception e) {
+                    e.printStackTrace();
+                    return false;
+                }
+            }
+        }
+        return true;
+    }
+
+    @Override
+    public boolean neutronFirewallPolicyExists(String uuid) {
+        return firewallPolicyDB.containsKey(uuid);
+    }
+
+    @Override
+    public NeutronFirewallPolicy getNeutronFirewallPolicy(String uuid) {
+        if (!neutronFirewallPolicyExists(uuid)) {
+            logger.debug("No Firewall Rule Have Been Defined");
+            return null;
+        }
+        return firewallPolicyDB.get(uuid);
+    }
+
+    @Override
+    public List<NeutronFirewallPolicy> getAllNeutronFirewallPolicies() {
+        Set<NeutronFirewallPolicy> allFirewallPolicies = new HashSet<NeutronFirewallPolicy>();
+        for (Entry<String, NeutronFirewallPolicy> entry : firewallPolicyDB.entrySet()) {
+            NeutronFirewallPolicy firewallPolicy = entry.getValue();
+            allFirewallPolicies.add(firewallPolicy);
+        }
+        logger.debug("Exiting getFirewallPolicies, Found {} OpenStackFirewallPolicy", allFirewallPolicies.size());
+        List<NeutronFirewallPolicy> ans = new ArrayList<NeutronFirewallPolicy>();
+        ans.addAll(allFirewallPolicies);
+        return ans;
+    }
+
+    @Override
+    public boolean addNeutronFirewallPolicy(NeutronFirewallPolicy input) {
+        if (neutronFirewallPolicyExists(input.getFirewallPolicyUUID())) {
+            return false;
+        }
+        firewallPolicyDB.putIfAbsent(input.getFirewallPolicyUUID(), input);
+        return true;
+    }
+
+    @Override
+    public boolean removeNeutronFirewallPolicy(String uuid) {
+        if (!neutronFirewallPolicyExists(uuid)) {
+            return false;
+        }
+        firewallPolicyDB.remove(uuid);
+        return true;
+    }
+
+    @Override
+    public boolean updateNeutronFirewallPolicy(String uuid, NeutronFirewallPolicy delta) {
+        if (!neutronFirewallPolicyExists(uuid)) {
+            return false;
+        }
+        NeutronFirewallPolicy target = firewallPolicyDB.get(uuid);
+        return overwrite(target, delta);
+    }
+
+    @Override
+    public boolean neutronFirewallPolicyInUse(String firewallPolicyUUID) {
+        return !neutronFirewallPolicyExists(firewallPolicyUUID);
+    }
+
+    private void loadConfiguration() {
+        for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, FILE_NAME)) {
+            NeutronFirewallPolicy nn = (NeutronFirewallPolicy) conf;
+            firewallPolicyDB.put(nn.getFirewallPolicyUUID(), nn);
+        }
+    }
+
+    @Override
+    public Status saveConfiguration() {
+        return configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(firewallPolicyDB.values()),
+                FILE_NAME);
+    }
+
+    @Override
+    public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
+        return ois.readObject();
+    }
+
+}
\ No newline at end of file
diff --git a/opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/NeutronFirewallRuleInterface.java b/opendaylight/networkconfiguration/neutron/implementation/src/main/java/org/opendaylight/controller/networkconfig/neutron/implementation/NeutronFirewallRuleInterface.java
new file mode 100644 (file)
index 0000000..ba84500
--- /dev/null
@@ -0,0 +1,267 @@
+/*
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * 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.networkconfig.neutron.implementation;
+
+import org.apache.felix.dm.Component;
+import org.opendaylight.controller.clustering.services.CacheConfigException;
+import org.opendaylight.controller.clustering.services.CacheExistException;
+import org.opendaylight.controller.clustering.services.IClusterContainerServices;
+import org.opendaylight.controller.clustering.services.IClusterServices;
+import org.opendaylight.controller.configuration.ConfigurationObject;
+import org.opendaylight.controller.configuration.IConfigurationContainerAware;
+import org.opendaylight.controller.configuration.IConfigurationContainerService;
+import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallRuleCRUD;
+import org.opendaylight.controller.networkconfig.neutron.NeutronFirewallRule;
+import org.opendaylight.controller.sal.utils.IObjectReader;
+import org.opendaylight.controller.sal.utils.Status;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Dictionary;
+import java.util.EnumSet;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.concurrent.ConcurrentMap;
+
+public class NeutronFirewallRuleInterface implements INeutronFirewallRuleCRUD, IConfigurationContainerAware, IObjectReader {
+    private static final Logger logger = LoggerFactory.getLogger(NeutronFirewallRuleInterface.class);
+    private static final String FILE_NAME ="neutron.firewallrules.conf";
+    private String containerName = null;
+
+    private IClusterContainerServices clusterContainerService = null;
+    private IConfigurationContainerService configurationService;
+    private ConcurrentMap<String, NeutronFirewallRule> firewallRuleDB;
+
+    // methods needed for creating caches
+    void setClusterContainerService(IClusterContainerServices s) {
+        logger.debug("Cluster Service set");
+        clusterContainerService = s;
+    }
+
+    void unsetClusterContainerService(IClusterContainerServices s) {
+        if (clusterContainerService == s) {
+            logger.debug("Cluster Service removed!");
+            clusterContainerService = null;
+        }
+    }
+
+    public void setConfigurationContainerService(IConfigurationContainerService service) {
+        logger.trace("Configuration service set: {}", service);
+        configurationService = service;
+    }
+
+    public void unsetConfigurationContainerService(IConfigurationContainerService service) {
+        logger.trace("Configuration service removed: {}", service);
+        configurationService = null;
+    }
+
+    private void allocateCache() {
+        if (this.clusterContainerService == null) {
+            logger.error("un-initialized clusterContainerService, can't create cache");
+            return;
+        }
+        logger.debug("Creating Cache for Neutron Firewall Rule");
+        try {
+            // neutron caches
+            this.clusterContainerService.createCache("neutronFirewallRules",
+                    EnumSet.of(IClusterServices.cacheMode.NON_TRANSACTIONAL));
+        } catch (CacheConfigException cce) {
+            logger.error("Cache couldn't be created for Neutron Firewall Rule -  check cache mode");
+        } catch (CacheExistException cce) {
+            logger.error("Cache for Neutron Firewall Rule already exists, destroy and recreate");
+        }
+        logger.debug("Cache successfully created for Neutron Firewall Rule");
+    }
+
+    @SuppressWarnings({ "unchecked" })
+    private void retrieveCache() {
+        if (clusterContainerService == null) {
+            logger.error("un-initialized clusterContainerService, can't retrieve cache");
+            return;
+        }
+
+        logger.debug("Retrieving cache for Neutron Firewall Rule");
+        firewallRuleDB = (ConcurrentMap<String, NeutronFirewallRule>) clusterContainerService
+                .getCache("neutronFirewallRules");
+        if (firewallRuleDB == null) {
+            logger.error("Cache couldn't be retrieved for Neutron Firewall Rule");
+        }
+        logger.debug("Cache was successfully retrieved for Neutron Firewall Rule");
+    }
+
+    private void destroyCache() {
+        if (clusterContainerService == null) {
+            logger.error("un-initialized clusterMger, can't destroy cache");
+            return;
+        }
+        logger.debug("Destroying Cache for HostTracker");
+        clusterContainerService.destroyCache("neutronFirewallRules");
+    }
+
+    private void startUp() {
+        allocateCache();
+        retrieveCache();
+        loadConfiguration();
+    }
+
+    /**
+     * Function called by the dependency manager when all the required
+     * dependencies are satisfied
+     *
+     */
+    void init(Component c) {
+        Dictionary<?, ?> props = c.getServiceProperties();
+        if (props != null) {
+            this.containerName = (String) props.get("containerName");
+            logger.debug("Running containerName: {}", this.containerName);
+        } else {
+            // In the Global instance case the containerName is empty
+            this.containerName = "";
+        }
+        startUp();
+    }
+
+    /**
+     * Function called by the dependency manager when at least one dependency
+     * become unsatisfied or when the component is shutting down because for
+     * example bundle is being stopped.
+     *
+     */
+    void destroy() {
+        destroyCache();
+    }
+
+    /**
+     * Function called by dependency manager after "init ()" is called and after
+     * the services provided by the class are registered in the service registry
+     *
+     */
+    void start() {
+    }
+
+    /**
+     * Function called by the dependency manager before the services exported by
+     * the component are unregistered, this will be followed by a "destroy ()"
+     * calls
+     *
+     */
+    void stop() {
+    }
+
+    // this method uses reflection to update an object from it's delta.
+
+    private boolean overwrite(Object target, Object delta) {
+        Method[] methods = target.getClass().getMethods();
+
+        for(Method toMethod: methods){
+            if(toMethod.getDeclaringClass().equals(target.getClass())
+                    && toMethod.getName().startsWith("set")){
+
+                String toName = toMethod.getName();
+                String fromName = toName.replace("set", "get");
+
+                try {
+                    Method fromMethod = delta.getClass().getMethod(fromName);
+                    Object value = fromMethod.invoke(delta, (Object[])null);
+                    if(value != null){
+                        toMethod.invoke(target, value);
+                    }
+                } catch (Exception e) {
+                    e.printStackTrace();
+                    return false;
+                }
+            }
+        }
+        return true;
+    }
+
+    @Override
+    public boolean neutronFirewallRuleExists(String uuid) {
+        return firewallRuleDB.containsKey(uuid);
+    }
+
+    @Override
+    public NeutronFirewallRule getNeutronFirewallRule(String uuid) {
+        if (!neutronFirewallRuleExists(uuid)) {
+            logger.debug("No Firewall Rule Have Been Defined");
+            return null;
+        }
+        return firewallRuleDB.get(uuid);
+    }
+
+    @Override
+    public List<NeutronFirewallRule> getAllNeutronFirewallRules() {
+        Set<NeutronFirewallRule> allFirewallRules = new HashSet<NeutronFirewallRule>();
+        for (Entry<String, NeutronFirewallRule> entry : firewallRuleDB.entrySet()) {
+            NeutronFirewallRule firewallRule = entry.getValue();
+            allFirewallRules.add(firewallRule);
+        }
+        logger.debug("Exiting getFirewallRules, Found {} OpenStackFirewallRule", allFirewallRules.size());
+        List<NeutronFirewallRule> ans = new ArrayList<NeutronFirewallRule>();
+        ans.addAll(allFirewallRules);
+        return ans;
+    }
+
+    @Override
+    public boolean addNeutronFirewallRule(NeutronFirewallRule input) {
+        if (neutronFirewallRuleExists(input.getFirewallRuleUUID())) {
+            return false;
+        }
+        firewallRuleDB.putIfAbsent(input.getFirewallRuleUUID(), input);
+        return true;
+    }
+
+    @Override
+    public boolean removeNeutronFirewallRule(String uuid) {
+        if (!neutronFirewallRuleExists(uuid)) {
+            return false;
+        }
+        firewallRuleDB.remove(uuid);
+        return true;
+    }
+
+    @Override
+    public boolean updateNeutronFirewallRule(String uuid, NeutronFirewallRule delta) {
+        if (!neutronFirewallRuleExists(uuid)) {
+            return false;
+        }
+        NeutronFirewallRule target = firewallRuleDB.get(uuid);
+        return overwrite(target, delta);
+    }
+
+    @Override
+    public boolean neutronFirewallRuleInUse(String firewallRuleUUID) {
+        return !neutronFirewallRuleExists(firewallRuleUUID);
+    }
+
+    private void loadConfiguration() {
+        for (ConfigurationObject conf : configurationService.retrieveConfiguration(this, FILE_NAME)) {
+            NeutronFirewallRule nn = (NeutronFirewallRule) conf;
+            firewallRuleDB.put(nn.getFirewallRuleUUID(), nn);
+        }
+    }
+
+    @Override
+    public Status saveConfiguration() {
+        return configurationService.persistConfiguration(new ArrayList<ConfigurationObject>(firewallRuleDB.values()),
+                FILE_NAME);
+    }
+
+    @Override
+    public Object readObject(ObjectInputStream ois) throws FileNotFoundException, IOException, ClassNotFoundException {
+        return ois.readObject();
+    }
+
+}
\ No newline at end of file
diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallAware.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallAware.java
new file mode 100644 (file)
index 0000000..9b4f579
--- /dev/null
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * 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.networkconfig.neutron;
+
+/**
+ * This interface defines the methods a service that wishes to be aware of Firewall Rules needs to implement
+ *
+ */
+
+public interface INeutronFirewallAware {
+
+    /**
+     * Services provide this interface method to indicate if the specified firewall can be created
+     *
+     * @param firewall
+     *            instance of proposed new Firewall object
+     * @return integer
+     *            the return value is understood to be a HTTP status code.  A return value outside of 200 through 299
+     *            results in the create operation being interrupted and the returned status value reflected in the
+     *            HTTP response.
+     */
+    public int canCreateNeutronFirewall(NeutronFirewall firewall);
+
+    /**
+     * Services provide this interface method for taking action after a firewall has been created
+     *
+     * @param firewall
+     *            instance of new Firewall object
+     * @return void
+     */
+    public void neutronFirewallCreated(NeutronFirewall firewall);
+
+    /**
+     * Services provide this interface method to indicate if the specified firewall can be changed using the specified
+     * delta
+     *
+     * @param delta
+     *            updates to the firewall object using patch semantics
+     * @param original
+     *            instance of the Firewall object to be updated
+     * @return integer
+     *            the return value is understood to be a HTTP status code.  A return value outside of 200 through 299
+     *            results in the update operation being interrupted and the returned status value reflected in the
+     *            HTTP response.
+     */
+    public int canUpdateNeutronFirewall(NeutronFirewall delta, NeutronFirewall original);
+
+    /**
+     * Services provide this interface method for taking action after a firewall has been updated
+     *
+     * @param firewall
+     *            instance of modified Firewall object
+     * @return void
+     */
+    public void neutronFirewallUpdated(NeutronFirewall firewall);
+
+    /**
+     * Services provide this interface method to indicate if the specified firewall can be deleted
+     *
+     * @param firewall
+     *            instance of the Firewall object to be deleted
+     * @return integer
+     *            the return value is understood to be a HTTP status code.  A return value outside of 200 through 299
+     *            results in the delete operation being interrupted and the returned status value reflected in the
+     *            HTTP response.
+     */
+    public int canDeleteNeutronFirewall(NeutronFirewall firewall);
+
+    /**
+     * Services provide this interface method for taking action after a firewall has been deleted
+     *
+     * @param firewall
+     *            instance of deleted Firewall object
+     * @return void
+     */
+    public void neutronFirewallDeleted(NeutronFirewall firewall);
+}
diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallCRUD.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallCRUD.java
new file mode 100644 (file)
index 0000000..c986bff
--- /dev/null
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * 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.networkconfig.neutron;
+
+import java.util.List;
+
+/**
+ * This interface defines the methods for CRUD of NB OpenStack Firewall objects
+ *
+ */
+
+public interface INeutronFirewallCRUD {
+    /**
+     * Applications call this interface method to determine if a particular
+     *Firewall object exists
+     *
+     * @param uuid
+     *            UUID of the Firewall object
+     * @return boolean
+     */
+
+    public boolean neutronFirewallExists(String uuid);
+
+    /**
+     * Applications call this interface method to return if a particular
+     * Firewall object exists
+     *
+     * @param uuid
+     *            UUID of the Firewall object
+     * @return {@link org.opendaylight.controller.networkconfig.neutron.NeutronFirewall}
+     *          OpenStackFirewall class
+     */
+
+    public NeutronFirewall getNeutronFirewall(String uuid);
+
+    /**
+     * Applications call this interface method to return all Firewall objects
+     *
+     * @return List of OpenStackNetworks objects
+     */
+
+    public List<NeutronFirewall> getAllNeutronFirewalls();
+
+    /**
+     * Applications call this interface method to add a Firewall object to the
+     * concurrent map
+     *
+     * @param input
+     *            OpenStackNetwork object
+     * @return boolean on whether the object was added or not
+     */
+
+    public boolean addNeutronFirewall(NeutronFirewall input);
+
+    /**
+     * Applications call this interface method to remove a Neutron Firewall object to the
+     * concurrent map
+     *
+     * @param uuid
+     *            identifier for the Firewall object
+     * @return boolean on whether the object was removed or not
+     */
+
+    public boolean removeNeutronFirewall(String uuid);
+
+    /**
+     * Applications call this interface method to edit a Firewall object
+     *
+     * @param uuid
+     *            identifier of the Firewall object
+     * @param delta
+     *            OpenStackFirewall object containing changes to apply
+     * @return boolean on whether the object was updated or not
+     */
+
+    public boolean updateNeutronFirewall(String uuid, NeutronFirewall delta);
+
+    /**
+     * Applications call this interface method to see if a MAC address is in use
+     *
+     * @param uuid
+     *            identifier of the Firewall object
+     * @return boolean on whether the macAddress is already associated with a
+     * port or not
+     */
+
+    public boolean neutronFirewallInUse(String uuid);
+
+}
diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallPolicyAware.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallPolicyAware.java
new file mode 100644 (file)
index 0000000..203d513
--- /dev/null
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * 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.networkconfig.neutron;
+
+/**
+ * This interface defines the methods a service that wishes to be aware of Firewall Policys needs to implement
+ *
+ */
+
+public interface INeutronFirewallPolicyAware {
+
+    /**
+     * Services provide this interface method to indicate if the specified firewallPolicy can be created
+     *
+     * @param firewallPolicy
+     *            instance of proposed new Firewall Policy object
+     * @return integer
+     *            the return value is understood to be a HTTP status code.  A return value outside of 200 through 299
+     *            results in the create operation being interrupted and the returned status value reflected in the
+     *            HTTP response.
+     */
+    public int canCreateNeutronFirewallPolicy(NeutronFirewallPolicy firewallPolicy);
+
+    /**
+     * Services provide this interface method for taking action after a firewallPolicy has been created
+     *
+     * @param firewallPolicy
+     *            instance of new Firewall Policy object
+     * @return void
+     */
+    public void neutronFirewallPolicyCreated(NeutronFirewallPolicy firewallPolicy);
+
+    /**
+     * Services provide this interface method to indicate if the specified firewallPolicy can be changed using the specified
+     * delta
+     *
+     * @param delta
+     *            updates to the firewallPolicy object using patch semantics
+     * @param original
+     *            instance of the Firewall Policy object to be updated
+     * @return integer
+     *            the return value is understood to be a HTTP status code.  A return value outside of 200 through 299
+     *            results in the update operation being interrupted and the returned status value reflected in the
+     *            HTTP response.
+     */
+    public int canUpdateNeutronFirewallPolicy(NeutronFirewallPolicy delta, NeutronFirewallPolicy original);
+
+    /**
+     * Services provide this interface method for taking action after a firewallPolicy has been updated
+     *
+     * @param firewallPolicy
+     *            instance of modified Firewall Policy object
+     * @return void
+     */
+    public void neutronFirewallPolicyUpdated(NeutronFirewallPolicy firewallPolicy);
+
+    /**
+     * Services provide this interface method to indicate if the specified firewallPolicy can be deleted
+     *
+     * @param firewallPolicy
+     *            instance of the Firewall Policy object to be deleted
+     * @return integer
+     *            the return value is understood to be a HTTP status code.  A return value outside of 200 through 299
+     *            results in the delete operation being interrupted and the returned status value reflected in the
+     *            HTTP response.
+     */
+    public int canDeleteNeutronFirewallPolicy(NeutronFirewallPolicy firewallPolicy);
+
+    /**
+     * Services provide this interface method for taking action after a firewallPolicy has been deleted
+     *
+     * @param firewallPolicy
+     *            instance of deleted Firewall Policy object
+     * @return void
+     */
+    public void neutronFirewallPolicyDeleted(NeutronFirewallPolicy firewallPolicy);
+}
diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallPolicyCRUD.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallPolicyCRUD.java
new file mode 100644 (file)
index 0000000..6049656
--- /dev/null
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * 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.networkconfig.neutron;
+
+import java.util.List;
+
+/**
+ * This interface defines the methods for CRUD of NB OpenStack Firewall Policy objects
+ *
+ */
+
+public interface INeutronFirewallPolicyCRUD {
+    /**
+     * Applications call this interface method to determine if a particular
+     *FirewallPolicy object exists
+     *
+     * @param uuid
+     *            UUID of the Firewall Policy object
+     * @return boolean
+     */
+
+    public boolean neutronFirewallPolicyExists(String uuid);
+
+    /**
+     * Applications call this interface method to return if a particular
+     * FirewallPolicy object exists
+     *
+     * @param uuid
+     *            UUID of the Firewall Policy object
+     * @return {@link NeutronFirewallPolicy}
+     *          OpenStackFirewallPolicy class
+     */
+
+    public NeutronFirewallPolicy getNeutronFirewallPolicy(String uuid);
+
+    /**
+     * Applications call this interface method to return all Firewall Policy objects
+     *
+     * @return List of OpenStack Firewall Policy objects
+     */
+
+    public List<NeutronFirewallPolicy> getAllNeutronFirewallPolicies();
+
+    /**
+     * Applications call this interface method to add a Firewall Policy object to the
+     * concurrent map
+     *
+     * @param input
+     *            OpenStackNetwork object
+     * @return boolean on whether the object was added or not
+     */
+
+    public boolean addNeutronFirewallPolicy(NeutronFirewallPolicy input);
+
+    /**
+     * Applications call this interface method to remove a Neutron FirewallPolicy object to the
+     * concurrent map
+     *
+     * @param uuid
+     *            identifier for the Firewall Policy object
+     * @return boolean on whether the object was removed or not
+     */
+
+    public boolean removeNeutronFirewallPolicy(String uuid);
+
+    /**
+     * Applications call this interface method to edit a FirewallPolicy object
+     *
+     * @param uuid
+     *            identifier of the Firewall Policy object
+     * @param delta
+     *            OpenStackFirewallPolicy object containing changes to apply
+     * @return boolean on whether the object was updated or not
+     */
+
+    public boolean updateNeutronFirewallPolicy(String uuid, NeutronFirewallPolicy delta);
+
+    /**
+     * Applications call this interface method to see if a MAC address is in use
+     *
+     * @param uuid
+     *            identifier of the Firewall Policy object
+     * @return boolean on whether the macAddress is already associated with a
+     * port or not
+     */
+
+    public boolean neutronFirewallPolicyInUse(String uuid);
+
+}
diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallRuleAware.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallRuleAware.java
new file mode 100644 (file)
index 0000000..a663058
--- /dev/null
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * 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.networkconfig.neutron;
+
+/**
+ * This interface defines the methods a service that wishes to be aware of Firewall Rules needs to implement
+ *
+ */
+
+public interface INeutronFirewallRuleAware {
+
+    /**
+     * Services provide this interface method to indicate if the specified firewallRule can be created
+     *
+     * @param firewallRule
+     *            instance of proposed new Firewall Rule object
+     * @return integer
+     *            the return value is understood to be a HTTP status code.  A return value outside of 200 through 299
+     *            results in the create operation being interrupted and the returned status value reflected in the
+     *            HTTP response.
+     */
+    public int canCreateNeutronFirewallRule(NeutronFirewallRule firewallRule);
+
+    /**
+     * Services provide this interface method for taking action after a firewallRule has been created
+     *
+     * @param firewallRule
+     *            instance of new Firewall Rule object
+     * @return void
+     */
+    public void neutronFirewallRuleCreated(NeutronFirewallRule firewallRule);
+
+    /**
+     * Services provide this interface method to indicate if the specified firewallRule can be changed using the specified
+     * delta
+     *
+     * @param delta
+     *            updates to the firewallRule object using patch semantics
+     * @param original
+     *            instance of the Firewall Rule object to be updated
+     * @return integer
+     *            the return value is understood to be a HTTP status code.  A return value outside of 200 through 299
+     *            results in the update operation being interrupted and the returned status value reflected in the
+     *            HTTP response.
+     */
+    public int canUpdateNeutronFirewallRule(NeutronFirewallRule delta, NeutronFirewallRule original);
+
+    /**
+     * Services provide this interface method for taking action after a firewallRule has been updated
+     *
+     * @param firewallRule
+     *            instance of modified Firewall Rule object
+     * @return void
+     */
+    public void neutronFirewallRuleUpdated(NeutronFirewallRule firewallRule);
+
+    /**
+     * Services provide this interface method to indicate if the specified firewallRule can be deleted
+     *
+     * @param firewallRule
+     *            instance of the Firewall Rule object to be deleted
+     * @return integer
+     *            the return value is understood to be a HTTP status code.  A return value outside of 200 through 299
+     *            results in the delete operation being interrupted and the returned status value reflected in the
+     *            HTTP response.
+     */
+    public int canDeleteNeutronFirewallRule(NeutronFirewallRule firewallRule);
+
+    /**
+     * Services provide this interface method for taking action after a firewallRule has been deleted
+     *
+     * @param firewallRule
+     *            instance of deleted Firewall Rule object
+     * @return void
+     */
+    public void neutronFirewallRuleDeleted(NeutronFirewallRule firewallRule);
+}
diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallRuleCRUD.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronFirewallRuleCRUD.java
new file mode 100644 (file)
index 0000000..990896b
--- /dev/null
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * 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.networkconfig.neutron;
+
+import java.util.List;
+
+/**
+ * This interface defines the methods for CRUD of NB OpenStack Firewall Rule objects
+ *
+ */
+
+public interface INeutronFirewallRuleCRUD {
+    /**
+     * Applications call this interface method to determine if a particular
+     *FirewallRule object exists
+     *
+     * @param uuid
+     *            UUID of the Firewall Rule object
+     * @return boolean
+     */
+
+    public boolean neutronFirewallRuleExists(String uuid);
+
+    /**
+     * Applications call this interface method to return if a particular
+     * FirewallRule object exists
+     *
+     * @param uuid
+     *            UUID of the Firewall Rule object
+     * @return {@link NeutronFirewallRule}
+     *          OpenStackFirewall Rule class
+     */
+
+    public NeutronFirewallRule getNeutronFirewallRule(String uuid);
+
+    /**
+     * Applications call this interface method to return all Firewall Rule objects
+     *
+     * @return List of OpenStackNetworks objects
+     */
+
+    public List<NeutronFirewallRule> getAllNeutronFirewallRules();
+
+    /**
+     * Applications call this interface method to add a Firewall Rule object to the
+     * concurrent map
+     *
+     * @param input
+     *            OpenStackNetwork object
+     * @return boolean on whether the object was added or not
+     */
+
+    public boolean addNeutronFirewallRule(NeutronFirewallRule input);
+
+    /**
+     * Applications call this interface method to remove a Neutron FirewallRule object to the
+     * concurrent map
+     *
+     * @param uuid
+     *            identifier for the Firewall Rule object
+     * @return boolean on whether the object was removed or not
+     */
+
+    public boolean removeNeutronFirewallRule(String uuid);
+
+    /**
+     * Applications call this interface method to edit a FirewallRule object
+     *
+     * @param uuid
+     *            identifier of the Firewall Rule object
+     * @param delta
+     *            OpenStackFirewallRule object containing changes to apply
+     * @return boolean on whether the object was updated or not
+     */
+
+    public boolean updateNeutronFirewallRule(String uuid, NeutronFirewallRule delta);
+
+    /**
+     * Applications call this interface method to see if a MAC address is in use
+     *
+     * @param uuid
+     *            identifier of the Firewall Rule object
+     * @return boolean on whether the macAddress is already associated with a
+     * port or not
+     */
+
+    public boolean neutronFirewallRuleInUse(String uuid);
+
+}
index 21cfdb1305060d1bfa24ff32866f1ce0aa8509b5..6ce5499cdf9a2cc99ffda04d75d13a11d4c11bbb 100644 (file)
@@ -46,4 +46,19 @@ public class NeutronCRUDInterfaces {
         INeutronSecurityRuleCRUD answer = (INeutronSecurityRuleCRUD) ServiceHelper.getGlobalInstance(INeutronSecurityRuleCRUD.class, o);
         return answer;
     }
+
+    public static INeutronFirewallCRUD getINeutronFirewallCRUD(Object o) {
+        INeutronFirewallCRUD answer = (INeutronFirewallCRUD) ServiceHelper.getGlobalInstance(INeutronFirewallCRUD.class, o);
+        return answer;
+    }
+
+    public static INeutronFirewallPolicyCRUD getINeutronFirewallPolicyCRUD(Object o) {
+        INeutronFirewallPolicyCRUD answer = (INeutronFirewallPolicyCRUD) ServiceHelper.getGlobalInstance(INeutronFirewallPolicyCRUD.class, o);
+        return answer;
+    }
+
+    public static INeutronFirewallRuleCRUD getINeutronFirewallRuleCRUD(Object o) {
+        INeutronFirewallRuleCRUD answer = (INeutronFirewallRuleCRUD) ServiceHelper.getGlobalInstance(INeutronFirewallRuleCRUD.class, o);
+        return answer;
+    }
 }
\ No newline at end of file
diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronFirewall.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronFirewall.java
new file mode 100644 (file)
index 0000000..39f04c9
--- /dev/null
@@ -0,0 +1,178 @@
+/*
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * 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.networkconfig.neutron;
+
+import org.opendaylight.controller.configuration.ConfigurationObject;
+
+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 java.io.Serializable;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * OpenStack Neutron v2.0 Firewall as a service
+ * (FWaaS) bindings. See OpenStack Network API
+ * v2.0 Reference for description of  the fields:
+ * Implemented fields are as follows:
+ *
+ * id                 uuid-str
+ * tenant_id          uuid-str
+ * name               String
+ * description        String
+ * admin_state_up     Bool
+ * status             String
+ * shared             Bool
+ * firewall_policy_id uuid-str
+ * http://docs.openstack.org/api/openstack-network/2.0/openstack-network.pdf
+ */
+
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.NONE)
+
+public class NeutronFirewall extends ConfigurationObject implements Serializable {
+    private static final long serialVersionUID = 1L;
+
+    @XmlElement(name="id")
+    String firewallUUID;
+
+    @XmlElement (name="tenant_id")
+    String firewallTenantID;
+
+    @XmlElement (name="name")
+    String firewallName;
+
+    @XmlElement (name="description")
+    String firewallDescription;
+
+    @XmlElement (defaultValue="true", name="admin_state_up")
+    Boolean firewallAdminStateIsUp;
+
+    @XmlElement (name="status")
+    String firewallStatus;
+
+    @XmlElement (defaultValue="false", name="shared")
+    Boolean firewallIsShared;
+
+    @XmlElement (name="firewall_policy_id")
+    String neutronFirewallPolicyID;
+
+    public String getFirewallUUID() {
+        return firewallUUID;
+    }
+
+    public void setFirewallUUID(String firewallUUID) {
+        this.firewallUUID = firewallUUID;
+    }
+
+    public String getFirewallTenantID() {
+        return firewallTenantID;
+    }
+
+    public void setFirewallTenantID(String firewallTenantID) {
+        this.firewallTenantID = firewallTenantID;
+    }
+
+    public String getFirewallName() {
+        return firewallName;
+    }
+
+    public void setFirewallName(String firewallName) {
+        this.firewallName = firewallName;
+    }
+
+    public String getFirewallDescription() {
+        return firewallDescription;
+    }
+
+    public void setFirewallDescription(String firewallDescription) {
+        this.firewallDescription = firewallDescription;
+    }
+
+    public Boolean getFirewallAdminStateIsUp() {
+        return firewallAdminStateIsUp;
+    }
+
+    public void setFirewallAdminStateIsUp(Boolean firewallAdminStateIsUp) {
+        this.firewallAdminStateIsUp = firewallAdminStateIsUp;
+    }
+
+    public String getFirewallStatus() {
+        return firewallStatus;
+    }
+
+    public void setFirewallStatus(String firewallStatus) {
+        this.firewallStatus = firewallStatus;
+    }
+
+    public Boolean getFirewallIsShared() {
+        return firewallIsShared;
+    }
+
+    public void setFirewallIsShared(Boolean firewallIsShared) {
+        this.firewallIsShared = firewallIsShared;
+    }
+
+    public String getFirewallPolicyID() {
+        return neutronFirewallPolicyID;
+    }
+
+    public void setNeutronFirewallPolicyID(String firewallPolicy) {
+        this.neutronFirewallPolicyID = firewallPolicy;
+    }
+
+    public NeutronFirewall extractFields(List<String> fields) {
+        NeutronFirewall ans = new NeutronFirewall();
+        Iterator<String> i = fields.iterator();
+        while (i.hasNext()) {
+            String s = i.next();
+            if (s.equals("id")) {
+                ans.setFirewallUUID(this.getFirewallUUID());
+            }
+            if (s.equals("tenant_id")) {
+                ans.setFirewallTenantID(this.getFirewallTenantID());
+            }
+            if (s.equals("name")) {
+                ans.setFirewallName(this.getFirewallName());
+            }
+            if(s.equals("description")) {
+                ans.setFirewallDescription(this.getFirewallDescription());
+            }
+            if (s.equals("admin_state_up")) {
+                ans.setFirewallAdminStateIsUp(firewallAdminStateIsUp);
+            }
+            if (s.equals("status")) {
+                ans.setFirewallStatus(this.getFirewallStatus());
+            }
+            if (s.equals("shared")) {
+                ans.setFirewallIsShared(firewallIsShared);
+            }
+            if (s.equals("firewall_policy_id")) {
+                ans.setNeutronFirewallPolicyID(this.getFirewallPolicyID());
+            }
+        }
+        return ans;
+    }
+
+    @Override
+    public String toString() {
+        return "NeutronFirewall{" +
+            "firewallUUID='" + firewallUUID + '\'' +
+            ", firewallTenantID='" + firewallTenantID + '\'' +
+            ", firewallName='" + firewallName + '\'' +
+            ", firewallDescription='" + firewallDescription + '\'' +
+            ", firewallAdminStateIsUp=" + firewallAdminStateIsUp +
+            ", firewallStatus='" + firewallStatus + '\'' +
+            ", firewallIsShared=" + firewallIsShared +
+            ", firewallRulePolicyID=" + neutronFirewallPolicyID +
+            '}';
+    }
+}
diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronFirewallPolicy.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronFirewallPolicy.java
new file mode 100644 (file)
index 0000000..46436b5
--- /dev/null
@@ -0,0 +1,165 @@
+/*
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * 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.networkconfig.neutron;
+
+import org.opendaylight.controller.configuration.ConfigurationObject;
+
+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 java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * OpenStack Neutron v2.0 Firewall as a service
+ * (FWaaS) bindings. See OpenStack Network API
+ * v2.0 Reference for description of  the fields.
+ * The implemented fields are as follows:
+ *
+ * id             uuid-str
+ * tenant_id      uuid-str
+ * name           String
+ * description    String
+ * shared         Boolean
+ * firewall_rules List
+ * audited        Boolean
+ * http://docs.openstack.org/api/openstack-network/2.0/openstack-network.pdf
+ */
+
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.NONE)
+
+public class NeutronFirewallPolicy extends ConfigurationObject implements Serializable {
+    private static final long serialVersionUID = 1L;
+
+    @XmlElement(name="id")
+    String firewallPolicyUUID;
+
+    @XmlElement (name="tenant_id")
+    String firewallPolicyTenantID;
+
+    @XmlElement (name="name")
+    String firewallPolicyName;
+
+    @XmlElement (name="description")
+    String firewallPolicyDescription;
+
+    @XmlElement (defaultValue="false", name="shared")
+    Boolean firewallPolicyIsShared;
+
+    @XmlElement (name="firewall_rules")
+    List<String> firewallPolicyRules;
+
+    @XmlElement (defaultValue="false", name="audited")
+    String firewallPolicyIsAudited;
+
+    public String getFirewallPolicyIsAudited() {
+        return firewallPolicyIsAudited;
+    }
+
+    public void setFirewallPolicyIsAudited(String firewallPolicyIsAudited) {
+        this.firewallPolicyIsAudited = firewallPolicyIsAudited;
+    }
+
+    public void setFirewallPolicyRules(List<String> firewallPolicyRules) {
+        this.firewallPolicyRules = firewallPolicyRules;
+    }
+
+    public List<String> getFirewallPolicyRules() {
+        return firewallPolicyRules;
+    }
+
+    public Boolean getFirewallPolicyIsShared() {
+        return firewallPolicyIsShared;
+    }
+
+    public void setFirewallPolicyIsShared(Boolean firewallPolicyIsShared) {
+        this.firewallPolicyIsShared = firewallPolicyIsShared;
+    }
+
+    public String getFirewallPolicyDescription() {
+        return firewallPolicyDescription;
+    }
+
+    public void setFirewallPolicyDescription(String firewallPolicyDescription) {
+        this.firewallPolicyDescription = firewallPolicyDescription;
+    }
+
+    public String getFirewallPolicyName() {
+        return firewallPolicyName;
+    }
+
+    public void setFirewallPolicyName(String firewallPolicyName) {
+        this.firewallPolicyName = firewallPolicyName;
+    }
+
+    public String getFirewallPolicyTenantID() {
+        return firewallPolicyTenantID;
+    }
+
+    public void setFirewallPolicyTenantID(String firewallPolicyTenantID) {
+        this.firewallPolicyTenantID = firewallPolicyTenantID;
+    }
+
+    public String getFirewallPolicyUUID() {
+        return firewallPolicyUUID;
+    }
+
+    public void setFirewallPolicyUUID(String firewallPolicyUUID) {
+        this.firewallPolicyUUID = firewallPolicyUUID;
+    }
+
+    public NeutronFirewallPolicy extractFields(List<String> fields) {
+        NeutronFirewallPolicy ans = new NeutronFirewallPolicy();
+        Iterator<String> i = fields.iterator();
+        while (i.hasNext()) {
+            String s = i.next();
+            if (s.equals("id")) {
+                ans.setFirewallPolicyUUID(this.getFirewallPolicyUUID());
+            }
+            if (s.equals("tenant_id")) {
+                ans.setFirewallPolicyTenantID(this.getFirewallPolicyTenantID());
+            }
+            if (s.equals("name")) {
+                ans.setFirewallPolicyName(this.getFirewallPolicyName());
+            }
+            if(s.equals("description")) {
+                ans.setFirewallPolicyDescription(this.getFirewallPolicyDescription());
+            }
+            if (s.equals("shared")) {
+                ans.setFirewallPolicyIsShared(firewallPolicyIsShared);
+            }
+            if (s.equals("firewall_rules")) {
+                List<String> firewallRuleList = new ArrayList<String>();
+                firewallRuleList.addAll(this.getFirewallPolicyRules());
+                ans.setFirewallPolicyRules(firewallRuleList);
+            }
+            if (s.equals("audited")) {
+                ans.setFirewallPolicyIsAudited(firewallPolicyIsAudited);
+            }
+        }
+        return ans;
+    }
+
+    @Override
+    public String toString() {
+        return "NeutronFirewallPolicy{" +
+            "firewallPolicyUUID='" + firewallPolicyUUID + '\'' +
+            ", firewallPolicyTenantID='" + firewallPolicyTenantID + '\'' +
+            ", firewallPolicyName='" + firewallPolicyName + '\'' +
+            ", firewallPolicyDescription='" + firewallPolicyDescription + '\'' +
+            ", firewallPolicyIsShared=" + firewallPolicyIsShared +
+            ", firewallPolicyRules=" + firewallPolicyRules +
+            ", firewallPolicyIsAudited='" + firewallPolicyIsAudited + '\'' +
+            '}';
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronFirewallRule.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronFirewallRule.java
new file mode 100644 (file)
index 0000000..63a65a2
--- /dev/null
@@ -0,0 +1,323 @@
+/*
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * 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.networkconfig.neutron;
+
+import org.opendaylight.controller.configuration.ConfigurationObject;
+
+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 java.io.Serializable;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * OpenStack Neutron v2.0 Firewall as a service
+ * (FWaaS) bindings. See OpenStack Network API
+ * v2.0 Reference for description of  the fields.
+ * The implemented fields are as follows:
+ *
+ * tenant_id               uuid-str
+ * name                    String
+ * description             String
+ * admin_state_up          Bool
+ * status                  String
+ * shared                  Bool
+ * firewall_policy_id      uuid-str
+ * protocol                String
+ * ip_version              Integer
+ * source_ip_address       String (IP addr or CIDR)
+ * destination_ip_address  String (IP addr or CIDR)
+ * source_port             Integer
+ * destination_port        Integer
+ * position                Integer
+ * action                  String
+ * enabled                 Bool
+ * id                      uuid-str
+ * http://docs.openstack.org/api/openstack-network/2.0/openstack-network.pdf
+ */
+
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.NONE)
+
+public class NeutronFirewallRule extends ConfigurationObject implements Serializable {
+    private static final long serialVersionUID = 1L;
+
+    @XmlElement(name = "id")
+    String firewallRuleUUID;
+
+    @XmlElement(name = "tenant_id")
+    String firewallRuleTenantID;
+
+    @XmlElement(name = "name")
+    String firewallRuleName;
+
+    @XmlElement(name = "description")
+    String firewallRuleDescription;
+
+    @XmlElement(defaultValue = "true", name = "admin_state_up")
+    Boolean firewallRuleAdminStateIsUp;
+
+    @XmlElement(name = "status")
+    String firewallRuleStatus;
+
+    @XmlElement(defaultValue = "false", name = "shared")
+    Boolean firewallRuleIsShared;
+
+    @XmlElement(name = "firewall_policy_id")
+    String firewallRulePolicyID;
+
+    @XmlElement(name = "protocol")
+    String firewallRuleProtocol;
+
+    @XmlElement(name = "ip_version")
+    Integer firewallRuleIpVer;
+
+    @XmlElement(name = "source_ip_address")
+    String firewallRuleSrcIpAddr;
+
+    @XmlElement(name = "destination_ip_address")
+    String firewallRuleDstIpAddr;
+
+    @XmlElement(name = "source_port")
+    Integer firewallRuleSrcPort;
+
+    @XmlElement(name = "destination_port")
+    Integer firewallRuleDstPort;
+
+    @XmlElement(name = "position")
+    Integer firewallRulePosition;
+
+    @XmlElement(name = "action")
+    String firewallRuleAction;
+
+    @XmlElement(name = "enabled")
+    Boolean firewallRuleIsEnabled;
+
+    public Boolean getFirewallRuleIsEnabled() {
+        return firewallRuleIsEnabled;
+    }
+
+    public void setFirewallRuleIsEnabled(Boolean firewallRuleIsEnabled) {
+        this.firewallRuleIsEnabled = firewallRuleIsEnabled;
+    }
+
+    public String getFirewallRuleAction() {
+        return firewallRuleAction;
+    }
+
+    public void setFirewallRuleAction(String firewallRuleAction) {
+        this.firewallRuleAction = firewallRuleAction;
+    }
+
+    public Integer getFirewallRulePosition() {
+        return firewallRulePosition;
+    }
+
+    public void setFirewallRulePosition(Integer firewallRulePosition) {
+        this.firewallRulePosition = firewallRulePosition;
+    }
+
+    public Integer getFirewallRuleDstPort() {
+        return firewallRuleDstPort;
+    }
+
+    public void setFirewallRuleDstPort(Integer firewallRuleDstPort) {
+        this.firewallRuleDstPort = firewallRuleDstPort;
+    }
+
+    public Integer getFirewallRuleSrcPort() {
+        return firewallRuleSrcPort;
+    }
+
+    public void setFirewallRuleSrcPort(Integer firewallRuleSrcPort) {
+        this.firewallRuleSrcPort = firewallRuleSrcPort;
+    }
+
+    public String getFirewallRuleDstIpAddr() {
+        return firewallRuleDstIpAddr;
+    }
+
+    public void setFirewallRuleDstIpAddr(String firewallRuleDstIpAddr) {
+        this.firewallRuleDstIpAddr = firewallRuleDstIpAddr;
+    }
+
+    public String getFirewallRuleSrcIpAddr() {
+        return firewallRuleSrcIpAddr;
+    }
+
+    public void setFirewallRuleSrcIpAddr(String firewallRuleSrcIpAddr) {
+        this.firewallRuleSrcIpAddr = firewallRuleSrcIpAddr;
+    }
+
+    public Integer getFirewallRuleIpVer() {
+        return firewallRuleIpVer;
+    }
+
+    public void setFirewallRuleIpVer(Integer firewallRuleIpVer) {
+        this.firewallRuleIpVer = firewallRuleIpVer;
+    }
+
+    public String getFirewallRuleProtocol() {
+        return firewallRuleProtocol;
+    }
+
+    public void setFirewallRuleProtocol(String firewallRuleProtocol) {
+        this.firewallRuleProtocol = firewallRuleProtocol;
+    }
+
+    public String getFirewallRulePolicyID() {
+        return firewallRulePolicyID;
+    }
+
+    public void setFirewallRulesPolicyID(String firewallRulePolicyID) {
+        this.firewallRulePolicyID = firewallRulePolicyID;
+    }
+
+    public Boolean getFirewallRuleIsShared() {
+        return firewallRuleIsShared;
+    }
+
+    public void setFirewallRuleIsShared(Boolean firewallRuleIsShared) {
+        this.firewallRuleIsShared = firewallRuleIsShared;
+    }
+
+    public String getFirewallRuleStatus() {
+        return firewallRuleStatus;
+    }
+
+    public void setFirewallRuleStatus(String firewallRuleStatus) {
+        this.firewallRuleStatus = firewallRuleStatus;
+    }
+
+    public Boolean getFirewallRuleAdminStateIsUp() {
+        return firewallRuleAdminStateIsUp;
+    }
+
+    public void setFirewallRuleAdminStateIsUp(Boolean firewallRuleAdminStateIsUp) {
+        this.firewallRuleAdminStateIsUp = firewallRuleAdminStateIsUp;
+    }
+
+    public String getFirewallRuleDescription() {
+        return firewallRuleDescription;
+    }
+
+    public void setFirewallRuleDescription(String firewallRuleDescription) {
+        this.firewallRuleDescription = firewallRuleDescription;
+    }
+
+    public String getFirewallRuleName() {
+        return firewallRuleName;
+    }
+
+    public void setFirewallRuleName(String firewallRuleName) {
+        this.firewallRuleName = firewallRuleName;
+    }
+
+    public String getFirewallRuleTenantID() {
+        return firewallRuleTenantID;
+    }
+
+    public void setFirewallRuleTenantID(String firewallRuleTenantID) {
+        this.firewallRuleTenantID = firewallRuleTenantID;
+    }
+
+    public String getFirewallRuleUUID() {
+        return firewallRuleUUID;
+    }
+
+    public void setFirewallRuleUUID(String firewallRuleUUID) {
+        this.firewallRuleUUID = firewallRuleUUID;
+    }
+
+    public NeutronFirewallRule extractFields(List<String> fields) {
+        NeutronFirewallRule ans = new NeutronFirewallRule();
+        Iterator<String> i = fields.iterator();
+        while (i.hasNext()) {
+            String s = i.next();
+            if (s.equals("id")) {
+                ans.setFirewallRuleUUID(this.getFirewallRuleUUID());
+            }
+            if (s.equals("tenant_id")) {
+                ans.setFirewallRuleTenantID(this.getFirewallRuleTenantID());
+            }
+            if (s.equals("name")) {
+                ans.setFirewallRuleName(this.getFirewallRuleName());
+            }
+            if (s.equals("description")) {
+                ans.setFirewallRuleDescription(this.getFirewallRuleDescription());
+            }
+            if (s.equals("admin_state_up")) {
+                ans.setFirewallRuleAdminStateIsUp(firewallRuleAdminStateIsUp);
+            }
+            if (s.equals("status")) {
+                ans.setFirewallRuleStatus(this.getFirewallRuleStatus());
+            }
+            if (s.equals("shared")) {
+                ans.setFirewallRuleIsShared(firewallRuleIsShared);
+            }
+            if (s.equals("firewall_policy_id")) {
+                ans.setFirewallRulesPolicyID(this.getFirewallRulePolicyID());
+            }
+            if (s.equals("protocol")) {
+                ans.setFirewallRuleProtocol(this.getFirewallRuleProtocol());
+            }
+            if (s.equals("source_ip_address")) {
+                ans.setFirewallRuleSrcIpAddr(this.getFirewallRuleSrcIpAddr());
+            }
+            if (s.equals("destination_ip_address")) {
+                ans.setFirewallRuleDstIpAddr(this.getFirewallRuleDstIpAddr());
+            }
+            if (s.equals("source_port")) {
+                ans.setFirewallRuleSrcPort(this.getFirewallRuleSrcPort());
+            }
+            if (s.equals("destination_port")) {
+                ans.setFirewallRuleDstPort(this.getFirewallRuleDstPort());
+            }
+            if (s.equals("position")) {
+                ans.setFirewallRulePosition(this.getFirewallRulePosition());
+            }
+            if (s.equals("action")) {
+                ans.setFirewallRuleAction(this.getFirewallRuleAction());
+            }
+            if (s.equals("enabled")) {
+                ans.setFirewallRuleIsEnabled(firewallRuleIsEnabled);
+            }
+
+        }
+        return ans;
+    }
+
+    @Override
+    public String toString() {
+        return "firewallPolicyRules{" +
+            "firewallRuleUUID='" + firewallRuleUUID + '\'' +
+            ", firewallRuleTenantID='" + firewallRuleTenantID + '\'' +
+            ", firewallRuleName='" + firewallRuleName + '\'' +
+            ", firewallRuleDescription='" + firewallRuleDescription + '\'' +
+            ", firewallRuleAdminStateIsUp=" + firewallRuleAdminStateIsUp +
+            ", firewallRuleStatus='" + firewallRuleStatus + '\'' +
+            ", firewallRuleIsShared=" + firewallRuleIsShared +
+            ", firewallRulePolicyID=" + firewallRulePolicyID +
+            ", firewallRuleProtocol='" + firewallRuleProtocol + '\'' +
+            ", firewallRuleIpVer=" + firewallRuleIpVer +
+            ", firewallRuleSrcIpAddr='" + firewallRuleSrcIpAddr + '\'' +
+            ", firewallRuleDstIpAddr='" + firewallRuleDstIpAddr + '\'' +
+            ", firewallRuleSrcPort=" + firewallRuleSrcPort +
+            ", firewallRuleDstPort=" + firewallRuleDstPort +
+            ", firewallRulePosition=" + firewallRulePosition +
+            ", firewallRuleAction='" + firewallRuleAction + '\'' +
+            ", firewallRuleIsEnabled=" + firewallRuleIsEnabled +
+            '}';
+    }
+
+    public void initDefaults() {
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallNorthbound.java b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallNorthbound.java
new file mode 100644 (file)
index 0000000..204c9f5
--- /dev/null
@@ -0,0 +1,381 @@
+/*
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * 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.networkconfig.neutron.northbound;
+
+
+import org.codehaus.enunciate.jaxrs.ResponseCode;
+import org.codehaus.enunciate.jaxrs.StatusCodes;
+import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallAware;
+import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallCRUD;
+import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallRuleCRUD;
+import org.opendaylight.controller.networkconfig.neutron.NeutronCRUDInterfaces;
+import org.opendaylight.controller.networkconfig.neutron.NeutronFirewall;
+import org.opendaylight.controller.northbound.commons.RestMessages;
+import org.opendaylight.controller.northbound.commons.exception.BadRequestException;
+import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException;
+import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException;
+import org.opendaylight.controller.sal.utils.ServiceHelper;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * Neutron Northbound REST APIs for Firewall.<br>
+ * This class provides REST APIs for managing neutron Firewall
+ *
+ * <br>
+ * <br>
+ * Authentication scheme : <b>HTTP Basic</b><br>
+ * Authentication realm : <b>opendaylight</b><br>
+ * Transport : <b>HTTP and HTTPS</b><br>
+ * <br>
+ * HTTPS Authentication is disabled by default. Administrator can enable it in
+ * tomcat-server.xml after adding a proper keystore / SSL certificate from a
+ * trusted authority.<br>
+ * More info :
+ * http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
+ *
+ */
+@Path("/fw/firewalls")
+public class NeutronFirewallNorthbound {
+
+    private NeutronFirewall extractFields(NeutronFirewall o, List<String> fields) {
+        return o.extractFields(fields);
+    }
+
+    /**
+     * Returns a list of all Firewalls */
+    @GET
+    @Produces({ MediaType.APPLICATION_JSON })
+    @StatusCodes({
+            @ResponseCode(code = 200, condition = "Operation successful"),
+            @ResponseCode(code = 401, condition = "Unauthorized"),
+            @ResponseCode(code = 501, condition = "Not Implemented") })
+
+    public Response listGroups(
+            // return fields
+            @QueryParam("fields") List<String> fields,
+            // OpenStack firewall attributes
+            @QueryParam("id") String queryFirewallUUID,
+            @QueryParam("tenant_id") String queryFirewallTenantID,
+            @QueryParam("name") String queryFirewallName,
+            @QueryParam("description") String queryFirewallDescription,
+            @QueryParam("shared") Boolean queryFirewallAdminStateIsUp,
+            @QueryParam("status") String queryFirewallStatus,
+            @QueryParam("shared") Boolean queryFirewallIsShared,
+            @QueryParam("firewall_policy_id") String queryFirewallPolicyID,
+            // pagination
+            @QueryParam("limit") String limit,
+            @QueryParam("marker") String marker,
+            @QueryParam("page_reverse") String pageReverse
+            // sorting not supported
+    ) {
+        INeutronFirewallCRUD firewallInterface = NeutronCRUDInterfaces.getINeutronFirewallCRUD(this);
+        INeutronFirewallRuleCRUD firewallRuleInterface = NeutronCRUDInterfaces.getINeutronFirewallRuleCRUD(this);
+
+        if (firewallInterface == null) {
+            throw new ServiceUnavailableException("Firewall CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+        List<NeutronFirewall> allFirewalls = firewallInterface.getAllNeutronFirewalls();
+        List<NeutronFirewall> ans = new ArrayList<NeutronFirewall>();
+        Iterator<NeutronFirewall> i = allFirewalls.iterator();
+        while (i.hasNext()) {
+            NeutronFirewall nsg = i.next();
+            if ((queryFirewallUUID == null ||
+                queryFirewallUUID.equals(nsg.getFirewallUUID())) &&
+                (queryFirewallTenantID == null ||
+                    queryFirewallTenantID.equals(nsg.getFirewallTenantID())) &&
+                (queryFirewallName == null ||
+                    queryFirewallName.equals(nsg.getFirewallName())) &&
+                (queryFirewallDescription == null ||
+                    queryFirewallDescription.equals(nsg.getFirewallDescription())) &&
+                (queryFirewallAdminStateIsUp == null ||
+                    queryFirewallAdminStateIsUp.equals(nsg.getFirewallAdminStateIsUp())) &&
+                (queryFirewallStatus == null ||
+                    queryFirewallStatus.equals(nsg.getFirewallStatus())) &&
+                (queryFirewallIsShared == null ||
+                    queryFirewallIsShared.equals(nsg.getFirewallIsShared())) &&
+                (queryFirewallPolicyID == null ||
+                    queryFirewallPolicyID.equals(nsg.getFirewallPolicyID()))) {
+                if (fields.size() > 0) {
+                    ans.add(extractFields(nsg,fields));
+                } else {
+                    ans.add(nsg);
+                }
+            }
+        }
+        //TODO: apply pagination to results
+        return Response.status(200).entity(
+                new NeutronFirewallRequest(ans)).build();
+    }
+
+    /**
+     * Returns a specific Firewall */
+
+    @Path("{firewallUUID}")
+    @GET
+    @Produces({ MediaType.APPLICATION_JSON })
+    @StatusCodes({
+            @ResponseCode(code = 200, condition = "Operation successful"),
+            @ResponseCode(code = 401, condition = "Unauthorized"),
+            @ResponseCode(code = 404, condition = "Not Found"),
+            @ResponseCode(code = 501, condition = "Not Implemented") })
+    public Response showFirewall(@PathParam("firewallUUID") String firewallUUID,
+                                      // return fields
+                                      @QueryParam("fields") List<String> fields) {
+        INeutronFirewallCRUD firewallInterface = NeutronCRUDInterfaces.getINeutronFirewallCRUD(this);
+        if (firewallInterface == null) {
+            throw new ServiceUnavailableException("Firewall CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+        if (!firewallInterface.neutronFirewallExists(firewallUUID)) {
+            throw new ResourceNotFoundException("Firewall UUID does not exist.");
+        }
+        if (fields.size() > 0) {
+            NeutronFirewall ans = firewallInterface.getNeutronFirewall(firewallUUID);
+            return Response.status(200).entity(
+                    new NeutronFirewallRequest(extractFields(ans, fields))).build();
+        } else {
+            return Response.status(200).entity(new NeutronFirewallRequest(firewallInterface.getNeutronFirewall(firewallUUID))).build();
+        }
+    }
+
+    /**
+     * Creates new Firewall */
+
+    @POST
+    @Produces({ MediaType.APPLICATION_JSON })
+    @Consumes({ MediaType.APPLICATION_JSON })
+    @StatusCodes({
+            @ResponseCode(code = 201, condition = "Created"),
+            @ResponseCode(code = 400, condition = "Bad Request"),
+            @ResponseCode(code = 401, condition = "Unauthorized"),
+            @ResponseCode(code = 403, condition = "Forbidden"),
+            @ResponseCode(code = 404, condition = "Not Found"),
+            @ResponseCode(code = 409, condition = "Conflict"),
+            @ResponseCode(code = 501, condition = "Not Implemented") })
+    public Response createFirewalls(final NeutronFirewallRequest input) {
+        INeutronFirewallCRUD firewallInterface = NeutronCRUDInterfaces.getINeutronFirewallCRUD(this);
+        if (firewallInterface == null) {
+            throw new ServiceUnavailableException("Firewall CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+        if (input.isSingleton()) {
+            NeutronFirewall singleton = input.getSingleton();
+
+            /*
+             *  Verify that the Firewall doesn't already exist.
+             */
+            if (firewallInterface.neutronFirewallExists(singleton.getFirewallUUID())) {
+                throw new BadRequestException("Firewall UUID already exists");
+            }
+            firewallInterface.addNeutronFirewall(singleton);
+            Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallAware.class, this, null);
+            if (instances != null) {
+                for (Object instance : instances) {
+                    INeutronFirewallAware service = (INeutronFirewallAware) instance;
+                    int status = service.canCreateNeutronFirewall(singleton);
+                    if (status < 200 || status > 299) {
+                        return Response.status(status).build();
+                    }
+                }
+            }
+            firewallInterface.addNeutronFirewall(singleton);
+            if (instances != null) {
+                for (Object instance : instances) {
+                    INeutronFirewallAware service = (INeutronFirewallAware) instance;
+                    service.neutronFirewallCreated(singleton);
+                }
+            }
+        } else {
+            List<NeutronFirewall> bulk = input.getBulk();
+            Iterator<NeutronFirewall> i = bulk.iterator();
+            HashMap<String, NeutronFirewall> testMap = new HashMap<String, NeutronFirewall>();
+            Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallAware.class, this, null);
+            while (i.hasNext()) {
+                NeutronFirewall test = i.next();
+
+                /*
+                 *  Verify that the secruity group doesn't already exist
+                 */
+                if (firewallInterface.neutronFirewallExists(test.getFirewallUUID())) {
+                    throw new BadRequestException("Firewall UUID already is already created");
+                }
+                if (testMap.containsKey(test.getFirewallUUID())) {
+                    throw new BadRequestException("Firewall UUID already exists");
+                }
+                if (instances != null) {
+                    for (Object instance : instances) {
+                        INeutronFirewallAware service = (INeutronFirewallAware) instance;
+                        int status = service.canCreateNeutronFirewall(test);
+                        if (status < 200 || status > 299) {
+                            return Response.status(status).build();
+                        }
+                    }
+                }
+            }
+
+            /*
+             * now, each element of the bulk request can be added to the cache
+             */
+            i = bulk.iterator();
+            while (i.hasNext()) {
+                NeutronFirewall test = i.next();
+                firewallInterface.addNeutronFirewall(test);
+                if (instances != null) {
+                    for (Object instance : instances) {
+                        INeutronFirewallAware service = (INeutronFirewallAware) instance;
+                        service.neutronFirewallCreated(test);
+                    }
+                }
+            }
+        }
+        return Response.status(201).entity(input).build();
+    }
+
+    /**
+     * Updates a Firewall */
+
+    @Path("{firewallUUID}")
+    @PUT
+    @Produces({ MediaType.APPLICATION_JSON })
+    @Consumes({ MediaType.APPLICATION_JSON })
+    @StatusCodes({
+            @ResponseCode(code = 200, condition = "Operation successful"),
+            @ResponseCode(code = 400, condition = "Bad Request"),
+            @ResponseCode(code = 401, condition = "Unauthorized"),
+            @ResponseCode(code = 403, condition = "Forbidden"),
+            @ResponseCode(code = 404, condition = "Not Found"),
+            @ResponseCode(code = 501, condition = "Not Implemented") })
+    public Response updateFirewall(
+            @PathParam("firewallUUID") String firewallUUID, final NeutronFirewallRequest input) {
+        INeutronFirewallCRUD firewallInterface = NeutronCRUDInterfaces.getINeutronFirewallCRUD(this);
+        if (firewallInterface == null) {
+            throw new ServiceUnavailableException("Firewall CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+
+        /*
+         * verify the Firewall exists and there is only one delta provided
+         */
+        if (!firewallInterface.neutronFirewallExists(firewallUUID)) {
+            throw new ResourceNotFoundException("Firewall UUID does not exist.");
+        }
+        if (!input.isSingleton()) {
+            throw new BadRequestException("Only singleton edit supported");
+        }
+        NeutronFirewall delta = input.getSingleton();
+        NeutronFirewall original = firewallInterface.getNeutronFirewall(firewallUUID);
+
+        /*
+         * updates restricted by Neutron
+         */
+        if (delta.getFirewallUUID() != null ||
+                delta.getFirewallTenantID() != null ||
+                delta.getFirewallName() != null ||
+                delta.getFirewallDescription() != null ||
+                delta.getFirewallAdminStateIsUp() != null ||
+                delta.getFirewallStatus() != null ||
+                delta.getFirewallIsShared() != null ||
+                delta.getFirewallPolicyID() != null) {
+            throw new BadRequestException("Attribute edit blocked by Neutron");
+        }
+
+        Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallAware.class, this, null);
+        if (instances != null) {
+            for (Object instance : instances) {
+                INeutronFirewallAware service = (INeutronFirewallAware) instance;
+                int status = service.canUpdateNeutronFirewall(delta, original);
+                if (status < 200 || status > 299) {
+                    return Response.status(status).build();
+                }
+            }
+        }
+
+        /*
+         * update the object and return it
+         */
+        firewallInterface.updateNeutronFirewall(firewallUUID, delta);
+        NeutronFirewall updatedFirewall = firewallInterface.getNeutronFirewall(firewallUUID);
+        if (instances != null) {
+            for (Object instance : instances) {
+                INeutronFirewallAware service = (INeutronFirewallAware) instance;
+                service.neutronFirewallUpdated(updatedFirewall);
+            }
+        }
+        return Response.status(200).entity(new NeutronFirewallRequest(firewallInterface.getNeutronFirewall(firewallUUID))).build();
+    }
+
+    /**
+     * Deletes a Firewall */
+
+    @Path("{firewallUUID}")
+    @DELETE
+    @StatusCodes({
+            @ResponseCode(code = 204, condition = "No Content"),
+            @ResponseCode(code = 401, condition = "Unauthorized"),
+            @ResponseCode(code = 404, condition = "Not Found"),
+            @ResponseCode(code = 409, condition = "Conflict"),
+            @ResponseCode(code = 501, condition = "Not Implemented") })
+    public Response deleteFirewall(
+            @PathParam("firewallUUID") String firewallUUID) {
+        INeutronFirewallCRUD firewallInterface = NeutronCRUDInterfaces.getINeutronFirewallCRUD(this);
+        if (firewallInterface == null) {
+            throw new ServiceUnavailableException("Firewall CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+
+        /*
+         * verify the Firewall exists and it isn't currently in use
+         */
+        if (!firewallInterface.neutronFirewallExists(firewallUUID)) {
+            throw new ResourceNotFoundException("Firewall UUID does not exist.");
+        }
+        if (firewallInterface.neutronFirewallInUse(firewallUUID)) {
+            return Response.status(409).build();
+        }
+        NeutronFirewall singleton = firewallInterface.getNeutronFirewall(firewallUUID);
+        Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallAware.class, this, null);
+        if (instances != null) {
+            for (Object instance : instances) {
+                INeutronFirewallAware service = (INeutronFirewallAware) instance;
+                int status = service.canDeleteNeutronFirewall(singleton);
+                if (status < 200 || status > 299) {
+                    return Response.status(status).build();
+                }
+            }
+        }
+
+        /*
+         * remove it and return 204 status
+         */
+        firewallInterface.removeNeutronFirewall(firewallUUID);
+        if (instances != null) {
+            for (Object instance : instances) {
+                INeutronFirewallAware service = (INeutronFirewallAware) instance;
+                service.neutronFirewallDeleted(singleton);
+            }
+        }
+        return Response.status(204).build();
+    }
+}
diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyNorthbound.java b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyNorthbound.java
new file mode 100644 (file)
index 0000000..bfe2c92
--- /dev/null
@@ -0,0 +1,374 @@
+/*
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * 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.networkconfig.neutron.northbound;
+
+
+import org.codehaus.enunciate.jaxrs.ResponseCode;
+import org.codehaus.enunciate.jaxrs.StatusCodes;
+import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallPolicyAware;
+import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallPolicyCRUD;
+import org.opendaylight.controller.networkconfig.neutron.NeutronCRUDInterfaces;
+import org.opendaylight.controller.networkconfig.neutron.NeutronFirewallPolicy;
+import org.opendaylight.controller.northbound.commons.RestMessages;
+import org.opendaylight.controller.northbound.commons.exception.BadRequestException;
+import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException;
+import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException;
+import org.opendaylight.controller.sal.utils.ServiceHelper;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * Neutron Northbound REST APIs for Firewall Policies.<br>
+ * This class provides REST APIs for managing neutron Firewall Policies
+ *
+ * <br>
+ * <br>
+ * Authentication scheme : <b>HTTP Basic</b><br>
+ * Authentication realm : <b>opendaylight</b><br>
+ * Transport : <b>HTTP and HTTPS</b><br>
+ * <br>
+ * HTTPS Authentication is disabled by default. Administrator can enable it in
+ * tomcat-server.xml after adding a proper keystore / SSL certificate from a
+ * trusted authority.<br>
+ * More info :
+ * http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
+ *
+ */
+@Path("/fw/firewalls_policies")
+public class NeutronFirewallPolicyNorthbound {
+
+    private NeutronFirewallPolicy extractFields(NeutronFirewallPolicy o, List<String> fields) {
+        return o.extractFields(fields);
+    }
+
+    /**
+     * Returns a list of all Firewall Policies */
+    @GET
+    @Produces({ MediaType.APPLICATION_JSON })
+    @StatusCodes({
+            @ResponseCode(code = 200, condition = "Operation successful"),
+            @ResponseCode(code = 401, condition = "Unauthorized"),
+            @ResponseCode(code = 501, condition = "Not Implemented") })
+
+    public Response listGroups(
+            // return fields
+            @QueryParam("fields") List<String> fields,
+            // OpenStack Firewall Policy attributes
+            @QueryParam("id") String queryFirewallPolicyUUID,
+            @QueryParam("tenant_id") String queryFirewallPolicyTenantID,
+            @QueryParam("name") String queryFirewallPolicyName,
+            @QueryParam("description") String querySecurityPolicyDescription,
+            @QueryParam("shared") String querySecurityPolicyIsShared,
+            @QueryParam("firewall_rules") List querySecurityPolicyFirewallRules,
+            @QueryParam("audited") Boolean querySecurityPolicyIsAudited,
+            // pagination
+            @QueryParam("limit") String limit,
+            @QueryParam("marker") String marker,
+            @QueryParam("page_reverse") String pageReverse
+            // sorting not supported
+    ) {
+        INeutronFirewallPolicyCRUD firewallPolicyInterface = NeutronCRUDInterfaces.getINeutronFirewallPolicyCRUD(this);
+
+        if (firewallPolicyInterface == null) {
+            throw new ServiceUnavailableException("Firewall Policy CRUD Interface "
+                + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+        List<NeutronFirewallPolicy> allFirewallPolicies = firewallPolicyInterface.getAllNeutronFirewallPolicies();
+        List<NeutronFirewallPolicy> ans = new ArrayList<NeutronFirewallPolicy>();
+        Iterator<NeutronFirewallPolicy> i = allFirewallPolicies.iterator();
+        while (i.hasNext()) {
+            NeutronFirewallPolicy nsg = i.next();
+            if ((queryFirewallPolicyUUID == null ||
+                queryFirewallPolicyUUID.equals(nsg.getFirewallPolicyUUID())) &&
+                (queryFirewallPolicyTenantID == null ||
+                    queryFirewallPolicyTenantID.equals(nsg.getFirewallPolicyTenantID())) &&
+                (queryFirewallPolicyName == null ||
+                    queryFirewallPolicyName.equals(nsg.getFirewallPolicyName())) &&
+                (querySecurityPolicyDescription == null ||
+                    querySecurityPolicyDescription.equals(nsg.getFirewallPolicyDescription())) &&
+                (querySecurityPolicyIsShared == null ||
+                    querySecurityPolicyIsShared.equals(nsg.getFirewallPolicyIsShared())) &&
+                (querySecurityPolicyFirewallRules.size() == 0 ||
+                    querySecurityPolicyFirewallRules.equals(nsg.getFirewallPolicyRules())) &&
+                (querySecurityPolicyIsAudited == null ||
+                    querySecurityPolicyIsAudited.equals(nsg.getFirewallPolicyIsAudited()))) {
+                if (fields.size() > 0) {
+                    ans.add(extractFields(nsg,fields));
+                } else {
+                    ans.add(nsg);
+                }
+            }
+        } // ans.add((NeutronFirewallPolicy) rules);
+        //TODO: apply pagination to results
+        return Response.status(200).entity(
+                new NeutronFirewallPolicyRequest(ans)).build();
+    }
+
+    /**
+     * Returns a specific Firewall Policy */
+
+    @Path("{firewallPolicyUUID}")
+    @GET
+    @Produces({ MediaType.APPLICATION_JSON })
+    @StatusCodes({
+            @ResponseCode(code = 200, condition = "Operation successful"),
+            @ResponseCode(code = 401, condition = "Unauthorized"),
+            @ResponseCode(code = 404, condition = "Not Found"),
+            @ResponseCode(code = 501, condition = "Not Implemented") })
+    public Response showFirewallPolicy(@PathParam("firewallPolicyUUID") String firewallPolicyUUID,
+                                      // return fields
+                                      @QueryParam("fields") List<String> fields) {
+        INeutronFirewallPolicyCRUD firewallPolicyInterface = NeutronCRUDInterfaces.getINeutronFirewallPolicyCRUD(this);
+        if (firewallPolicyInterface == null) {
+            throw new ServiceUnavailableException("Firewall Policy CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+        if (!firewallPolicyInterface.neutronFirewallPolicyExists(firewallPolicyUUID)) {
+            throw new ResourceNotFoundException("Firewall Policy UUID does not exist.");
+        }
+        if (fields.size() > 0) {
+            NeutronFirewallPolicy ans = firewallPolicyInterface.getNeutronFirewallPolicy(firewallPolicyUUID);
+            return Response.status(200).entity(
+                    new NeutronFirewallPolicyRequest(extractFields(ans, fields))).build();
+        } else {
+            return Response.status(200).entity(new NeutronFirewallPolicyRequest(firewallPolicyInterface.getNeutronFirewallPolicy(firewallPolicyUUID))).build();
+        }
+    }
+
+    /**
+     * Creates new Firewall Policy
+     * */
+    @POST
+    @Produces({ MediaType.APPLICATION_JSON })
+    @Consumes({ MediaType.APPLICATION_JSON })
+    @StatusCodes({
+            @ResponseCode(code = 201, condition = "Created"),
+            @ResponseCode(code = 400, condition = "Bad Request"),
+            @ResponseCode(code = 401, condition = "Unauthorized"),
+            @ResponseCode(code = 403, condition = "Forbidden"),
+            @ResponseCode(code = 404, condition = "Not Found"),
+            @ResponseCode(code = 409, condition = "Conflict"),
+            @ResponseCode(code = 501, condition = "Not Implemented") })
+    public Response createFirewallPolicies(final NeutronFirewallPolicyRequest input) {
+        INeutronFirewallPolicyCRUD firewallPolicyInterface = NeutronCRUDInterfaces.getINeutronFirewallPolicyCRUD(this);
+        if (firewallPolicyInterface == null) {
+            throw new ServiceUnavailableException("Firewall Policy CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+        if (input.isSingleton()) {
+            NeutronFirewallPolicy singleton = input.getSingleton();
+
+            /*
+             *  Verify that the Firewall Policy doesn't already exist.
+             */
+            if (firewallPolicyInterface.neutronFirewallPolicyExists(singleton.getFirewallPolicyUUID())) {
+                throw new BadRequestException("Firewall Policy UUID already exists");
+            }
+            firewallPolicyInterface.addNeutronFirewallPolicy(singleton);
+
+            Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallPolicyAware.class, this, null);
+            if (instances != null) {
+                for (Object instance : instances) {
+                    INeutronFirewallPolicyAware service = (INeutronFirewallPolicyAware) instance;
+                    int status = service.canCreateNeutronFirewallPolicy(singleton);
+                    if (status < 200 || status > 299) {
+                        return Response.status(status).build();
+                    }
+                }
+            }
+            firewallPolicyInterface.addNeutronFirewallPolicy(singleton);
+            if (instances != null) {
+                for (Object instance : instances) {
+                    INeutronFirewallPolicyAware service = (INeutronFirewallPolicyAware) instance;
+                    service.neutronFirewallPolicyCreated(singleton);
+                }
+            }
+        } else {
+            List<NeutronFirewallPolicy> bulk = input.getBulk();
+            Iterator<NeutronFirewallPolicy> i = bulk.iterator();
+            HashMap<String, NeutronFirewallPolicy> testMap = new HashMap<String, NeutronFirewallPolicy>();
+            Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallPolicyAware.class, this, null);
+            while (i.hasNext()) {
+                NeutronFirewallPolicy test = i.next();
+
+                /*
+                 *  Verify that the firewall policy doesn't already exist
+                 */
+
+                if (firewallPolicyInterface.neutronFirewallPolicyExists(test.getFirewallPolicyUUID())) {
+                    throw new BadRequestException("Firewall Policy UUID already is already created");
+                }
+                if (testMap.containsKey(test.getFirewallPolicyUUID())) {
+                    throw new BadRequestException("Firewall Policy UUID already exists");
+                }
+                if (instances != null) {
+                    for (Object instance : instances) {
+                        INeutronFirewallPolicyAware service = (INeutronFirewallPolicyAware) instance;
+                        int status = service.canCreateNeutronFirewallPolicy(test);
+                        if (status < 200 || status > 299) {
+                            return Response.status(status).build();
+                        }
+                    }
+                }
+            }
+            /*
+             * now, each element of the bulk request can be added to the cache
+             */
+            i = bulk.iterator();
+            while (i.hasNext()) {
+                NeutronFirewallPolicy test = i.next();
+                firewallPolicyInterface.addNeutronFirewallPolicy(test);
+                if (instances != null) {
+                    for (Object instance : instances) {
+                        INeutronFirewallPolicyAware service = (INeutronFirewallPolicyAware) instance;
+                        service.neutronFirewallPolicyCreated(test);
+                    }
+                }
+            }
+        }
+        return Response.status(201).entity(input).build();
+    }
+
+    /**
+     * Updates a Firewall Policy
+     */
+    @Path("{firewallPolicyUUID}")
+    @PUT
+    @Produces({ MediaType.APPLICATION_JSON })
+    @Consumes({ MediaType.APPLICATION_JSON })
+    //@TypeHint(OpenStackSubnets.class)
+    @StatusCodes({
+            @ResponseCode(code = 200, condition = "Operation successful"),
+            @ResponseCode(code = 400, condition = "Bad Request"),
+            @ResponseCode(code = 401, condition = "Unauthorized"),
+            @ResponseCode(code = 403, condition = "Forbidden"),
+            @ResponseCode(code = 404, condition = "Not Found"),
+            @ResponseCode(code = 501, condition = "Not Implemented") })
+    public Response updateFirewallPolicy(
+            @PathParam("firewallPolicyUUID") String firewallPolicyUUID, final NeutronFirewallPolicyRequest input) {
+        INeutronFirewallPolicyCRUD firewallPolicyInterface = NeutronCRUDInterfaces.getINeutronFirewallPolicyCRUD(this);
+        if (firewallPolicyInterface == null) {
+            throw new ServiceUnavailableException("Firewall Policy CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+
+        /*
+         * verify the Firewall Policy exists and there is only one delta provided
+         */
+        if (!firewallPolicyInterface.neutronFirewallPolicyExists(firewallPolicyUUID)) {
+            throw new ResourceNotFoundException("Firewall Policy UUID does not exist.");
+        }
+        if (!input.isSingleton()) {
+            throw new BadRequestException("Only singleton edit supported");
+        }
+        NeutronFirewallPolicy delta = input.getSingleton();
+        NeutronFirewallPolicy original = firewallPolicyInterface.getNeutronFirewallPolicy(firewallPolicyUUID);
+
+        /*
+         * updates restricted by Neutron
+         */
+        if (delta.getFirewallPolicyUUID() != null ||
+                delta.getFirewallPolicyTenantID() != null ||
+                delta.getFirewallPolicyName() != null ||
+                delta.getFirewallPolicyDescription() != null ||
+                delta.getFirewallPolicyIsShared() != null ||
+                delta.getFirewallPolicyRules().size() > 0 ||
+                delta.getFirewallPolicyIsAudited() != null) {
+            throw new BadRequestException("Attribute edit blocked by Neutron");
+        }
+
+        Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallPolicyAware.class, this, null);
+        if (instances != null) {
+            for (Object instance : instances) {
+                INeutronFirewallPolicyAware service = (INeutronFirewallPolicyAware) instance;
+                int status = service.canUpdateNeutronFirewallPolicy(delta, original);
+                if (status < 200 || status > 299) {
+                    return Response.status(status).build();
+                }
+            }
+        }
+
+        /*
+         * update the object and return it
+         */
+        firewallPolicyInterface.updateNeutronFirewallPolicy(firewallPolicyUUID, delta);
+        NeutronFirewallPolicy updatedFirewallPolicy = firewallPolicyInterface.getNeutronFirewallPolicy(firewallPolicyUUID);
+        if (instances != null) {
+            for (Object instance : instances) {
+                INeutronFirewallPolicyAware service = (INeutronFirewallPolicyAware) instance;
+                service.neutronFirewallPolicyUpdated(updatedFirewallPolicy);
+            }
+        }
+        return Response.status(200).entity(new NeutronFirewallPolicyRequest(firewallPolicyInterface.getNeutronFirewallPolicy(firewallPolicyUUID))).build();
+    }
+
+    /**
+     * Deletes a Firewall Policy */
+
+    @Path("{firewallPolicyUUID}")
+    @DELETE
+    @StatusCodes({
+            @ResponseCode(code = 204, condition = "No Content"),
+            @ResponseCode(code = 401, condition = "Unauthorized"),
+            @ResponseCode(code = 404, condition = "Not Found"),
+            @ResponseCode(code = 409, condition = "Conflict"),
+            @ResponseCode(code = 501, condition = "Not Implemented") })
+    public Response deleteFirewallPolicy(
+            @PathParam("firewallPolicyUUID") String firewallPolicyUUID) {
+        INeutronFirewallPolicyCRUD firewallPolicyInterface = NeutronCRUDInterfaces.getINeutronFirewallPolicyCRUD(this);
+        if (firewallPolicyInterface == null) {
+            throw new ServiceUnavailableException("Firewall Policy CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+
+        /*
+         * verify the Firewall Policy exists and it isn't currently in use
+         */
+        if (!firewallPolicyInterface.neutronFirewallPolicyExists(firewallPolicyUUID)) {
+            throw new ResourceNotFoundException("Firewall Policy UUID does not exist.");
+        }
+        if (firewallPolicyInterface.neutronFirewallPolicyInUse(firewallPolicyUUID)) {
+            return Response.status(409).build();
+        }
+        NeutronFirewallPolicy singleton = firewallPolicyInterface.getNeutronFirewallPolicy(firewallPolicyUUID);
+        Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallPolicyAware.class, this, null);
+        if (instances != null) {
+            for (Object instance : instances) {
+                INeutronFirewallPolicyAware service = (INeutronFirewallPolicyAware) instance;
+                int status = service.canDeleteNeutronFirewallPolicy(singleton);
+                if (status < 200 || status > 299) {
+                    return Response.status(status).build();
+                }
+            }
+        }
+
+        firewallPolicyInterface.removeNeutronFirewallPolicy(firewallPolicyUUID);
+        if (instances != null) {
+            for (Object instance : instances) {
+                INeutronFirewallPolicyAware service = (INeutronFirewallPolicyAware) instance;
+                service.neutronFirewallPolicyDeleted(singleton);
+            }
+        }
+        return Response.status(204).build();
+    }
+}
diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyRequest.java b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallPolicyRequest.java
new file mode 100644 (file)
index 0000000..473846a
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * 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.networkconfig.neutron.northbound;
+
+import org.opendaylight.controller.networkconfig.neutron.NeutronFirewallPolicy;
+
+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 java.util.List;
+
+
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.NONE)
+
+public class NeutronFirewallPolicyRequest {
+    /**
+     * See OpenStack Network API v2.0 Reference for description of
+     * http://docs.openstack.org/api/openstack-network/2.0/content/
+     */
+
+    @XmlElement(name="firewall_policy")
+    NeutronFirewallPolicy singletonFirewallPolicy;
+
+    @XmlElement(name="firewall_policies")
+    List<NeutronFirewallPolicy> bulkRequest;
+
+    NeutronFirewallPolicyRequest() {
+    }
+
+    NeutronFirewallPolicyRequest(List<NeutronFirewallPolicy> bulk) {
+        bulkRequest = bulk;
+        singletonFirewallPolicy = null;
+    }
+
+    NeutronFirewallPolicyRequest(NeutronFirewallPolicy group) {
+        singletonFirewallPolicy = group;
+    }
+
+    public List<NeutronFirewallPolicy> getBulk() {
+        return bulkRequest;
+    }
+
+    public NeutronFirewallPolicy getSingleton() {
+        return singletonFirewallPolicy;
+    }
+
+    public boolean isSingleton() {
+        return (singletonFirewallPolicy != null);
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRequest.java b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRequest.java
new file mode 100644 (file)
index 0000000..11a7836
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * 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.networkconfig.neutron.northbound;
+
+import org.opendaylight.controller.networkconfig.neutron.NeutronFirewall;
+
+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 java.util.List;
+
+
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.NONE)
+
+public class NeutronFirewallRequest {
+    /**
+     * See OpenStack Network API v2.0 Reference for description of
+     * http://docs.openstack.org/api/openstack-network/2.0/content/
+     */
+
+    @XmlElement(name="firewall")
+    NeutronFirewall singletonFirewall;
+
+    @XmlElement(name="firewalls")
+    List<NeutronFirewall> bulkRequest;
+
+    NeutronFirewallRequest() {
+    }
+
+    NeutronFirewallRequest(List<NeutronFirewall> bulk) {
+        bulkRequest = bulk;
+        singletonFirewall = null;
+    }
+
+    NeutronFirewallRequest(NeutronFirewall group) {
+        singletonFirewall = group;
+    }
+
+    public List<NeutronFirewall> getBulk() {
+        return bulkRequest;
+    }
+
+    public NeutronFirewall getSingleton() {
+        return singletonFirewall;
+    }
+
+    public boolean isSingleton() {
+        return (singletonFirewall != null);
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRuleRequest.java b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRuleRequest.java
new file mode 100644 (file)
index 0000000..19e67dd
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * 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.networkconfig.neutron.northbound;
+
+import org.opendaylight.controller.networkconfig.neutron.NeutronFirewallRule;
+
+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 java.util.List;
+
+
+@XmlRootElement
+@XmlAccessorType(XmlAccessType.NONE)
+
+public class NeutronFirewallRuleRequest {
+    /**
+     * See OpenStack Network API v2.0 Reference for description of
+     * http://docs.openstack.org/api/openstack-network/2.0/content/
+     */
+
+    @XmlElement(name="firewall_rule")
+    NeutronFirewallRule singletonFirewallRule;
+
+    @XmlElement(name="firewall_rules")
+    List<NeutronFirewallRule> bulkRequest;
+
+    NeutronFirewallRuleRequest() {
+    }
+
+    NeutronFirewallRuleRequest(List<NeutronFirewallRule> bulk) {
+        bulkRequest = bulk;
+        singletonFirewallRule = null;
+    }
+
+    NeutronFirewallRuleRequest(NeutronFirewallRule group) {
+        singletonFirewallRule = group;
+    }
+
+    public List<NeutronFirewallRule> getBulk() {
+        return bulkRequest;
+    }
+
+    public NeutronFirewallRule getSingleton() {
+        return singletonFirewallRule;
+    }
+
+    public boolean isSingleton() {
+        return (singletonFirewallRule != null);
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRulesNorthbound.java b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronFirewallRulesNorthbound.java
new file mode 100644 (file)
index 0000000..9911b4d
--- /dev/null
@@ -0,0 +1,427 @@
+/*
+ * Copyright (C) 2014 Red Hat, Inc.
+ *
+ * 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.networkconfig.neutron.northbound;
+
+
+import org.codehaus.enunciate.jaxrs.ResponseCode;
+import org.codehaus.enunciate.jaxrs.StatusCodes;
+import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallPolicyCRUD;
+import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallRuleAware;
+import org.opendaylight.controller.networkconfig.neutron.INeutronFirewallRuleCRUD;
+import org.opendaylight.controller.networkconfig.neutron.NeutronCRUDInterfaces;
+import org.opendaylight.controller.networkconfig.neutron.NeutronFirewallRule;
+import org.opendaylight.controller.northbound.commons.RestMessages;
+import org.opendaylight.controller.northbound.commons.exception.BadRequestException;
+import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException;
+import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException;
+import org.opendaylight.controller.sal.utils.ServiceHelper;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.DELETE;
+import javax.ws.rs.GET;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * Neutron Northbound REST APIs for Firewall Rule.<br>
+ * This class provides REST APIs for managing neutron Firewall Rule
+ *
+ * <br>
+ * <br>
+ * Authentication scheme : <b>HTTP Basic</b><br>
+ * Authentication realm : <b>opendaylight</b><br>
+ * Transport : <b>HTTP and HTTPS</b><br>
+ * <br>
+ * HTTPS Authentication is disabled by default. Administrator can enable it in
+ * tomcat-server.xml after adding a proper keystore / SSL certificate from a
+ * trusted authority.<br>
+ * More info :
+ * http://tomcat.apache.org/tomcat-7.0-doc/ssl-howto.html#Configuration
+ */
+
+@Path("fw/firewalls_rules")
+public class NeutronFirewallRulesNorthbound {
+
+    private NeutronFirewallRule extractFields(NeutronFirewallRule o, List<String> fields) {
+        return o.extractFields(fields);
+    }
+
+    /**
+     * Returns a list of all Firewall Rules
+     */
+    @GET
+    @Produces({MediaType.APPLICATION_JSON})
+    @StatusCodes({
+            @ResponseCode(code = 200, condition = "Operation successful"),
+            @ResponseCode(code = 401, condition = "Unauthorized"),
+            @ResponseCode(code = 501, condition = "Not Implemented")})
+    public Response listRules(
+            // return fields
+            @QueryParam("fields") List<String> fields,
+            // OpenStack firewall rule attributes
+            @QueryParam("id") String queryFirewallRuleUUID,
+            @QueryParam("tenant_id") String queryFirewallRuleTenantID,
+            @QueryParam("name") String queryFirewallRuleName,
+            @QueryParam("description") String queryFirewallRuleDescription,
+            @QueryParam("admin_state_up") Boolean queryFirewallRuleAdminStateIsUp,
+            @QueryParam("status") String queryFirewallRuleStatus,
+            @QueryParam("shared") Boolean queryFirewallRuleIsShared,
+            @QueryParam("firewall_policy_id") String queryFirewallRulePolicyID,
+            @QueryParam("protocol") String queryFirewallRuleProtocol,
+            @QueryParam("ip_version") Integer queryFirewallRuleIpVer,
+            @QueryParam("source_ip_address") String queryFirewallRuleSrcIpAddr,
+            @QueryParam("destination_ip_address") String queryFirewallRuleDstIpAddr,
+            @QueryParam("source_port") Integer queryFirewallRuleSrcPort,
+            @QueryParam("destination_port") Integer queryFirewallRuleDstPort,
+            @QueryParam("position") Integer queryFirewallRulePosition,
+            @QueryParam("action") String queryFirewallRuleAction,
+            @QueryParam("enabled") Boolean queryFirewallRuleIsEnabled,
+            // pagination
+            @QueryParam("limit") String limit,
+            @QueryParam("marker") String marker,
+            @QueryParam("page_reverse") String pageReverse
+            // sorting not supported
+    ) {
+        INeutronFirewallRuleCRUD firewallRuleInterface = NeutronCRUDInterfaces.getINeutronFirewallRuleCRUD(this);
+        if (firewallRuleInterface == null) {
+            throw new ServiceUnavailableException("Firewall Rule CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+        List<NeutronFirewallRule> allFirewallRules = firewallRuleInterface.getAllNeutronFirewallRules();
+        List<NeutronFirewallRule> ans = new ArrayList<NeutronFirewallRule>();
+        Iterator<NeutronFirewallRule> i = allFirewallRules.iterator();
+        while (i.hasNext()) {
+            NeutronFirewallRule nsr = i.next();
+            if ((queryFirewallRuleUUID == null ||
+                    queryFirewallRuleUUID.equals(nsr.getFirewallRuleUUID())) &&
+                    (queryFirewallRuleTenantID == null ||
+                            queryFirewallRuleTenantID.equals(nsr.getFirewallRuleTenantID())) &&
+                    (queryFirewallRuleName == null ||
+                            queryFirewallRuleName.equals(nsr.getFirewallRuleName())) &&
+                    (queryFirewallRuleDescription == null ||
+                            queryFirewallRuleDescription.equals(nsr.getFirewallRuleDescription())) &&
+                    (queryFirewallRuleAdminStateIsUp == null ||
+                            queryFirewallRuleAdminStateIsUp.equals(nsr.getFirewallRuleAdminStateIsUp())) &&
+                    (queryFirewallRuleStatus == null ||
+                            queryFirewallRuleStatus.equals(nsr.getFirewallRuleStatus())) &&
+                    (queryFirewallRuleIsShared == null ||
+                            queryFirewallRuleIsShared.equals(nsr.getFirewallRuleIsShared())) &&
+                    (queryFirewallRulePolicyID == null ||
+                            queryFirewallRulePolicyID.equals(nsr.getFirewallRulePolicyID())) &&
+                    (queryFirewallRuleProtocol == null ||
+                            queryFirewallRuleProtocol.equals(nsr.getFirewallRuleProtocol())) &&
+                    (queryFirewallRuleIpVer == null ||
+                            queryFirewallRuleIpVer.equals(nsr.getFirewallRuleIpVer())) &&
+                    (queryFirewallRuleSrcIpAddr == null ||
+                            queryFirewallRuleSrcIpAddr.equals(nsr.getFirewallRuleSrcIpAddr())) &&
+                    (queryFirewallRuleDstIpAddr == null ||
+                            queryFirewallRuleDstIpAddr.equals(nsr.getFirewallRuleDstIpAddr())) &&
+                    (queryFirewallRuleSrcPort == null ||
+                            queryFirewallRuleSrcPort.equals(nsr.getFirewallRuleSrcPort())) &&
+                    (queryFirewallRuleDstPort == null ||
+                            queryFirewallRuleDstPort.equals(nsr.getFirewallRuleDstPort())) &&
+                    (queryFirewallRulePosition == null ||
+                            queryFirewallRulePosition.equals(nsr.getFirewallRulePosition())) &&
+                    (queryFirewallRuleAction == null ||
+                            queryFirewallRuleAction.equals(nsr.getFirewallRuleAction())) &&
+                    (queryFirewallRuleIsEnabled == null ||
+                            queryFirewallRuleIsEnabled.equals(nsr.getFirewallRuleIsEnabled()))) {
+                if (fields.size() > 0) {
+                    ans.add(extractFields(nsr, fields));
+                } else {
+                    ans.add(nsr);
+                }
+            }
+        }
+        //TODO: apply pagination to results
+        return Response.status(200).entity(
+                new NeutronFirewallRuleRequest(ans)).build();
+    }
+
+    /**
+     * Returns a specific Firewall Rule
+     */
+
+    @Path("{firewallRuleUUID}")
+    @GET
+    @Produces({MediaType.APPLICATION_JSON})
+    @StatusCodes({
+            @ResponseCode(code = 200, condition = "Operation successful"),
+            @ResponseCode(code = 401, condition = "Unauthorized"),
+            @ResponseCode(code = 404, condition = "Not Found"),
+            @ResponseCode(code = 501, condition = "Not Implemented")})
+    public Response showFirewallRule(@PathParam("firewallRuleUUID") String firewallRuleUUID,
+            // return fields
+            @QueryParam("fields") List<String> fields) {
+        INeutronFirewallRuleCRUD firewallRuleInterface = NeutronCRUDInterfaces.getINeutronFirewallRuleCRUD(this);
+        if (firewallRuleInterface == null) {
+            throw new ServiceUnavailableException("Firewall Rule CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+        if (!firewallRuleInterface.neutronFirewallRuleExists(firewallRuleUUID)) {
+            throw new ResourceNotFoundException("Firewall Rule UUID does not exist.");
+        }
+        if (fields.size() > 0) {
+            NeutronFirewallRule ans = firewallRuleInterface.getNeutronFirewallRule(firewallRuleUUID);
+            return Response.status(200).entity(
+                    new NeutronFirewallRuleRequest(extractFields(ans, fields))).build();
+        } else {
+            return Response.status(200)
+                    .entity(new NeutronFirewallRuleRequest(
+                            firewallRuleInterface.getNeutronFirewallRule(firewallRuleUUID)))
+                    .build();
+        }
+    }
+
+    /**
+     * Creates new Firewall Rule
+     */
+
+    @POST
+    @Produces({MediaType.APPLICATION_JSON})
+    @Consumes({MediaType.APPLICATION_JSON})
+    @StatusCodes({
+            @ResponseCode(code = 201, condition = "Created"),
+            @ResponseCode(code = 400, condition = "Bad Request"),
+            @ResponseCode(code = 401, condition = "Unauthorized"),
+            @ResponseCode(code = 403, condition = "Forbidden"),
+            @ResponseCode(code = 404, condition = "Not Found"),
+            @ResponseCode(code = 409, condition = "Conflict"),
+            @ResponseCode(code = 501, condition = "Not Implemented")})
+    public Response createFirewallRules(final NeutronFirewallRuleRequest input) {
+        INeutronFirewallRuleCRUD firewallRuleInterface = NeutronCRUDInterfaces.getINeutronFirewallRuleCRUD(this);
+        if (firewallRuleInterface == null) {
+            throw new ServiceUnavailableException("Firewall Rule CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+        INeutronFirewallPolicyCRUD firewallPolicyInterface = NeutronCRUDInterfaces.getINeutronFirewallPolicyCRUD(this);
+        if (firewallPolicyInterface == null) {
+            throw new ServiceUnavailableException("Firewall Policy CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+
+        if (input.isSingleton()) {
+            NeutronFirewallRule singleton = input.getSingleton();
+            if (firewallRuleInterface.neutronFirewallRuleExists(singleton.getFirewallRuleUUID())) {
+                throw new BadRequestException("Firewall Rule UUID already exists");
+            }
+            firewallRuleInterface.addNeutronFirewallRule(singleton);
+            Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallRuleAware.class, this, null);
+            if (instances != null) {
+                for (Object instance : instances) {
+                    INeutronFirewallRuleAware service = (INeutronFirewallRuleAware) instance;
+                    int status = service.canCreateNeutronFirewallRule(singleton);
+                    if (status < 200 || status > 299) {
+                        return Response.status(status).build();
+                    }
+                }
+            }
+            // add rule to cache
+            singleton.initDefaults();
+            firewallRuleInterface.addNeutronFirewallRule(singleton);
+            if (instances != null) {
+                for (Object instance : instances) {
+                    INeutronFirewallRuleAware service = (INeutronFirewallRuleAware) instance;
+                    service.neutronFirewallRuleCreated(singleton);
+                }
+            }
+        } else {
+            List<NeutronFirewallRule> bulk = input.getBulk();
+            Iterator<NeutronFirewallRule> i = bulk.iterator();
+            HashMap<String, NeutronFirewallRule> testMap = new HashMap<String, NeutronFirewallRule>();
+            Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallRuleAware.class, this, null);
+            while (i.hasNext()) {
+                NeutronFirewallRule test = i.next();
+
+                /*
+                 *  Verify that the Firewall rule doesn't already exist
+                 */
+
+                if (firewallRuleInterface.neutronFirewallRuleExists(test.getFirewallRuleUUID())) {
+                    throw new BadRequestException("Firewall Rule UUID already exists");
+                }
+                if (testMap.containsKey(test.getFirewallRuleUUID())) {
+                    throw new BadRequestException("Firewall Rule UUID already exists");
+                }
+                if (instances != null) {
+                    for (Object instance : instances) {
+                        INeutronFirewallRuleAware service = (INeutronFirewallRuleAware) instance;
+                        int status = service.canCreateNeutronFirewallRule(test);
+                        if (status < 200 || status > 299) {
+                            return Response.status(status).build();
+                        }
+                    }
+                }
+            }
+            /*
+             * now, each element of the bulk request can be added to the cache
+             */
+            i = bulk.iterator();
+            while (i.hasNext()) {
+                NeutronFirewallRule test = i.next();
+                firewallRuleInterface.addNeutronFirewallRule(test);
+                if (instances != null) {
+                    for (Object instance : instances) {
+                        INeutronFirewallRuleAware service = (INeutronFirewallRuleAware) instance;
+                        service.neutronFirewallRuleCreated(test);
+                    }
+                }
+            }
+        }
+        return Response.status(201).entity(input).build();
+    }
+
+    /**
+     * Updates a Firewall Rule
+     */
+    @Path("{firewallRuleUUID}")
+    @PUT
+    @Produces({MediaType.APPLICATION_JSON})
+    @Consumes({MediaType.APPLICATION_JSON})
+    @StatusCodes({
+            @ResponseCode(code = 200, condition = "Operation successful"),
+            @ResponseCode(code = 400, condition = "Bad Request"),
+            @ResponseCode(code = 401, condition = "Unauthorized"),
+            @ResponseCode(code = 403, condition = "Forbidden"),
+            @ResponseCode(code = 404, condition = "Not Found"),
+            @ResponseCode(code = 501, condition = "Not Implemented")})
+    public Response updateFirewallRule(
+            @PathParam("firewallRuleUUID") String firewallRuleUUID, final NeutronFirewallRuleRequest input) {
+        INeutronFirewallRuleCRUD firewallRuleInterface = NeutronCRUDInterfaces.getINeutronFirewallRuleCRUD(this);
+        if (firewallRuleInterface == null) {
+            throw new ServiceUnavailableException("Firewall Rule CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+        /*
+         * verify the Firewall Rule exists
+         */
+        if (!firewallRuleInterface.neutronFirewallRuleExists(firewallRuleUUID)) {
+            throw new ResourceNotFoundException("Firewall Rule UUID does not exist.");
+        }
+        if (!input.isSingleton()) {
+            throw new BadRequestException("Only singleton edit supported");
+        }
+        NeutronFirewallRule delta = input.getSingleton();
+        NeutronFirewallRule original = firewallRuleInterface.getNeutronFirewallRule(firewallRuleUUID);
+
+        /*
+         * updates restricted by Neutron
+         *
+         */
+        if (delta.getFirewallRuleUUID() != null ||
+                delta.getFirewallRuleTenantID() != null ||
+                delta.getFirewallRuleName() != null ||
+                delta.getFirewallRuleDescription() != null ||
+                delta.getFirewallRuleAdminStateIsUp() != null ||
+                delta.getFirewallRuleStatus() != null ||
+                delta.getFirewallRuleIsShared() != null ||
+                delta.getFirewallRulePolicyID() != null ||
+                delta.getFirewallRuleProtocol() != null ||
+                delta.getFirewallRuleIpVer() != null ||
+                delta.getFirewallRuleSrcIpAddr() != null ||
+                delta.getFirewallRuleDstIpAddr() != null ||
+                delta.getFirewallRuleSrcPort() != null ||
+                delta.getFirewallRuleDstPort() != null ||
+                delta.getFirewallRulePosition() != null ||
+                delta.getFirewallRuleAction() != null ||
+                delta.getFirewallRuleIsEnabled() != null) {
+            throw new BadRequestException("Attribute edit blocked by Neutron");
+        }
+
+        Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallRuleAware.class, this, null);
+        if (instances != null) {
+            for (Object instance : instances) {
+                INeutronFirewallRuleAware service = (INeutronFirewallRuleAware) instance;
+                int status = service.canUpdateNeutronFirewallRule(delta, original);
+                if (status < 200 || status > 299) {
+                    return Response.status(status).build();
+                }
+            }
+        }
+
+        /*
+         * update the object and return it
+         */
+        firewallRuleInterface.updateNeutronFirewallRule(firewallRuleUUID, delta);
+        NeutronFirewallRule updatedFirewallRule = firewallRuleInterface.getNeutronFirewallRule(firewallRuleUUID);
+        if (instances != null) {
+            for (Object instance : instances) {
+                INeutronFirewallRuleAware service = (INeutronFirewallRuleAware) instance;
+                service.neutronFirewallRuleUpdated(updatedFirewallRule);
+            }
+        }
+        return Response.status(200)
+                .entity(new NeutronFirewallRuleRequest(firewallRuleInterface.getNeutronFirewallRule(firewallRuleUUID)))
+                .build();
+    }
+
+    /**
+     * Deletes a Firewall Rule
+     */
+
+    @Path("{firewallRuleUUID}")
+    @DELETE
+    @StatusCodes({
+            @ResponseCode(code = 204, condition = "No Content"),
+            @ResponseCode(code = 401, condition = "Unauthorized"),
+            @ResponseCode(code = 404, condition = "Not Found"),
+            @ResponseCode(code = 409, condition = "Conflict"),
+            @ResponseCode(code = 501, condition = "Not Implemented")})
+    public Response deleteFirewallRule(
+            @PathParam("firewallRuleUUID") String firewallRuleUUID) {
+        INeutronFirewallRuleCRUD firewallRuleInterface = NeutronCRUDInterfaces.getINeutronFirewallRuleCRUD(this);
+        if (firewallRuleInterface == null) {
+            throw new ServiceUnavailableException("Firewall Rule CRUD Interface "
+                    + RestMessages.SERVICEUNAVAILABLE.toString());
+        }
+
+        /*
+         * verify the Firewall Rule exists and it isn't currently in use
+         */
+        if (!firewallRuleInterface.neutronFirewallRuleExists(firewallRuleUUID)) {
+            throw new ResourceNotFoundException("Firewall Rule UUID does not exist.");
+        }
+        if (firewallRuleInterface.neutronFirewallRuleInUse(firewallRuleUUID)) {
+            return Response.status(409).build();
+        }
+        NeutronFirewallRule singleton = firewallRuleInterface.getNeutronFirewallRule(firewallRuleUUID);
+        Object[] instances = ServiceHelper.getGlobalInstances(INeutronFirewallRuleAware.class, this, null);
+        if (instances != null) {
+            for (Object instance : instances) {
+                INeutronFirewallRuleAware service = (INeutronFirewallRuleAware) instance;
+                int status = service.canDeleteNeutronFirewallRule(singleton);
+                if (status < 200 || status > 299) {
+                    return Response.status(status).build();
+                }
+            }
+        }
+
+        /*
+         * remove it and return 204 status
+         */
+        firewallRuleInterface.removeNeutronFirewallRule(firewallRuleUUID);
+        if (instances != null) {
+            for (Object instance : instances) {
+                INeutronFirewallRuleAware service = (INeutronFirewallRuleAware) instance;
+                service.neutronFirewallRuleDeleted(singleton);
+            }
+        }
+        return Response.status(204).build();
+    }
+}
index 3fe03a2dac8de2f64d9ee2b9796befe72ab0e8b1..9abcca7c53466880de769f93324ad09577142bf8 100644 (file)
@@ -8,12 +8,13 @@
 
 package org.opendaylight.controller.networkconfig.neutron.northbound;
 
+import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider;
+
+import javax.ws.rs.core.Application;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Map;
 import java.util.Set;
-import javax.ws.rs.core.Application;
-import org.eclipse.persistence.jaxb.rs.MOXyJsonProvider;
 
 
 /**
@@ -34,6 +35,9 @@ public class NeutronNorthboundRSApplication extends Application {
         classes.add(NeutronFloatingIPsNorthbound.class);
         classes.add(NeutronSecurityGroupsNorthbound.class);
         classes.add(NeutronSecurityRulesNorthbound.class);
+        classes.add(NeutronFirewallNorthbound.class);
+        classes.add(NeutronFirewallPolicyNorthbound.class);
+        classes.add(NeutronFirewallRulesNorthbound.class);
         return classes;
     }
 
index 196982b3610ee6f33f2afc8a4685a905780cdb26..746135891ea5acf3b976ae64421dda9a393c4f07 100644 (file)
@@ -44,6 +44,7 @@
       <plugin>
         <groupId>org.apache.felix</groupId>
         <artifactId>maven-bundle-plugin</artifactId>
+        <version>${bundle.plugin.version}</version>
         <extensions>true</extensions>
         <configuration>
           <instructions>
diff --git a/opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerShell.java b/opendaylight/topologymanager/implementation/src/main/java/org/opendaylight/controller/topologymanager/ITopologyManagerShell.java
new file mode 100644 (file)
index 0000000..22bd9c0
--- /dev/null
@@ -0,0 +1,17 @@
+/**
+* Copyright (c) 2014 Inocybe Technologies, 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.topologymanager;
+
+import java.util.List;
+
+public interface ITopologyManagerShell {
+    public List<String> printUserLink();
+    public List<String> addUserLink(String name, String ncStr1, String ncStr2);
+    public List<String> deleteUserLinkShell(String name);
+    public List<String> printNodeEdges();
+}
index 4ccbb0197d4bf1cdc1e6d2e87ed6e1a547ea0425..80d7083ec0dee0059a8b7c0c33720522b65fb4bc 100644 (file)
@@ -26,6 +26,7 @@ import org.opendaylight.controller.switchmanager.ISwitchManager;
 import org.opendaylight.controller.topologymanager.ITopologyManager;
 import org.opendaylight.controller.topologymanager.ITopologyManagerAware;
 import org.opendaylight.controller.topologymanager.ITopologyManagerClusterWideAware;
+import org.opendaylight.controller.topologymanager.ITopologyManagerShell;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -73,6 +74,7 @@ public class Activator extends ComponentActivatorAbstractBase {
 
             c.setInterface(new String[] { IListenTopoUpdates.class.getName(),
                     ITopologyManager.class.getName(),
+                    ITopologyManagerShell.class.getName(),
                     IConfigurationContainerAware.class.getName(),
                     ICacheUpdateAware.class.getName() }, props);
 
index ff1c026a344d74efa5aa1f1b57e05e60775cd1a4..b0e87c48f3e0812fd2e33c7789e5e916479f6465 100644 (file)
@@ -57,6 +57,7 @@ import org.opendaylight.controller.switchmanager.ISwitchManager;
 import org.opendaylight.controller.topologymanager.ITopologyManager;
 import org.opendaylight.controller.topologymanager.ITopologyManagerAware;
 import org.opendaylight.controller.topologymanager.ITopologyManagerClusterWideAware;
+import org.opendaylight.controller.topologymanager.ITopologyManagerShell;
 import org.opendaylight.controller.topologymanager.TopologyUserLinkConfig;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.FrameworkUtil;
@@ -71,6 +72,7 @@ import org.slf4j.LoggerFactory;
 public class TopologyManagerImpl implements
         ICacheUpdateAware<Object, Object>,
         ITopologyManager,
+        ITopologyManagerShell,
         IConfigurationContainerAware,
         IListenTopoUpdates,
         IObjectReader,
@@ -1010,4 +1012,82 @@ public class TopologyManagerImpl implements
             }
         }
     }
+
+    public List<String> printUserLink() {
+        List<String> result = new ArrayList<String>();
+        for (String name : this.userLinksDB.keySet()) {
+            TopologyUserLinkConfig linkConfig = userLinksDB.get(name);
+            result.add("Name : " + name);
+            result.add(linkConfig.toString());
+            result.add("Edge " + getLinkTuple(linkConfig));
+            result.add("Reverse Edge " + getReverseLinkTuple(linkConfig));
+        }
+        return result;
+    }
+
+    public List<String> addUserLink(String name, String ncStr1, String ncStr2) {
+        List<String> result = new ArrayList<String>();
+        if ((name == null)) {
+            result.add("Please enter a valid Name");
+            return result;
+        }
+
+        if (ncStr1 == null) {
+            result.add("Please enter two node connector strings");
+            return result;
+        }
+        if (ncStr2 == null) {
+            result.add("Please enter second node connector string");
+            return result;
+        }
+
+        NodeConnector nc1 = NodeConnector.fromString(ncStr1);
+        if (nc1 == null) {
+            result.add("Invalid input node connector 1 string: " + ncStr1);
+            return result;
+        }
+        NodeConnector nc2 = NodeConnector.fromString(ncStr2);
+        if (nc2 == null) {
+            result.add("Invalid input node connector 2 string: " + ncStr2);
+            return result;
+        }
+
+        TopologyUserLinkConfig config = new TopologyUserLinkConfig(name, ncStr1, ncStr2);
+        result.add(this.addUserLink(config).toString());
+        return result;
+    }
+
+    public List<String> deleteUserLinkShell(String name) {
+        List<String> result = new ArrayList<String>();
+        if ((name == null)) {
+            result.add("Please enter a valid Name");
+            return result;
+        }
+        this.deleteUserLink(name);
+        return result;
+    }
+
+    public List<String> printNodeEdges() {
+        List<String> result = new ArrayList<String>();
+        Map<Node, Set<Edge>> nodeEdges = getNodeEdges();
+        if (nodeEdges == null) {
+            return result;
+        }
+        Set<Node> nodeSet = nodeEdges.keySet();
+        if (nodeSet == null) {
+            return result;
+        }
+        result.add("        Node                                         Edge");
+        for (Node node : nodeSet) {
+            Set<Edge> edgeSet = nodeEdges.get(node);
+            if (edgeSet == null) {
+                continue;
+            }
+            for (Edge edge : edgeSet) {
+                result.add(node + "             " + edge);
+            }
+        }
+        return result;
+    }
+
 }
diff --git a/opendaylight/topologymanager/shell/pom.xml b/opendaylight/topologymanager/shell/pom.xml
new file mode 100644 (file)
index 0000000..078b55c
--- /dev/null
@@ -0,0 +1,52 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+  <modelVersion>4.0.0</modelVersion>
+  <parent>
+    <groupId>org.opendaylight.controller</groupId>
+    <artifactId>commons.opendaylight</artifactId>
+    <version>1.4.2-SNAPSHOT</version>
+    <relativePath>../../commons/opendaylight</relativePath>
+  </parent>
+  <artifactId>topologymanager.shell</artifactId>
+  <version>${topologymanager.shell.version}</version>
+  <packaging>bundle</packaging>
+  <dependencies>
+    <dependency>
+      <groupId>junit</groupId>
+      <artifactId>junit</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.karaf.shell</groupId>
+      <artifactId>org.apache.karaf.shell.console</artifactId>
+      <version>${karaf.shell.version}</version>
+    </dependency>
+    <dependency>
+      <groupId>org.mockito</groupId>
+      <artifactId>mockito-all</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>topologymanager</artifactId>
+      <version>${topologymanager.version}</version>
+    </dependency>
+  </dependencies>
+
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.felix</groupId>
+        <artifactId>maven-bundle-plugin</artifactId>
+        <version>${bundle.plugin.version}</version>
+        <configuration>
+          <instructions>
+            <Import-Package>org.apache.felix.service.command,
+              org.apache.karaf.shell.commands,
+              org.apache.karaf.shell.console,
+              *</Import-Package>
+          </instructions>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
+
+</project>
diff --git a/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/AddUserLink.java b/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/AddUserLink.java
new file mode 100644 (file)
index 0000000..1565a87
--- /dev/null
@@ -0,0 +1,39 @@
+/**
+* Copyright (c) 2014 Inocybe Technologies, 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.topologymanager.shell;
+
+import org.apache.felix.gogo.commands.Command;
+import org.apache.felix.gogo.commands.Argument;
+import org.apache.karaf.shell.console.OsgiCommandSupport;
+import org.opendaylight.controller.topologymanager.ITopologyManagerShell;
+
+@Command(scope = "topologymanager", name = "addUserLink", description="Adds user link")
+public class AddUserLink extends OsgiCommandSupport{
+    private ITopologyManagerShell topologyManager;
+
+    @Argument(index=0, name="name", description="name", required=true, multiValued=false)
+    String name = null;
+
+    @Argument(index=1, name="ncStr1", description="ncStr1", required=true, multiValued=false)
+    String ncStr1 = null;
+
+    @Argument(index=2, name="ncStr2", description="ncStr2", required=true, multiValued=false)
+    String ncStr2 = null;
+
+    @Override
+    protected Object doExecute() throws Exception {
+        for(String p : topologyManager.addUserLink(name, ncStr1, ncStr2)) {
+            System.out.println(p);
+        }
+        return null;
+    }
+
+    public void setTopologyManager(ITopologyManagerShell topologyManager){
+        this.topologyManager = topologyManager;
+    }
+}
diff --git a/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/DeleteUserLink.java b/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/DeleteUserLink.java
new file mode 100644 (file)
index 0000000..b226c3c
--- /dev/null
@@ -0,0 +1,33 @@
+/**
+* Copyright (c) 2014 Inocybe Technologies, 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.topologymanager.shell;
+
+import org.apache.felix.gogo.commands.Command;
+import org.apache.felix.gogo.commands.Argument;
+import org.apache.karaf.shell.console.OsgiCommandSupport;
+import org.opendaylight.controller.topologymanager.ITopologyManagerShell;
+
+@Command(scope = "topologymanager", name = "deleteUserLink", description="deletes user link")
+public class DeleteUserLink extends OsgiCommandSupport{
+    private ITopologyManagerShell topologyManager;
+
+    @Argument(index=0, name="name", description="name", required=true, multiValued=false)
+    String name = null;
+
+    @Override
+    protected Object doExecute() throws Exception {
+        for(String p : topologyManager.deleteUserLinkShell(name)) {
+            System.out.println(p);
+        }
+        return null;
+    }
+
+    public void setTopologyManager(ITopologyManagerShell topologyManager){
+        this.topologyManager = topologyManager;
+    }
+}
diff --git a/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintNodeEdges.java b/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintNodeEdges.java
new file mode 100644 (file)
index 0000000..9c5e806
--- /dev/null
@@ -0,0 +1,29 @@
+/**
+* Copyright (c) 2014 Inocybe Technologies, 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.topologymanager.shell;
+
+import org.apache.felix.gogo.commands.Command;
+import org.apache.karaf.shell.console.OsgiCommandSupport;
+import org.opendaylight.controller.topologymanager.ITopologyManagerShell;
+
+@Command(scope = "topologymanager", name = "printNodeEdges", description="Prints node edges")
+public class PrintNodeEdges extends OsgiCommandSupport{
+    private ITopologyManagerShell topologyManager;
+
+    @Override
+    protected Object doExecute() throws Exception {
+        for(String p : topologyManager.printNodeEdges()) {
+            System.out.println(p);
+        }
+        return null;
+    }
+
+    public void setTopologyManager(ITopologyManagerShell topologyManager){
+        this.topologyManager = topologyManager;
+    }
+}
diff --git a/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintUserLink.java b/opendaylight/topologymanager/shell/src/main/java/org/opendaylight/controller/topologymanager/shell/PrintUserLink.java
new file mode 100644 (file)
index 0000000..df7ab35
--- /dev/null
@@ -0,0 +1,29 @@
+/**
+* Copyright (c) 2014 Inocybe Technologies, 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.topologymanager.shell;
+
+import org.apache.felix.gogo.commands.Command;
+import org.apache.karaf.shell.console.OsgiCommandSupport;
+import org.opendaylight.controller.topologymanager.ITopologyManagerShell;
+
+@Command(scope = "topologymanager", name = "printUserLink", description="Prints user link")
+public class PrintUserLink extends OsgiCommandSupport{
+    private ITopologyManagerShell topologyManager;
+
+    @Override
+    protected Object doExecute() throws Exception {
+        for(String p : topologyManager.printUserLink()) {
+            System.out.println(p);
+        }
+        return null;
+    }
+
+    public void setTopologyManager(ITopologyManagerShell topologyManager){
+        this.topologyManager = topologyManager;
+    }
+}
diff --git a/opendaylight/topologymanager/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml b/opendaylight/topologymanager/shell/src/main/resources/OSGI-INF/blueprint/blueprint.xml
new file mode 100644 (file)
index 0000000..96b0b10
--- /dev/null
@@ -0,0 +1,33 @@
+<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
+
+    <reference id="topologyManagerRef" interface="org.opendaylight.controller.topologymanager.ITopologyManagerShell"/>
+    <command-bundle xmlns="http://karaf.apache.org/xmlns/shell/v1.1.0">
+
+        <command>
+        <action class="org.opendaylight.controller.topologymanager.shell.AddUserLink">
+            <property name="topologyManager" ref="topologyManagerRef"/>
+            </action>
+        </command>
+
+        <command>
+        <action class="org.opendaylight.controller.topologymanager.shell.DeleteUserLink">
+            <property name="topologyManager" ref="topologyManagerRef"/>
+            </action>
+        </command>
+
+        <command>
+        <action class="org.opendaylight.controller.topologymanager.shell.PrintNodeEdges">
+            <property name="topologyManager" ref="topologyManagerRef"/>
+            </action>
+        </command>
+
+        <command>
+        <action class="org.opendaylight.controller.topologymanager.shell.PrintUserLink">
+            <property name="topologyManager" ref="topologyManagerRef"/>
+            </action>
+        </command>
+
+    </command-bundle>
+
+
+</blueprint>