Merge "Bug 1239 - Clean up and refactor netconf-ssh client"
authorTony Tkacik <ttkacik@cisco.com>
Mon, 21 Jul 2014 08:08:41 +0000 (08:08 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Mon, 21 Jul 2014 08:08:41 +0000 (08:08 +0000)
798 files changed:
features/adsal/pom.xml [new file with mode: 0644]
features/adsal/src/main/resources/features.xml [new file with mode: 0644]
features/base/pom.xml
features/base/src/main/resources/features.xml
features/config/pom.xml [moved from opendaylight/config/feature/pom.xml with 97% similarity]
features/config/src/main/resources/features.xml [new file with mode: 0644]
features/extras/pom.xml [new file with mode: 0644]
features/extras/src/main/resources/features.xml [new file with mode: 0644]
features/mdsal/pom.xml [moved from opendaylight/md-sal/feature/pom.xml with 97% similarity]
features/mdsal/src/main/resources/features.xml [moved from opendaylight/md-sal/feature/src/main/resources/features.xml with 56% similarity]
features/netconf/pom.xml [new file with mode: 0644]
features/netconf/src/main/resources/features.xml [new file with mode: 0644]
features/pom.xml [new file with mode: 0644]
features/protocol-framework/pom.xml [new file with mode: 0644]
features/protocol-framework/src/main/resources/features.xml [new file with mode: 0644]
opendaylight/arphandler/src/main/java/org/opendaylight/controller/arphandler/ARPReply.java
opendaylight/arphandler/src/main/java/org/opendaylight/controller/arphandler/internal/ArpHandler.java
opendaylight/commons/filter-valve/src/main/java/org/opendaylight/controller/filtervalve/cors/jaxb/Context.java
opendaylight/commons/filter-valve/src/main/java/org/opendaylight/controller/filtervalve/cors/model/FilterProcessor.java
opendaylight/commons/filter-valve/src/main/java/org/opendaylight/controller/filtervalve/cors/model/UrlMatcher.java
opendaylight/commons/opendaylight/pom.xml
opendaylight/commons/protocol-framework/src/main/java/org/opendaylight/protocol/framework/AbstractDispatcher.java
opendaylight/config/config-api/src/main/java/org/opendaylight/controller/config/api/jmx/ServiceReferenceMXBean.java [moved from opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceMXBean.java with 87% similarity]
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicWritableWrapper.java
opendaylight/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/jmx/ServiceReferenceMXBeanImpl.java
opendaylight/config/config-manager/src/test/java/org/opendaylight/controller/config/manager/impl/ServiceReferenceRegistryImplTest.java
opendaylight/config/config-module-archetype/src/main/resources/archetype-resources/pom.xml
opendaylight/config/config-module-archetype/src/main/resources/archetype-resources/src/main/yang/__module-name__-impl.yang
opendaylight/config/config-module-archetype/src/main/resources/archetype-resources/src/main/yang/__module-name__.yang
opendaylight/config/config-persister-api/src/main/java/org/opendaylight/controller/config/persist/api/ConfigSnapshotHolder.java
opendaylight/config/config-persister-file-xml-adapter/src/main/java/org/opendaylight/controller/config/persist/storage/file/xml/model/ConfigSnapshot.java
opendaylight/config/config-util/pom.xml
opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigRegistryJMXClient.java
opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigTransactionClient.java
opendaylight/config/config-util/src/main/java/org/opendaylight/controller/config/util/ConfigTransactionJMXClient.java
opendaylight/config/feature/src/main/resources/features.xml [deleted file]
opendaylight/config/pom.xml
opendaylight/config/threadpool-config-impl/src/main/java/org/opendaylight/controller/config/threadpool/util/FlexibleThreadPoolWrapper.java
opendaylight/config/threadpool-config-impl/src/main/java/org/opendaylight/controller/config/yang/threadpool/impl/flexible/FlexibleThreadPoolModule.java
opendaylight/config/threadpool-config-impl/src/main/yang/threadpool-impl-flexible.yang
opendaylight/config/yang-jmx-generator-plugin/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/plugin/gofactory/AbsModuleGeneratedObjectFactory.java
opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ConfigConstants.java
opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntryBuilder.java
opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleUtil.java
opendaylight/config/yang-jmx-generator/src/main/java/org/opendaylight/controller/config/yangjmxgenerator/RuntimeBeanEntry.java
opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/ModuleMXBeanEntryTest.java
opendaylight/config/yang-jmx-generator/src/test/java/org/opendaylight/controller/config/yangjmxgenerator/ServiceInterfaceEntryTest.java
opendaylight/config/yang-test/.gitignore [deleted file]
opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/.gitignore [new file with mode: 0644]
opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/DepTestImplModule.java [deleted file]
opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/DepTestImplModuleFactory.java [deleted file]
opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/IdentityTestModule.java [deleted file]
opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/IdentityTestModuleFactory.java [deleted file]
opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/MultipleDependenciesModuleStub.txt [new file with mode: 0644]
opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/NetconfTestImplModule.java [deleted file]
opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/NetconfTestImplModuleFactory.java [deleted file]
opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/NetconfTestImplModuleStub.txt
opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/TestImplModule.java [deleted file]
opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/TestImplModuleFactory.java [deleted file]
opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/util/NetconfTestImplModuleUtil.java [moved from opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/NetconfTestImplModuleUtil.java with 69% similarity]
opendaylight/config/yang-test/src/main/yang/config-test-impl.yang
opendaylight/config/yang-test/src/test/java/org/opendaylight/controller/config/yang/test/impl/MultipleDependenciesModuleTest.java [new file with mode: 0644]
opendaylight/distribution/opendaylight-karaf/pom.xml
opendaylight/distribution/opendaylight-karaf/src/main/resources/configuration/initial/02-clustering.xml [deleted file]
opendaylight/distribution/opendaylight-karaf/src/main/resources/etc/custom.properties
opendaylight/distribution/opendaylight-karaf/src/main/resources/etc/startup.properties
opendaylight/distribution/opendaylight/pom.xml
opendaylight/distribution/opendaylight/src/main/resources/configuration/config.ini
opendaylight/distribution/opendaylight/src/main/resources/configuration/cors-config.xml
opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/01-md-sal.xml
opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/01-netconf.xml [new file with mode: 0644]
opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/02-clustering.xml [deleted file]
opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/03-toaster-sample.xml
opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/99-netconf-connector.xml
opendaylight/distribution/opendaylight/src/main/resources/configuration/logback.xml
opendaylight/distribution/opendaylight/src/main/resources/functions.sh [new file with mode: 0644]
opendaylight/distribution/opendaylight/src/main/resources/run.bat
opendaylight/distribution/opendaylight/src/main/resources/run.sh
opendaylight/md-sal/compatibility/flow-management-compatibility/src/main/java/org/opendaylight/controller/md/frm/compatibility/FRMRuntimeDataProvider.java
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/ComponentActivator.java
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/FlowProgrammerAdapter.java
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/FromSalConversionsUtils.java
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/InventoryAndReadAdapter.java
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/MDFlowMapping.java
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/NodeMapping.java
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/ToSalConversionsUtils.java
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/adsal/FlowServiceAdapter.java
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/adsal/FlowStatisticsAdapter.java
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/topology/TopologyMapping.java
opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/MDFlowMappingTest.java [new file with mode: 0644]
opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/NodeMappingTest.java
opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/TestFromSalConversionsUtils.java
opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/TestToSalConversionsUtils.java
opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/topology/test/TopologyMappingTest.java [new file with mode: 0644]
opendaylight/md-sal/model/model-flow-base/src/main/java/org/opendaylight/yang/gen/v1/urn/opendaylight/flow/types/port/rev130925/PortNumberBuilder.java [new file with mode: 0644]
opendaylight/md-sal/model/model-flow-base/src/main/yang/opendaylight-match-types.yang
opendaylight/md-sal/model/model-flow-base/src/main/yang/opendaylight-port-types.yang
opendaylight/md-sal/model/model-flow-base/src/main/yang/opendaylight-table-types.yang
opendaylight/md-sal/model/model-flow-management/pom.xml [deleted file]
opendaylight/md-sal/model/model-flow-management/src/main/yang/flow-management.yang [deleted file]
opendaylight/md-sal/model/model-flow-management/src/main/yang/group-management.yang [deleted file]
opendaylight/md-sal/model/model-flow-management/src/main/yang/meter-management.yang [deleted file]
opendaylight/md-sal/model/model-flow-management/src/main/yang/port-management.yang [deleted file]
opendaylight/md-sal/model/model-flow-management/src/main/yang/queue-management.yang [deleted file]
opendaylight/md-sal/model/model-flow-management/src/main/yang/table-management.yang [deleted file]
opendaylight/md-sal/model/model-flow-service/src/main/yang/node-errors.yang
opendaylight/md-sal/model/model-inventory/src/main/yang/opendaylight-inventory.yang
opendaylight/md-sal/model/pom.xml
opendaylight/md-sal/pom.xml
opendaylight/md-sal/remoterpc-routingtable/implementation/pom.xml [deleted file]
opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/RouteChangeListener.java [deleted file]
opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/RoutingTable.java [deleted file]
opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/RoutingTableException.java [deleted file]
opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/SystemException.java [deleted file]
opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/impl/Activator.java [deleted file]
opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/impl/RoutingTableImpl.java [deleted file]
opendaylight/md-sal/remoterpc-routingtable/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/impl/RoutingTableImplTest.java [deleted file]
opendaylight/md-sal/remoterpc-routingtable/integrationtest/pom.xml [deleted file]
opendaylight/md-sal/remoterpc-routingtable/integrationtest/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/impl/ZeroMQRoutingTableTestIT.java [deleted file]
opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/pom.xml [deleted file]
opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/src/main/java/org/opendaylight/controller/tests/zmqroutingtable/rest/RouteIdentifierImpl.java [deleted file]
opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/src/main/java/org/opendaylight/controller/tests/zmqroutingtable/rest/Router.java [deleted file]
opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/src/main/resources/WEB-INF/web.xml [deleted file]
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataBroker.java [deleted file]
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingTransactionChain.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/DataBroker.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/DataChangeListener.java [moved from opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataChangeListener.java with 87% similarity]
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/ReadOnlyTransaction.java [moved from opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataReadTransaction.java with 56% similarity]
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/ReadTransaction.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/ReadWriteTransaction.java [moved from opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataReadWriteTransaction.java with 64% similarity]
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/WriteTransaction.java [moved from opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataWriteTransaction.java with 74% similarity]
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/sal/binding/api/BindingAwareBroker.java
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/sal/binding/api/BindingAwareConsumer.java
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/sal/binding/api/BindingAwareProvider.java
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/sal/binding/api/NotificationListener.java
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/sal/binding/api/NotificationProviderService.java
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/sal/binding/api/NotificationService.java
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/sal/binding/api/RpcConsumerRegistry.java
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/sal/binding/api/RpcProviderRegistry.java
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/sal/binding/api/data/DataBrokerService.java
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/sal/binding/api/data/DataChangeListener.java
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/sal/binding/api/data/DataModificationTransaction.java
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/sal/binding/api/data/DataProviderService.java
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/sal/binding/api/data/DataRefresher.java
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/sal/binding/api/data/RuntimeDataProvider.java
opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/sal/binding/api/data/SynchronizedTransaction.java
opendaylight/md-sal/sal-binding-broker/pom.xml
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingAsyncDataBrokerImplModule.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingAsyncDataBrokerImplModuleFactory.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingBrokerImplModule.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/BindingBrokerImplModuleFactory.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/DataBrokerImplModule.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/DataBrokerImplModuleFactory.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/ForwardedCompatibleDataBrokerImplModule.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/config/yang/md/sal/binding/impl/ForwardedCompatibleDataBrokerImplModuleFactory.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/md/sal/binding/impl/AbstractForwardedTransaction.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractReadWriteTransaction.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractWriteTransaction.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/BindingDataReadTransactionImpl.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/BindingDataReadWriteTransactionImpl.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/BindingDataWriteTransactionImpl.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/BindingToNormalizedNodeCodec.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/BindingTranslatedTransactionChain.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/ForwardedBackwardsCompatibleDataBroker.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/ForwardedBindingDataBroker.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/codegen/impl/BrokerImplClassLoader.java [deleted file]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/codegen/impl/RpcRouterCodegenInstance.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/codegen/impl/RuntimeCodeGenerator.xtend
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/RootBindingAwareBroker.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/RpcProviderRegistryImpl.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/BindingIndependentConnector.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/BindingToDomCommitHandler.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/BindingToDomTransaction.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/DataModificationTracker.java [deleted file]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/DomToBindingCommitHandler.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/DomToBindingNotificationForwarder.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/DomToBindingRpcForwarder.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/DomToBindingRpcForwardingManager.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/DomToBindingTransaction.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/RpcInvocationStrategy.java
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/package-info.java [deleted file]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/util/MapUtils.java [deleted file]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/spi/DelegateProxy.java [deleted file]
opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/spi/remote/RouteChangeListener.java [deleted file]
opendaylight/md-sal/sal-binding-broker/src/main/yang/opendaylight-binding-broker-impl.yang
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/test/BindingNormalizedCodecTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/test/Bug1125RegressionTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/test/ListInsertionDataChangeListenerTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/test/RpcProviderRegistryTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/test/WriteTransactionTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/test/AbstractDataBrokerTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/test/AbstractDataChangeListenerTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/test/AbstractSchemaAwareTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/test/AssertCollections.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/test/DataBrokerTestCustomizer.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/impl/connect/dom/RpcInvocationStrategyTest.java
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/AbstractDataServiceTest.java
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/RuntimeCodeGeneratorTest.java
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/compat/MultipleAugmentationPutsTest.java [moved from opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/bugfix/MultipleAugmentationPutsTest.java with 99% similarity]
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/compat/UnionSerializationTest.java [moved from opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/bugfix/UnionSerializationTest.java with 97% similarity]
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/compat/package-info.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/util/BindingBrokerTestFactory.java
opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/util/BindingTestContext.java
opendaylight/md-sal/sal-binding-config/src/main/yang/opendaylight-md-sal-binding.yang
opendaylight/md-sal/sal-binding-dom-it/pom.xml
opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/md/sal/binding/data/ConcurrentImplicitCreateTest.java
opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/md/sal/binding/data/ListProcessingAndOrderingTest.java
opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/md/sal/binding/data/WildcardedDataChangeListenerTest.java
opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/bugfix/DOMCodecBug01Test.java
opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/bugfix/DOMCodecBug02Test.java
opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/bugfix/DOMCodecBug03Test.java
opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/bugfix/DeleteNestedAugmentationListenParentTest.java
opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/bugfix/FlagsSerializationTest.java
opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/bugfix/PutAugmentationTest.java
opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/bugfix/WriteParentListenAugmentTest.java
opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/bugfix/WriteParentReadChildTest.java
opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/bugfix/package-info.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/connect/dom/BrokerIntegrationTest.java
opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/connect/dom/ChangeOriginatedInDomBrokerTest.java
opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/connect/dom/CrossBrokerMountPointTest.java
opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/connect/dom/CrossBrokerRpcTest.java
opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/connect/dom/DOMRpcServiceTestBugfix560.java [new file with mode: 0644]
opendaylight/md-sal/sal-binding-it/src/main/java/org/opendaylight/controller/test/sal/binding/it/TestHelper.java
opendaylight/md-sal/sal-binding-it/src/test/resources/controller.xml
opendaylight/md-sal/sal-binding-util/src/main/java/org/opendaylight/controller/md/sal/binding/util/TypeSafeDataReader.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncDataBroker.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncDataChangeEvent.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncDataChangeListener.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncDataTransactionFactory.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncReadOnlyTransaction.java [new file with mode: 0644]
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncReadTransaction.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncReadWriteTransaction.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncTransaction.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncWriteTransaction.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataChangeEvent.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataChangeListener.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataChangePublisher.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataCommitHandler.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataCommitHandlerRegistration.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataModification.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataModificationTransactionFactory.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataProvider.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataProvisionService.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataReader.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/DataStore.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/TransactionChain.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/notify/NotificationPublishService.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/routing/RouteChange.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/routing/RouteChangeListener.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/routing/RouteChangePublisher.java
opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/routing/RoutedRegistration.java
opendaylight/md-sal/sal-common-impl/src/main/java/org/opendaylight/controller/md/sal/common/impl/service/TwoPhaseCommit.java
opendaylight/md-sal/sal-common-impl/src/main/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizationOperation.java
opendaylight/md-sal/sal-common-impl/src/main/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizer.java
opendaylight/md-sal/sal-common-impl/src/test/java/org/opendaylight/controller/md/sal/common/impl/util/compat/DataNormalizerTest.java
opendaylight/md-sal/sal-common-util/src/main/java/org/opendaylight/controller/sal/common/util/CommitHandlerTransactions.java
opendaylight/md-sal/sal-common-util/src/main/java/org/opendaylight/controller/sal/common/util/RpcErrors.java
opendaylight/md-sal/sal-common-util/src/main/java/org/opendaylight/controller/sal/common/util/Rpcs.java
opendaylight/md-sal/sal-compability/src/main/java/org/opendaylight/controller/sal/compability/ToSalPropertyClassUtils.java [deleted file]
opendaylight/md-sal/sal-distributed-datastore/pom.xml
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/AbstractUntypedActor.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ActorSystemFactory.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListener.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerProxy.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistration.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistrationProxy.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DistributedDataStore.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreFactory.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ListenerRegistration.java [deleted file]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ListenerRegistrationProxy.java [deleted file]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/Shard.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardManager.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardTransaction.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ShardTransactionChain.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/TerminationMonitor.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ThreePhaseCommitCohort.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ThreePhaseCommitCohortProxy.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/TransactionChainProxy.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/TransactionProxy.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/PrimaryNotFoundException.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/TimeoutException.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/AbortTransaction.java [moved from opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseListenerRegistration.java with 90% similarity]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/AbortTransactionReply.java [moved from opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseListenerRegistrationReply.java with 89% similarity]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CanCommitTransaction.java [moved from opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/CompositeNodeUtils.java with 75% similarity]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CanCommitTransactionReply.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseDataChangeListenerRegistration.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseDataChangeListenerRegistrationReply.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CommitTransaction.java [moved from opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/bugfix/RpcRegistrationNullPointer.java with 74% similarity]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CommitTransactionReply.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CreateTransaction.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CreateTransactionReply.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DataChanged.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DataChangedReply.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ForwardedCommitTransaction.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/Monitor.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/NonPersistent.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PreCommitTransaction.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PreCommitTransactionReply.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PrimaryFound.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ReadyTransactionReply.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/RegisterChangeListener.java
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/AbstractModification.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/CompositeModification.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/DeleteModification.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/ImmutableCompositeModification.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/MergeModification.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/Modification.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/MutableCompositeModification.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/WriteModification.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/utils/ActorContext.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedConfigDataStoreProviderModule.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedConfigDataStoreProviderModuleFactory.java [moved from opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedDataStoreProviderModuleFactory.java with 52% similarity]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedDataStoreProviderModule.java [deleted file]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedOperationalDataStoreProviderModule.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedOperationalDataStoreProviderModuleFactory.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/resources/application.conf [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/main/yang/distributed-datastore-provider.yang
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/AbstractActorTest.java
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/BasicIntegrationTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerProxyTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistrationProxyTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistrationTest.java [moved from opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ListenerRegistrationTest.java with 82% similarity]
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreIntegrationTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreTest.java
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardManagerTest.java
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTest.java
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTransactionChainTest.java
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ShardTransactionTest.java
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ThreePhaseCommitCohortProxyTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/TransactionProxyTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/modification/AbstractModificationTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/modification/DeleteModificationTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/modification/MergeModificationTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/modification/MutableCompositeModificationTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/modification/WriteModificationTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/DoNothingActor.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/MessageCollectorActor.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/MockActorContext.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/TestUtils.java [new file with mode: 0644]
opendaylight/md-sal/sal-distributed-datastore/src/test/resources/application.conf [new file with mode: 0644]
opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMDataBroker.java
opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMDataReadOnlyTransaction.java [new file with mode: 0644]
opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMDataReadTransaction.java
opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMTransactionChain.java
opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/sal/core/api/data/DataBrokerService.java
opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/sal/core/api/data/DataChangeListener.java
opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/sal/core/api/data/DataModificationTransaction.java
opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/sal/core/api/data/DataProviderService.java
opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/sal/core/api/data/DataStore.java
opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/sal/core/api/data/DataValidator.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/DomBrokerImplModuleFactory.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/DomInmemoryDataBrokerModuleFactory.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/AbstractDOMForwardedCompositeTransaction.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/AbstractDOMForwardedTransactionFactory.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMDataCommitCoordinatorImpl.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMForwardedReadOnlyTransaction.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMForwardedWriteTransaction.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/md/sal/dom/broker/impl/compat/BackwardsCompatibleTransaction.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/BrokerConfigActivator.java [deleted file]
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/BrokerImpl.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/ConsumerContextImpl.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/MountPointImpl.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/NotificationModule.java [deleted file]
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/ProviderContextImpl.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/DataReaderRouter.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/GlobalRpcRegistration.java [new file with mode: 0644]
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/HashMapDataStore.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/RoutedRpcRegImpl.java [new file with mode: 0644]
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/RoutedRpcSelector.java [new file with mode: 0644]
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/SchemaAwareDataStoreAdapter.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/SchemaAwareRpcBroker.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/osgi/AbstractBrokerServiceProxy.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/osgi/DOMDataBrokerProxy.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/osgi/SchemaServiceActivator.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/util/YangDataOperations.java
opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/util/YangSchemaUtils.java
opendaylight/md-sal/sal-dom-broker/src/main/yang/opendaylight-dom-broker-impl.yang
opendaylight/md-sal/sal-dom-broker/src/test/java/org/opendaylight/controller/md/sal/dom/broker/impl/DOMTransactionChainTest.java
opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/broker/spi/rpc/RpcRoutingStrategy.java [new file with mode: 0644]
opendaylight/md-sal/sal-inmemory-datastore/pom.xml
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-inmemory-datastore/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/DOMImmutableDataChangeEvent.java
opendaylight/md-sal/sal-inmemory-datastore/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/ResolveDataChangeEventsTask.java
opendaylight/md-sal/sal-inmemory-datastore/src/main/java/org/opendaylight/controller/md/sal/dom/store/impl/tree/ListenerTree.java
opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/AbstractDataChangeListenerTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/DatastoreTestTask.java [new file with mode: 0644]
opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/DefaultDataChangeListenerTestSuite.java [new file with mode: 0644]
opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/InMemoryDataStoreTest.java
opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/RootScopeSubtreeTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/WildcardedScopeBaseTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/WildcardedScopeOneTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/WildcardedScopeSubtreeTest.java [new file with mode: 0644]
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/sal/NetconfDeviceCommitHandler.java
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceDataReader.java
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceRpc.java
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceSalProvider.java
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/sal/NetconfDeviceTwoPhaseCommitTransaction.java
opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/netconf/schema/mapping/NetconfMessageTransformer.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/java/org/opendaylight/controller/sal/connect/util/FailedRpcResult.java [deleted file]
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/NetconfDeviceTest.java
opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfToNotificationTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfToRpcRequestTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-netconf-connector/src/test/resources/notification-payload.xml [new file with mode: 0644]
opendaylight/md-sal/sal-netconf-connector/src/test/resources/schemas/rpc-notification-subscription.yang [new file with mode: 0644]
opendaylight/md-sal/sal-netconf-connector/src/test/resources/schemas/user-notification.yang [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/README-FIRST
opendaylight/md-sal/sal-protocolbuffer-encoding/pom.xml
opendaylight/md-sal/sal-protocolbuffer-encoding/run.sh
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/transaction/ShardTransactionMessages.java [deleted file]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/util/EncoderDecoderUtil.java [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/common/SimpleNormalizedNodeMessage.java [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/datachange/notification/DataChangeListenerMessages.java [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/registration/ListenerRegistrationMessages.java [moved from opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/registration/ListenerRegistrationMessages.java with 68% similarity]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/shard/ShardManagerMessages.java [moved from opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/shard/ShardManagerMessages.java with 72% similarity]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionChainMessages.java [moved from opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/transaction/ShardTransactionChainMessages.java with 70% similarity]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionMessages.java [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/resources/DataChangeListener.proto [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/resources/ListenerRegistration.proto
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/resources/ShardManager.proto
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/resources/ShardTransaction.proto
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/resources/ShardTransactionChain.proto
opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/resources/SimpleNormalizedNode.proto [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/messages/ShardManagerMessagesTest.java [deleted file]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/util/NormalizedNodeXmlConverterTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/util/TestModel.java [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/protobuff/messages/ShardManagerMessagesTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/augment_choice.xml [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/augment_choice.yang [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/odl-datastore-test.yang [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/simple_xml_with_attributes.xml [new file with mode: 0644]
opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/test.yang [new file with mode: 0644]
opendaylight/md-sal/sal-remoterpc-connector/implementation/pom.xml [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/config/yang/md/sal/remote/rpc/ZeroMQServerModule.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/config/yang/md/sal/remote/rpc/ZeroMQServerModuleFactory.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/CapturedMessageHandler.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ClientImpl.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ClientRequestHandler.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/Context.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcClient.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcProvider.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcServer.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RoutingTableProvider.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ServerImpl.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ServerRequestHandler.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/SocketPair.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/dto/Message.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/dto/MessageWrapper.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/dto/RouteIdentifierImpl.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/util/XmlUtils.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/yang/odl-sal-dom-rpc-remote-cfg.yang [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ClientImplTest.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ClientRequestHandlerTest.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/MockRoutingTable.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcProviderTest.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/SerilizationTest.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ServerImplTest.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ServerRequestHandlerTest.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/utils/MessagingUtil.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/utils/RemoteServerTestClient.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/resources/AddFlow.xml [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/resources/FourSimpleChildren.xml [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/resources/logback-test.xml [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/pom.xml [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/java/org/opendaylight/controller/sample/zeromq/consumer/ExampleConsumer.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/FourSimpleChildren.xml [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/InvalidCompositeChild.xml [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/InvalidSimpleChild.xml [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/OneSimpleChild.xml [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/OneSimpleOneCompositeChild.xml [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/TwoCompositeChildren.xml [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/TwoSimpleChildren.xml [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/integrationtest/pom.xml [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/integrationtest/provider-service/pom.xml [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/integrationtest/provider-service/src/main/java/org/opendaylight/controller/sample/zeromq/provider/ExampleProvider.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-it/pom.xml [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-it/src/test/java/org/opendaylight/controller/sample/zeromq/test/it/RouterTest.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-it/src/test/resources/controller.xml [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-it/src/test/resources/logback.xml [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-nb/pom.xml [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-nb/src/main/java/org/opendaylight/controller/tests/zmqrouter/rest/Router.java [deleted file]
opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-nb/src/main/resources/WEB-INF/web.xml [deleted file]
opendaylight/md-sal/sal-rest-connector/pom.xml
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/Draft02.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/RestconfService.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/api/package-info.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/gson/JsonParser.java [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonMapper.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeProvider.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonToCompositeNodeReader.java [moved from opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/JsonReader.java with 52% similarity]
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestUtil.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfApplication.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfDocumentedExceptionMapper.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/RestconfProvider.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToJsonProvider.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/StructuredDataToXmlProvider.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlMapper.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlToCompositeNodeProvider.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlToCompositeNodeReader.java [moved from opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/XmlReader.java with 88% similarity]
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/impl/package-info.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/BrokerFacade.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/CompositeNodeWrapper.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/restconf/impl/EmptyNodeWrapper.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/IdentityValuesDTO.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/InstanceIdWithSchemaNode.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/NodeWrapper.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestCodec.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfDocumentedException.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfError.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/RestconfImpl.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/SimpleNodeWrapper.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/StructuredData.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/impl/package-info.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/AbstractRpcExecutor.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/BrokerRpcExecutor.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/MountPointRpcExecutor.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/restconf/rpc/impl/RpcExecutor.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/ListenerAdapter.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/listeners/Notificator.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServer.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServerHandler.java
opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/streams/websockets/WebSocketServerInitializer.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonBasicYangTypesTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnJsonChoiceCaseTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonBasicDataTypesTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonIdentityrefTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonIncorrectTopLevelTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonLeafrefType.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonNotExistingLeafTypeTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonWithAugmentTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/json/test/CnSnToJsonWithDataFromSeveralModulesTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnInstanceIdentifierToXmlTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlNotExistingLeafTypeTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlWithChoiceTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/cnsn/to/xml/test/CnSnToXmlWithDataFromSeveralModulesTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/input/to/cnsn/test/RestPutListDataTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonIdentityrefToCnSnTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonLeafrefToCnSnTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/json/to/cnsn/test/JsonToCnSnTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/BrokerFacadeTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CnSnToXmlAndJsonInstanceIdentifierTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/CodecsExceptionsCatchingTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyFuture.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyRpcResult.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/DummyType.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/InvokeRpcMethodTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/MediaTypesTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/MultipleEqualNamesForDataNodesTest.java [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/NormalizeNodeTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestCodecExceptionsTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestDeleteOperationTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetAugmentedElementWhenEqualNamesTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestGetOperationTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestPostOperationTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfDocumentedExceptionMapperTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfErrorTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/RestconfImplTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/TestUtils.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/URITest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnInstanceIdentifierTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/XmlAndJsonToCnSnLeafRefTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/YangAndXmlAndDataSchemaLoader.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/structures/LstItem.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/client/WebSocketClient.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/client/WebSocketClientHandler.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/websockets/test/RestStream.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlAugmentedElementToCnSnTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlLeafrefToCnSnTest.java
opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/xml/to/cnsn/test/XmlToCnSnTest.java
opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/simple-data-types/simple-data-types.yang
opendaylight/md-sal/sal-rest-connector/src/test/resources/cnsn-to-json/simple-data-types/xml/data.xml
opendaylight/md-sal/sal-rest-connector/src/test/resources/equal-data-node-names/equal-name-data-for-container.json [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/resources/equal-data-node-names/equal-name-data-for-container.xml [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/resources/equal-data-node-names/equal-name-data-for-leaf.json [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/resources/equal-data-node-names/equal-name-data-for-leaf.xml [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/resources/equal-data-node-names/yang/equal-data-node-names.yang [new file with mode: 0644]
opendaylight/md-sal/sal-rest-connector/src/test/resources/full-versions/test-module/test-module
opendaylight/md-sal/sal-rest-connector/src/test/resources/json-to-cnsn/empty-data1.json
opendaylight/md-sal/sal-rest-connector/src/test/resources/multiple-nodes/multiple-nodes.yang [new file with mode: 0644]
opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/impl/ModelGenerator.java
opendaylight/md-sal/sal-rest-docgen/src/main/java/org/opendaylight/controller/sal/rest/doc/mountpoints/MountPointSwagger.java
opendaylight/md-sal/sal-rest-docgen/src/main/resources/explorer/index.html
opendaylight/md-sal/sal-rest-docgen/src/test/java/org/opendaylight/controller/sal/rest/doc/impl/ApiDocGeneratorTest.java
opendaylight/md-sal/sal-test-model/pom.xml [new file with mode: 0644]
opendaylight/md-sal/sal-test-model/src/main/java/org/opendaylight/controller/md/sal/test/model/util/ListsBindingUtils.java [new file with mode: 0644]
opendaylight/md-sal/sal-test-model/src/main/yang/opendaylight-mdsal-augment-test.yang [new file with mode: 0644]
opendaylight/md-sal/sal-test-model/src/main/yang/opendaylight-mdsal-list-test.yang [new file with mode: 0644]
opendaylight/md-sal/sal-test-model/src/main/yang/opendaylight-sal-test-store.yang [moved from opendaylight/md-sal/sal-binding-dom-it/src/main/yang/opendaylight-sal-test-store.yang with 100% similarity]
opendaylight/md-sal/sal-test-model/src/main/yang/opendaylight-test-routed-rpc.yang [new file with mode: 0644]
opendaylight/md-sal/sal-test-model/src/main/yang/opendaylight-test-rpc-service.yang [new file with mode: 0644]
opendaylight/md-sal/samples/toaster-consumer/pom.xml
opendaylight/md-sal/samples/toaster-consumer/src/main/java/org/opendaylight/controller/config/yang/config/kitchen_service/impl/KitchenServiceModule.java
opendaylight/md-sal/samples/toaster-consumer/src/main/java/org/opendaylight/controller/sample/kitchen/api/KitchenService.java
opendaylight/md-sal/samples/toaster-consumer/src/main/java/org/opendaylight/controller/sample/kitchen/impl/KitchenServiceImpl.java
opendaylight/md-sal/samples/toaster-it/src/test/java/org/opendaylight/controller/sample/toaster/it/ToasterTest.java
opendaylight/md-sal/samples/toaster-it/src/test/resources/controller.xml
opendaylight/md-sal/samples/toaster-it/src/test/resources/logback.xml
opendaylight/md-sal/samples/toaster-provider/src/main/java/org/opendaylight/controller/config/yang/config/toaster_provider/impl/ToasterProviderModule.java
opendaylight/md-sal/samples/toaster-provider/src/main/java/org/opendaylight/controller/sample/toaster/provider/OpendaylightToaster.java
opendaylight/md-sal/samples/toaster-provider/src/main/yang/toaster-provider-impl.yang
opendaylight/md-sal/statistics-manager/src/main/java/org/opendaylight/controller/md/statistics/manager/FlowComparator.java
opendaylight/md-sal/statistics-manager/src/main/java/org/opendaylight/controller/md/statistics/manager/StatisticsRequestScheduler.java
opendaylight/netconf/config-netconf-connector/pom.xml
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/config/ServiceRegistryWrapper.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/mapping/config/Services.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/editconfig/MergeEditConfigStrategy.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/NetconfOperationServiceImpl.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/YangStoreServiceImpl.java
opendaylight/netconf/config-netconf-connector/src/main/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/YangStoreSnapshotImpl.java
opendaylight/netconf/config-netconf-connector/src/test/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/editconfig/MergeEditConfigStrategyTest.java [new file with mode: 0644]
opendaylight/netconf/config-netconf-connector/src/test/java/org/opendaylight/controller/netconf/confignetconfconnector/osgi/NetconfOperationServiceImplTest.java
opendaylight/netconf/config-persister-impl/src/main/java/org/opendaylight/controller/netconf/persist/impl/ConfigPusher.java
opendaylight/netconf/config-persister-impl/src/test/java/org/opendaylight/controller/netconf/persist/impl/osgi/TestingExceptionHandler.java
opendaylight/netconf/netconf-cli/.gitignore [new file with mode: 0644]
opendaylight/netconf/netconf-cli/README [new file with mode: 0644]
opendaylight/netconf/netconf-cli/README_ODL [new file with mode: 0644]
opendaylight/netconf/netconf-cli/pom.xml [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/Cli.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/CommandArgHandlerRegistry.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/Main.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/NetconfDeviceConnectionHandler.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/NetconfDeviceConnectionManager.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/SchemaContextRegistry.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/AbstractCommand.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/Command.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/CommandConstants.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/CommandDispatcher.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/CommandInvocationException.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/input/Input.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/input/InputDefinition.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/local/Close.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/local/Connect.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/local/Disconnect.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/local/Help.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/output/Output.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/output/OutputDefinition.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/remote/RemoteCommand.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/io/BaseConsoleContext.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/io/ConsoleContext.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/io/ConsoleIO.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/io/ConsoleIOImpl.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/io/IOUtil.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/AbstractReader.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/GenericListEntryReader.java [moved from opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/spi/remote/RemoteRpcRouter.java with 51% similarity]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/Reader.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/ReadingException.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/custom/ConfigReader.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/custom/EditContentReader.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/custom/FilterReader.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/custom/PasswordReader.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/AnyXmlReader.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/BasicDataHolderReader.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/ChoiceReader.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/ContainerReader.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/DecisionReader.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/GenericListReader.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/GenericReader.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/LeafListEntryReader.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/LeafReader.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/ListEntryReader.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/SeparatedNodes.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/UnionTypeReader.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/OutFormatter.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/WriteException.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/Writer.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/custom/DataWriter.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/AbstractWriter.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/AugmentationNodeCliSerializer.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/ChoiceNodeCliSerializer.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/CliOutputFromNormalizedNodeSerializerFactory.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/CompositeNodeWriter.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/ContainerNodeCliSerializer.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/LeafNodeCliSerializer.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/LeafSetEntryNodeCliSerializer.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/LeafSetNodeCliSerializer.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/MapEntryNodeCliSerializer.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/MapNodeCliSerializer.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/NodeCliSerializerDispatcher.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/NormalizedNodeWriter.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/resources/logback.xml [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/resources/schema/common/ietf-inet-types.yang [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/resources/schema/common/netconf-cli-ext.yang [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/resources/schema/local/netconf-cli.yang [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/main/resources/schema/remote/ietf-netconf.yang [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/test/java/org/opendaylight/controller/netconf/cli/ConsoleIOTestImpl.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/test/java/org/opendaylight/controller/netconf/cli/NetconfCliTest.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/test/java/org/opendaylight/controller/netconf/cli/ValueForMessages.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/test/java/org/opendaylight/controller/netconf/cli/io/IOUtilTest.java [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/test/resources/schema-context/ietf-inet-types.yang [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/test/resources/schema-context/ietf-netconf.yang [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/test/resources/schema-context/model1.yang [new file with mode: 0644]
opendaylight/netconf/netconf-cli/src/test/resources/schema-context/model2.yang [new file with mode: 0644]
opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfConfigPersisterITTest.java
opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfITSecureTest.java
opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfITTest.java
opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/NetconfMonitoringITTest.java
opendaylight/netconf/netconf-it/src/test/java/org/opendaylight/controller/netconf/it/SSLUtil.java
opendaylight/netconf/netconf-it/src/test/resources/logback-test.xml [moved from opendaylight/netconf/netconf-it/src/test/resources/logback.xml with 83% similarity]
opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/AbstractNetconfSessionNegotiator.java
opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfEOMAggregator.java
opendaylight/netconf/netconf-netty-util/src/main/java/org/opendaylight/controller/netconf/nettyutil/handler/NetconfMessageToXMLEncoder.java
opendaylight/netconf/netconf-util/src/test/resources/netconfMessages/editConfig_merge_multiple-deps1.xml [new file with mode: 0644]
opendaylight/netconf/netconf-util/src/test/resources/netconfMessages/editConfig_merge_multiple-deps2.xml [new file with mode: 0644]
opendaylight/netconf/pom.xml
opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronObject.java [new file with mode: 0644]
opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronNetwork.java
opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronPort.java
opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronRouter.java
opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/NeutronSubnet.java
opendaylight/northbound/commons/pom.xml
opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/NorthboundApplication.java
opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/GenericExceptionMapper.java [new file with mode: 0644]
opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Accessor.java [new file with mode: 0644]
opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/CompareExpression.java [new file with mode: 0644]
opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Expression.java [moved from opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/Constants.java with 65% similarity]
opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/ExpressionBuilder.java [new file with mode: 0644]
opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/IteratableTypeInfo.java [new file with mode: 0644]
opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/LogicalExpression.java [new file with mode: 0644]
opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Query.java [new file with mode: 0644]
opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContext.java [new file with mode: 0644]
opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContextImpl.java [new file with mode: 0644]
opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContextProvider.java [new file with mode: 0644]
opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryException.java [new file with mode: 0644]
opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryImpl.java [new file with mode: 0644]
opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/TypeInfo.java [new file with mode: 0644]
opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Visitor.java [new file with mode: 0644]
opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/WrapperTypeInfo.java [new file with mode: 0644]
opendaylight/northbound/commons/src/main/javacc/fiql.jj [new file with mode: 0644]
opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/BookBean.java [new file with mode: 0644]
opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/ExpresssionTest.java [new file with mode: 0644]
opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/Library.java [new file with mode: 0644]
opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/PersonBean.java [new file with mode: 0644]
opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/QueryContextTest.java [new file with mode: 0644]
opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/ReviewBean.java [new file with mode: 0644]
opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/XMLAccessorTypeTest.java [new file with mode: 0644]
opendaylight/northbound/commons/src/test/resources/logback.xml [moved from opendaylight/md-sal/remoterpc-routingtable/integrationtest/src/test/resources/logback.xml with 61% similarity]
opendaylight/northbound/connectionmanager/pom.xml
opendaylight/northbound/connectionmanager/src/main/java/org/opendaylight/controller/connectionmanager/northbound/ConnectionManagerNorthbound.java
opendaylight/northbound/containermanager/pom.xml
opendaylight/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerManagerNorthbound.java
opendaylight/northbound/containermanager/src/main/java/org/opendaylight/controller/containermanager/northbound/ContainerManagerNorthboundRSApplication.java
opendaylight/northbound/controllermanager/pom.xml
opendaylight/northbound/controllermanager/src/main/java/org/opendaylight/controller/controllermanager/northbound/ControllerManagerNorthbound.java
opendaylight/northbound/flowprogrammer/pom.xml
opendaylight/northbound/flowprogrammer/src/main/java/org/opendaylight/controller/flowprogrammer/northbound/FlowProgrammerNorthbound.java
opendaylight/northbound/hosttracker/pom.xml
opendaylight/northbound/hosttracker/src/main/java/org/opendaylight/controller/hosttracker/northbound/HostTrackerNorthbound.java
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/INeutronRequest.java [new file with mode: 0644]
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNetworkRequest.java
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronNetworksNorthbound.java
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronPortRequest.java
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronPortsNorthbound.java
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSubnetRequest.java
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/NeutronSubnetsNorthbound.java
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/PaginatedNeutronNetworkRequest.java [deleted file]
opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/PaginatedRequestFactory.java [new file with mode: 0644]
opendaylight/northbound/staticrouting/pom.xml
opendaylight/northbound/staticrouting/src/main/java/org/opendaylight/controller/forwarding/staticrouting/northbound/StaticRoutingNorthbound.java
opendaylight/northbound/statistics/pom.xml
opendaylight/northbound/statistics/src/main/java/org/opendaylight/controller/statistics/northbound/StatisticsNorthbound.java
opendaylight/northbound/subnets/pom.xml
opendaylight/northbound/subnets/src/main/java/org/opendaylight/controller/subnets/northbound/SubnetsNorthbound.java
opendaylight/northbound/switchmanager/pom.xml
opendaylight/northbound/switchmanager/src/main/java/org/opendaylight/controller/switchmanager/northbound/SwitchNorthbound.java
opendaylight/northbound/topology/pom.xml
opendaylight/northbound/topology/src/main/java/org/opendaylight/controller/topology/northbound/TopologyNorthboundJAXRS.java
opendaylight/protocol_plugins/openflow/src/main/java/org/opendaylight/controller/protocol_plugin/openflow/internal/DataPacketMuxDemux.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/ARP.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Ethernet.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IEEE8021Q.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IPv4.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDP.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/LLDPTLV.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/Packet.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/TCP.java
opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/packet/UDP.java
opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/ARPTest.java
opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/EthernetTest.java
opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IEEE8021QTest.java
opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/IPv4Test.java
opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/PacketTest.java
opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/TCPTest.java
opendaylight/sal/api/src/test/java/org/opendaylight/controller/sal/packet/UDPTest.java
pom.xml

diff --git a/features/adsal/pom.xml b/features/adsal/pom.xml
new file mode 100644 (file)
index 0000000..0ccb17a
--- /dev/null
@@ -0,0 +1,73 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project>
+  <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>features-adsal</artifactId>
+  <version>${sal.version}</version>
+  <packaging>pom</packaging>
+  <name>Features :: AD-SAL Features</name>
+  <description>AD-SAL Features POM</description>
+  <properties>
+    <features.file>features.xml</features.file>
+  </properties>
+  <dependencies>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>base-features</artifactId>
+      <version>${project.parent.version}</version>
+      <classifier>features</classifier>
+      <type>xml</type>
+      <scope>runtime</scope>
+    </dependency>
+  </dependencies>
+  <build>
+    <resources>
+      <resource>
+        <filtering>true</filtering>
+        <directory>src/main/resources</directory>
+      </resource>
+    </resources>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-resources-plugin</artifactId>
+        <executions>
+          <execution>
+            <id>filter</id>
+            <goals>
+              <goal>resources</goal>
+            </goals>
+            <phase>generate-resources</phase>
+          </execution>
+        </executions>
+      </plugin>
+      <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/${features.file}</file>
+                  <type>xml</type>
+                  <classifier>features</classifier>
+                </artifact>
+              </artifacts>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+    </plugins>
+  </build>
+</project>
diff --git a/features/adsal/src/main/resources/features.xml b/features/adsal/src/main/resources/features.xml
new file mode 100644 (file)
index 0000000..f955315
--- /dev/null
@@ -0,0 +1,47 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<features name="adsal-${project.version}" xmlns="http://karaf.apache.org/xmlns/features/v1.2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+   xsi:schemaLocation="http://karaf.apache.org/xmlns/features/v1.2.0 http://karaf.apache.org/xmlns/features/v1.2.0">
+   <feature name="odl-adsal-all" description="OpenDaylight AD-SAL All Features" version="${sal.version}">
+      <feature version="${sal.version}">odl-adsal-core</feature>
+      <feature version="${sal.networkconfiguration.version}">odl-adsal-networkconfiguration</feature>
+      <feature version="${sal.connection.version}">odl-adsal-connection</feature>
+      <feature version="${clustering.services.version}">odl-adsal-clustering</feature>
+      <feature version="${configuration.version}">odl-adsal-configuration</feature>
+   </feature>
+   <feature name="odl-adsal-core" description="OpenDaylight :: AD-SAL :: Core" version="${sal.version}">
+      <feature>base-felix-dm</feature>
+      <feature>base-dummy-console</feature>
+      <feature version="${project.version}">odl-adsal-thirdparty</feature>
+      <bundle start="true" start-level="35">mvn:org.apache.commons/commons-lang3/${commons.lang3.version}</bundle>
+  <!--    <bundle>mvn:org.osgi/org.osgi.compendium/${osgi.compendium.version}</bundle> -->
+      <bundle>mvn:org.opendaylight.controller/sal/${sal.version}</bundle>
+      <bundle>mvn:org.opendaylight.controller/sal.implementation/${sal.implementation.version}</bundle>
+   </feature>
+   <feature name="odl-adsal-networkconfiguration" description="OpenDaylight :: AD-SAL :: Network Configuration" version="${sal.networkconfiguration.version}">
+      <bundle>mvn:org.opendaylight.controller/sal.networkconfiguration/${sal.networkconfiguration.version}</bundle>
+      <bundle>mvn:org.opendaylight.controller/sal.networkconfiguration.implementation/${sal.networkconfiguration.version}</bundle>
+   </feature>
+   <feature name="odl-adsal-connection" description="OpenDaylight :: AD-SAL :: Connection" version="${sal.connection.version}">
+      <feature>odl-adsal-core</feature>
+      <bundle>mvn:org.opendaylight.controller/sal.connection/${sal.connection.version}</bundle>
+      <bundle>mvn:org.opendaylight.controller/sal.connection.implementation/${sal.connection.version}</bundle>
+   </feature>
+   <feature name="odl-adsal-clustering" description="OpenDaylight :: AD-SAL :: Clustering" version="${clustering.services.version}">
+      <feature>transaction</feature>
+      <feature>base-felix-dm</feature>
+      <feature>base-eclipselink-persistence</feature>
+      <feature version="${sal.version}">odl-adsal-core</feature>
+      <bundle>mvn:org.opendaylight.controller/clustering.services/${clustering.services.version}</bundle>
+      <bundle>mvn:org.opendaylight.controller/clustering.services-implementation/${clustering.services_implementation.version}</bundle>
+      <bundle>mvn:org.opendaylight.controller/clustering.stub/${clustering.stub.version}</bundle>
+   </feature>
+   <feature name="odl-adsal-configuration" description="OpenDaylight :: AD-SAL :: Configuration" version="${configuration.version}">
+      <feature version="${sal.version}">odl-adsal-core</feature>
+      <feature version="${clustering.services.version}">odl-adsal-clustering</feature>
+      <bundle>mvn:org.opendaylight.controller/configuration/${configuration.version}</bundle>
+      <bundle>mvn:org.opendaylight.controller/configuration.implementation/${configuration.implementation.version}</bundle>
+   </feature>
+   <feature name="odl-adsal-thirdparty" description="OpenDaylight :: AD-SAL :: Third-Party Depenencies" version="${project.version}">
+      <bundle>mvn:org.opendaylight.controller/logging.bridge/${logging.bridge.version}</bundle>
+   </feature>
+</features>
index 922b2d6bdfbd7652df204f2e70597a11fc0a76ac..d925f51b948cfe444a77a5875546e6986ec5ca26 100644 (file)
       </resource>
     </resources>
     <plugins>
+      <plugin>
+        <groupId>org.apache.karaf.tooling</groupId>
+        <artifactId>karaf-maven-plugin</artifactId>
+        <version>${karaf.version}</version>
+        <extensions>true</extensions>
+        <executions>
+          <execution>
+            <id>features-create-kar</id>
+            <goals>
+              <goal>features-create-kar</goal>
+            </goals>
+            <configuration>
+              <featuresFile>${project.build.directory}/classes/${features.file}</featuresFile>
+            </configuration>
+          </execution>
+        </executions>
+        <!-- There is no useful configuration for the kar mojo. The features-generate-descriptor mojo configuration may be useful -->
+      </plugin>
       <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-resources-plugin</artifactId>
index dd6eec8222988ed499aff01b2e56cb5163b119c2..b9107b9f62881d1fc2799ddbecc238559add943a 100644 (file)
@@ -79,6 +79,8 @@
    <feature name="base-eclipselink-persistence" description="EclipseLink Persistence API" version="2.0.4.v201112161009">
       <bundle start="true" start-level="35">mvn:eclipselink/javax.persistence/2.0.4.v201112161009</bundle>
       <bundle start="true" start-level="35">mvn:eclipselink/javax.resource/1.5.0.v200906010428</bundle>
+      <bundle start="true" start-level="35">mvn:org.eclipse.persistence/org.eclipse.persistence.moxy/2.5.0</bundle>
+      <bundle start="true" start-level="35">mvn:org.eclipse.persistence/org.eclipse.persistence.core/2.5.0</bundle>
    </feature>
    <feature name="base-gemini-web" description="Gemini Web" version="${geminiweb.version}">
       <feature>http</feature>
       <bundle start="true" start-level="35">mvn:orbit/org.apache.juli.extras/7.0.32.v201211081135</bundle>
       <bundle start="true" start-level="35">mvn:orbit/org.apache.tomcat.api/7.0.32.v201211081135</bundle>
       <bundle start="true" start-level="35">mvn:orbit/org.apache.tomcat.util/7.0.32.v201211201952</bundle>
+      <bundle start="true" start-level="35">wrap:mvn:virgomirror/org.eclipse.jdt.core.compiler.batch/3.8.0.I20120518-2145</bundle>
    </feature>
    <feature name="base-spring" description="Opendaylight Spring Support" version="${spring.version}">
       <bundle>mvn:org.ow2.asm/asm-all/${asm.version}</bundle>
similarity index 97%
rename from opendaylight/config/feature/pom.xml
rename to features/config/pom.xml
index aaf33ccc0fdfb64639ef6feb2c15256443dbca56..01a4ea74a264afcf722d10b6515b5b26313e869c 100644 (file)
@@ -5,6 +5,7 @@
     <groupId>org.opendaylight.controller</groupId>
     <artifactId>config-subsystem</artifactId>
     <version>0.2.5-SNAPSHOT</version>
+    <relativePath>../../opendaylight/config/</relativePath>
   </parent>
   <artifactId>config-features</artifactId>
 
diff --git a/features/config/src/main/resources/features.xml b/features/config/src/main/resources/features.xml
new file mode 100644 (file)
index 0000000..7c11b5b
--- /dev/null
@@ -0,0 +1,82 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<features name="odl-config-${project.version}" xmlns="http://karaf.apache.org/xmlns/features/v1.2.0"
+          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+          xsi:schemaLocation="http://karaf.apache.org/xmlns/features/v1.2.0 http://karaf.apache.org/xmlns/features/v1.2.0">
+  <repository>mvn:org.opendaylight.yangtools/features-yangtools/${yangtools.version}/xml/features</repository>
+  <repository>mvn:org.opendaylight.controller/netconf-features/${netconf.version}/xml/features</repository>
+
+  <feature name='odl-config-startup' version='${project.version}'>
+    <feature version='${project.version}'>odl-config-netconf-connector</feature>
+    <feature version='${project.version}'>odl-config-persister</feature>
+    <feature version='${project.version}'>odl-netconf-impl</feature>
+  </feature>
+
+  <feature name='odl-config-core' version='${project.version}'>
+    <feature version='${yangtools.version}'>yangtools-concepts</feature>
+    <feature version='${yangtools.version}'>yangtools-binding</feature>
+    <feature version='${yangtools.version}'>yangtools-binding-generator</feature>
+    <feature version='${mdsal.version}'>odl-mdsal-commons</feature>
+    <feature version='${project.version}'>odl-config-api</feature>
+    <bundle>mvn:org.opendaylight.controller/config-util/${project.version}</bundle>
+    <bundle>mvn:org.opendaylight.controller/yang-jmx-generator/${project.version}</bundle>
+    <bundle>mvn:org.opendaylight.controller/shutdown-api/${project.version}</bundle>
+    <bundle>mvn:org.opendaylight.controller/shutdown-impl/${project.version}</bundle>
+    <bundle>mvn:org.osgi/org.osgi.core/${osgi.core.version}</bundle>
+    <bundle>wrap:mvn:com.google.guava/guava/${guava.version}</bundle>
+    <bundle>mvn:org.javassist/javassist/${javassist.version}</bundle>
+  </feature>
+  <feature name='odl-config-manager' version='${project.version}'>
+    <feature version='${project.version}'>odl-config-core</feature>
+    <bundle>mvn:org.opendaylight.controller/config-manager/${project.version}</bundle>
+  </feature>
+  <feature name='odl-config-persister' version='${project.version}'>
+    <feature version='${netconf.version}'>odl-netconf-api</feature>
+    <feature version='${project.version}'>odl-config-api</feature>
+    <feature version='${yangtools.version}'>yangtools-binding-generator</feature>
+    <bundle>mvn:org.opendaylight.controller/config-persister-api/${project.version}</bundle>
+    <bundle>mvn:org.opendaylight.controller/config-persister-file-xml-adapter/${project.version}</bundle>
+    <bundle>mvn:org.opendaylight.controller/config-persister-directory-xml-adapter/${project.version}</bundle>
+    <bundle>mvn:org.opendaylight.controller/config-persister-impl/${project.version}</bundle>
+
+    <bundle>mvn:org.opendaylight.controller/netconf-util/${netconf.version}</bundle>
+    <bundle>mvn:org.opendaylight.controller/netconf-mapping-api/${netconf.version}</bundle>
+
+    <bundle>mvn:com.google.guava/guava/${guava.version}</bundle>
+    <bundle>mvn:commons-io/commons-io/${commons.io.version}</bundle>
+    <bundle>mvn:org.apache.commons/commons-lang3/${commons.lang3.version}</bundle>
+    <bundle>mvn:org.eclipse.persistence/org.eclipse.persistence.core/${eclipse.persistence.version}</bundle>
+    <bundle>mvn:org.eclipse.persistence/org.eclipse.persistence.moxy/${eclipse.persistence.version}</bundle>
+  </feature>
+  <feature name='odl-config-api' version='${project.version}'>
+    <bundle>mvn:org.opendaylight.controller/config-api/${project.version}</bundle>
+
+    <!-- yangtools features -->
+    <feature version='${yangtools.version}'>yangtools-concepts</feature>
+    <feature version='${yangtools.version}'>yangtools-binding</feature>
+  </feature>
+
+  <feature name='odl-config-netty-config-api' version='${project.version}'>
+    <bundle>mvn:org.opendaylight.controller/netty-config-api/${project.version}</bundle>
+
+    <!-- netty bundles -->
+    <bundle>mvn:io.netty/netty-transport/${netty.version}</bundle>
+    <bundle>mvn:io.netty/netty-common/${netty.version}</bundle>
+    <bundle>mvn:io.netty/netty-buffer/${netty.version}</bundle>
+
+    <feature version='${project.version}'>odl-config-api</feature>
+  </feature>
+  <feature name='odl-config-netty' version='${project.version}'>
+    <feature version='${project.version}'>odl-config-netty-config-api</feature>
+    <bundle>mvn:org.opendaylight.controller/netty-event-executor-config/${project.version}</bundle>
+    <bundle>mvn:org.opendaylight.controller/netty-threadgroup-config/${project.version}</bundle>
+    <bundle>mvn:org.opendaylight.controller/netty-timer-config/${project.version}</bundle>
+    <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>
+  </feature>
+  <feature name='odl-config-dispatcher' version='${project.version}'>
+      <bundle>mvn:org.opendaylight.controller/netconf-config-dispatcher/${project.version}</bundle>
+  </feature>
+
+</features>
\ No newline at end of file
diff --git a/features/extras/pom.xml b/features/extras/pom.xml
new file mode 100644 (file)
index 0000000..4563190
--- /dev/null
@@ -0,0 +1,81 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project>
+  <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>extras-features</artifactId>
+  <packaging>kar</packaging>
+  <name>${project.artifactId}</name>
+  <description>Base Features POM</description>
+  <properties>
+    <features.file>features.xml</features.file>
+    <netty3.version>3.9.2.Final</netty3.version>
+  </properties>
+  <build>
+    <resources>
+      <resource>
+        <filtering>true</filtering>
+        <directory>src/main/resources</directory>
+      </resource>
+    </resources>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.karaf.tooling</groupId>
+        <artifactId>karaf-maven-plugin</artifactId>
+        <version>${karaf.version}</version>
+        <extensions>true</extensions>
+        <executions>
+          <execution>
+            <id>features-create-kar</id>
+            <goals>
+              <goal>features-create-kar</goal>
+            </goals>
+            <configuration>
+              <featuresFile>${project.build.directory}/classes/${features.file}</featuresFile>
+            </configuration>
+          </execution>
+        </executions>
+        <!-- There is no useful configuration for the kar mojo. The features-generate-descriptor mojo configuration may be useful -->
+      </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-resources-plugin</artifactId>
+        <executions>
+          <execution>
+            <id>filter</id>
+            <goals>
+              <goal>resources</goal>
+            </goals>
+            <phase>generate-resources</phase>
+          </execution>
+        </executions>
+      </plugin>
+      <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/${features.file}</file>
+                  <type>xml</type>
+                  <classifier>features</classifier>
+                </artifact>
+              </artifacts>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+    </plugins>
+  </build>
+</project>
diff --git a/features/extras/src/main/resources/features.xml b/features/extras/src/main/resources/features.xml
new file mode 100644 (file)
index 0000000..3be66d9
--- /dev/null
@@ -0,0 +1,34 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<features name="extras-features-${project.version}" xmlns="http://karaf.apache.org/xmlns/features/v1.0.0">
+
+   <feature name="osgi-compendium" description="OSGi compendium feature" version="${osgi.version}" resolver="(obr)">
+      <bundle start-level="10">mvn:org.osgi/org.osgi.compendium/${osgi.compendium.version}</bundle>
+   </feature>
+
+   <feature name="odl-extras-scala" description="Scala Runtime for OpenDaylight" version="${scala.version}" resolver="(obr)" start-level="10">
+      <bundle>mvn:org.scala-lang/scala-library/${scala.version}.${scala.micro.version}</bundle>
+      <bundle>mvn:org.scala-lang/scala-reflect/${scala.version}.${scala.micro.version}</bundle>
+   </feature>
+
+   <feature name="odl-extras-akka-system" description="Akka Actor Framework System Bundles" version="${akka.version}" resolver="(obr)" start-level="15">
+      <feature version="${scala.version}">odl-extras-scala</feature>
+      <bundle dependency="true">mvn:com.typesafe/config/${typesafe.config.version}</bundle>
+      <bundle dependency="true">mvn:com.typesafe.akka/akka-actor_${scala.version}/${akka.version}</bundle>
+      <bundle dependency="true">mvn:com.typesafe.akka/akka-slf4j_${scala.version}/${akka.version}</bundle>
+      <bundle>mvn:com.typesafe.akka/akka-osgi_${scala.version}/${akka.version}</bundle>
+   </feature>
+
+   <feature name="odl-extras-akka-clustering" description="Akka Clustering Support" version="${akka.version}" resolver="(obr)" start-level="20">
+      <feature version="${akka.version}">odl-extras-akka-system</feature>
+      <bundle dependency="true">wrap:mvn:org.uncommons.maths/uncommons-maths/${uncommons.maths.version}</bundle>
+      <bundle dependency="true">mvn:com.google.protobuf/protobuf-java/${protobuf.version}</bundle>
+      <bundle dependency="true">wrap:mvn:io.netty/netty/${netty3.version}</bundle>
+      <bundle>mvn:com.typesafe.akka/akka-remote_${scala.version}/${akka.version}</bundle>
+      <bundle>mvn:com.typesafe.akka/akka-cluster_${scala.version}/${akka.version}</bundle>
+   </feature>
+
+   <feature name='odl-extras-leveldb' description='LevelDB feature' version='0.7' resolver='(obr)'>
+      <bundle start-level="20">wrap:mvn:org.iq80.leveldb/leveldb/${leveldb.version}</bundle>
+      <bundle start-level="20">wrap:mvn:org.fusesource.leveldbjni/leveldbjni-all/${leveldbjni.version}</bundle>
+   </feature>
+</features>
similarity index 97%
rename from opendaylight/md-sal/feature/pom.xml
rename to features/mdsal/pom.xml
index c08c3e5606023bcc9cbd4c6780287135a7dd32ab..2983c5efab8fb21031991fe6af248032eb842365 100644 (file)
@@ -5,6 +5,7 @@
     <groupId>org.opendaylight.controller</groupId>
     <artifactId>sal-parent</artifactId>
     <version>1.1-SNAPSHOT</version>
+    <relativePath>../../opendaylight/md-sal</relativePath>
   </parent>
   <artifactId>mdsal-features</artifactId>
 
similarity index 56%
rename from opendaylight/md-sal/feature/src/main/resources/features.xml
rename to features/mdsal/src/main/resources/features.xml
index 16b457403740b7cac4f3fc137e1a1a9d00db4521..7d393bc64cdc7aab9056043d8b1f852260dcfe27 100644 (file)
@@ -9,20 +9,20 @@
         <feature version='${project.version}'>odl-mdsal-restconf</feature>
     </feature>
     <feature name='odl-mdsal-commons' version='${project.version}'>
-        <feature version='${yangtools.version}'>yangtools-concepts</feature>
-        <feature version='${yangtools.version}'>yangtools-binding</feature>
+        <feature version='${yangtools.version}'>yangtools-data-binding</feature>
         <bundle>mvn:org.opendaylight.controller/sal-common/${project.version}</bundle>
         <bundle>mvn:org.opendaylight.controller/sal-common-api/${project.version}</bundle>
         <bundle>mvn:org.opendaylight.controller/sal-common-impl/${project.version}</bundle>
         <bundle>mvn:org.opendaylight.controller/sal-common-util/${project.version}</bundle>
-        <bundle>wrap:mvn:com.google.guava/guava/${guava.version}</bundle>
-        <bundle>wrap:mvn:org.eclipse.xtend/org.eclipse.xtend.lib/${xtend.version}</bundle>
     </feature>
     <feature name='odl-mdsal-broker' version='${project.version}'>
         <feature version='${yangtools.version}'>yangtools-concepts</feature>
         <feature version='${yangtools.version}'>yangtools-binding</feature>
         <feature version='${mdsal.version}'>odl-mdsal-commons</feature>
-        <feature version='${config.version}'>odl-config-subsystem</feature>
+        <feature version='${config.version}'>odl-config-core</feature>
+        <feature version='${config.version}'>odl-config-manager</feature>
+        <feature version='${config.version}'>odl-config-api</feature>
+        <feature version='${config.version}'>odl-config-persister</feature>
         <bundle>mvn:org.opendaylight.controller/sal-core-api/${project.version}</bundle>
         <bundle>mvn:org.opendaylight.controller/sal-core-spi/${project.version}</bundle>
         <bundle>mvn:org.opendaylight.controller/sal-broker-impl/${project.version}</bundle>
@@ -31,6 +31,7 @@
         <bundle>mvn:org.opendaylight.controller/sal-binding-broker-impl/${project.version}</bundle>
         <bundle>mvn:org.opendaylight.controller/sal-binding-util/${project.version}</bundle>
         <bundle>mvn:org.opendaylight.controller/sal-connector-api/${project.version}</bundle>
+        <bundle>mvn:org.opendaylight.controller/sal-inmemory-datastore/${project.version}</bundle>
     </feature>
     <feature name='odl-mdsal-restconf' version='${project.version}'>
         <feature version='${mdsal.version}'>odl-mdsal-broker</feature>
         <bundle>wrap:mvn:io.netty/netty-handler/${netty.version}</bundle>
         <bundle>wrap:mvn:io.netty/netty-transport/${netty.version}</bundle>
     </feature>
+    <feature name='odl-mdsal-model' version='${project.version}'>
+        <bundle>mvn:org.opendaylight.controller.model/model-flow-base/${project.version}</bundle>
+        <bundle>mvn:org.opendaylight.controller.model/model-flow-management/${project.version}</bundle>
+        <bundle>mvn:org.opendaylight.controller.model/model-flow-service/${project.version}</bundle>
+        <bundle>mvn:org.opendaylight.controller.model/model-flow-statistics/${project.version}</bundle>
+        <bundle>mvn:org.opendaylight.controller.model/model-inventory/${project.version}</bundle>
+        <bundle>mvn:org.opendaylight.controller.model/model-topology/${project.version}</bundle>
+    </feature>
+    <feature name='odl-mdsal-toaster' version='${project.version}'>
+        <feature version='${yangtools.version}'>yangtools-concepts</feature>
+        <feature version='${yangtools.version}'>yangtools-binding</feature>
+        <feature version='${project.version}'>odl-mdsal-broker</feature>
+        <feature version='${project.version}'>odl-mdsal-all</feature>
+        <bundle>mvn:org.opendaylight.controller.samples/sample-toaster/${project.version}</bundle>
+        <bundle>mvn:org.opendaylight.controller.samples/sample-toaster-consumer/${project.version}</bundle>
+        <bundle>mvn:org.opendaylight.controller.samples/sample-toaster-provider/${project.version}</bundle>
+    </feature>
+    <feature name='odl-mdsal-misc' version='${project.version}'>
+        <bundle>mvn:org.opendaylight.controller/sal-netconf-connector/${project.version}</bundle>
+        <bundle>mvn:org.opendaylight.controller/sal-restconf-broker/${project.version}</bundle>
+        <bundle>mvn:org.opendaylight.controller/sal-remote/${project.version}</bundle>
+        <bundle>mvn:org.opendaylight.controller.md/topology-manager/${project.version}</bundle>
+        <bundle>mvn:org.opendaylight.controller.md/topology-lldp-discovery/${project.version}</bundle>
+        <bundle>mvn:org.opendaylight.controller.md/statistics-manager/${project.version}</bundle>
+        <bundle>mvn:org.opendaylight.controller.md/inventory-manager/${project.version}</bundle>
+        <bundle>mvn:org.opendaylight.controller.md/forwardingrules-manager/${project.version}</bundle>
+    </feature>
+
 </features>
diff --git a/features/netconf/pom.xml b/features/netconf/pom.xml
new file mode 100644 (file)
index 0000000..457fc64
--- /dev/null
@@ -0,0 +1,71 @@
+<?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>netconf-subsystem</artifactId>
+    <version>0.2.5-SNAPSHOT</version>
+    <relativePath>../../opendaylight/netconf</relativePath>
+  </parent>
+  <artifactId>netconf-features</artifactId>
+
+  <packaging>pom</packaging>
+
+  <properties>
+    <features.file>features.xml</features.file>
+  </properties>
+
+  <dependencies></dependencies>
+
+  <build>
+    <resources>
+      <resource>
+        <filtering>true</filtering>
+        <directory>src/main/resources</directory>
+      </resource>
+    </resources>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-resources-plugin</artifactId>
+        <executions>
+          <execution>
+            <id>filter</id>
+            <goals>
+              <goal>resources</goal>
+            </goals>
+            <phase>generate-resources</phase>
+          </execution>
+        </executions>
+      </plugin>
+      <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/${features.file}</file>
+                  <type>xml</type>
+                  <classifier>features</classifier>
+                </artifact>
+              </artifacts>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+    </plugins>
+  </build>
+  <scm>
+    <connection>scm:git:ssh://git.opendaylight.org:29418/controller.git</connection>
+    <developerConnection>scm:git:ssh://git.opendaylight.org:29418/controller.git</developerConnection>
+    <tag>HEAD</tag>
+    <url>https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL</url>
+  </scm>
+</project>
diff --git a/features/netconf/src/main/resources/features.xml b/features/netconf/src/main/resources/features.xml
new file mode 100644 (file)
index 0000000..50a537b
--- /dev/null
@@ -0,0 +1,59 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<features name="odl-netconf-${project.version}" xmlns="http://karaf.apache.org/xmlns/features/v1.2.0"
+          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+          xsi:schemaLocation="http://karaf.apache.org/xmlns/features/v1.2.0 http://karaf.apache.org/xmlns/features/v1.2.0">
+  <repository>mvn:org.opendaylight.controller/features-odl-protocol-framework/${protocol-framework.version}/xml/features</repository>
+  <repository>mvn:org.opendaylight.controller/config-features/${config.version}/xml/features</repository>
+
+  <feature name='odl-netconf-api' version='${project.version}'>
+    <bundle>mvn:org.opendaylight.controller/netconf-api/${project.version}</bundle>
+    <bundle>mvn:org.opendaylight.controller/ietf-netconf-monitoring/${project.version}</bundle>
+    <bundle>mvn:org.opendaylight.controller/ietf-netconf-monitoring-extension/${project.version}</bundle>
+    <feature version='${protocol-framework.version}'>odl-protocol-framework</feature>
+    <bundle>mvn:org.opendaylight.yangtools.model/ietf-inet-types/${ietf-inet-types.version}</bundle>
+    <bundle>mvn:org.opendaylight.yangtools.model/ietf-yang-types/${ietf-yang-types.version}</bundle>
+  </feature>
+  <feature name='odl-netconf-mapping-api' version='${project.version}'>
+    <feature version='${project.version}'>odl-netconf-api</feature>
+    <bundle>mvn:org.opendaylight.controller/netconf-mapping-api/${project.version}</bundle>
+  </feature>
+  <feature name='odl-netconf-util' version='${project.version}'>
+    <feature version='${project.version}'>odl-netconf-mapping-api</feature>
+    <bundle>mvn:org.opendaylight.controller/netconf-util/${project.version}</bundle>
+  </feature>
+  <feature name='odl-config-netconf-connector' version='${project.version}'>
+    <feature version='${config.version}'>odl-config-manager</feature>
+    <bundle>mvn:org.opendaylight.controller/config-netconf-connector/${project.version}</bundle>
+    <feature version='${project.version}'>odl-netconf-api</feature>
+    <feature version='${project.version}'>odl-netconf-mapping-api</feature>
+    <feature version='${project.version}'>odl-netconf-util</feature>
+  </feature>
+
+  <feature name='odl-netconf-impl' version='${project.version}'>
+    <bundle>mvn:org.opendaylight.controller/netconf-impl/${project.version}</bundle>
+    <feature version='${project.version}'>odl-netconf-api</feature>
+    <feature version='${project.version}'>odl-netconf-mapping-api</feature>
+    <feature version='${project.version}'>odl-netconf-util</feature>
+    <feature version='${project.version}'>odl-netconf-netty-util</feature>
+  </feature>
+  <feature name='odl-netconf-netty-util' version='${project.version}'>
+    <bundle>mvn:org.opendaylight.controller/netconf-netty-util/${project.version}</bundle>
+    <feature version='${project.version}'>odl-netconf-api</feature>
+    <feature version='${project.version}'>odl-netconf-mapping-api</feature>
+    <feature version='${project.version}'>odl-netconf-util</feature>
+    <bundle>mvn:org.opendaylight.controller.thirdparty/ganymed/${ganymed.version}</bundle>
+    <bundle>mvn:org.openexi/nagasena/${exi.nagasena.version}</bundle>
+    <bundle>mvn:io.netty/netty-codec/${netty.version}</bundle>
+    <bundle>mvn:io.netty/netty-handler/${netty.version}</bundle>
+    <bundle>mvn:io.netty/netty-common/${netty.version}</bundle>
+    <bundle>mvn:io.netty/netty-buffer/${netty.version}</bundle>
+    <bundle>mvn:io.netty/netty-transport/${netty.version}</bundle>
+  </feature>
+  <feature name='odl-netconf-misc' version='${project.version}'>
+    <bundle>mvn:org.opendaylight.controller/netconf-client/${project.version}</bundle>
+    <bundle>mvn:org.opendaylight.controller/netconf-monitoring/${project.version}</bundle>
+    <bundle>mvn:org.opendaylight.controller/netconf-tcp/${project.version}</bundle>
+  </feature>
+
+</features>
\ No newline at end of file
diff --git a/features/pom.xml b/features/pom.xml
new file mode 100644 (file)
index 0000000..dce47fa
--- /dev/null
@@ -0,0 +1,21 @@
+<?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>features-controller</artifactId>
+  <packaging>pom</packaging>
+  <prerequisites>
+    <maven>3.0</maven>
+  </prerequisites>
+  <modules>
+    <module>config</module>
+    <module>mdsal</module>
+    <module>netconf</module>
+    <module>protocol-framework</module>
+  </modules>
+</project>
diff --git a/features/protocol-framework/pom.xml b/features/protocol-framework/pom.xml
new file mode 100644 (file)
index 0000000..f0208d6
--- /dev/null
@@ -0,0 +1,71 @@
+<?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>features-odl-protocol-framework</artifactId>
+  <version>${protocol-framework.version}</version>
+  <packaging>pom</packaging>
+
+  <properties>
+    <features.file>features.xml</features.file>
+  </properties>
+
+  <dependencies></dependencies>
+
+  <build>
+    <resources>
+      <resource>
+        <filtering>true</filtering>
+        <directory>src/main/resources</directory>
+      </resource>
+    </resources>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-resources-plugin</artifactId>
+        <executions>
+          <execution>
+            <id>filter</id>
+            <goals>
+              <goal>resources</goal>
+            </goals>
+            <phase>generate-resources</phase>
+          </execution>
+        </executions>
+      </plugin>
+      <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/${features.file}</file>
+                  <type>xml</type>
+                  <classifier>features</classifier>
+                </artifact>
+              </artifacts>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+    </plugins>
+  </build>
+  <scm>
+    <connection>scm:git:ssh://git.opendaylight.org:29418/controller.git</connection>
+    <developerConnection>scm:git:ssh://git.opendaylight.org:29418/controller.git</developerConnection>
+    <tag>HEAD</tag>
+    <url>https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL</url>
+  </scm>
+</project>
diff --git a/features/protocol-framework/src/main/resources/features.xml b/features/protocol-framework/src/main/resources/features.xml
new file mode 100644 (file)
index 0000000..d2560f5
--- /dev/null
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<features name="odl-protocol-framework-${protocol-framework.version}" xmlns="http://karaf.apache.org/xmlns/features/v1.2.0"
+          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+          xsi:schemaLocation="http://karaf.apache.org/xmlns/features/v1.2.0 http://karaf.apache.org/xmlns/features/v1.2.0">
+  <repository>mvn:org.opendaylight.controller/config-features/${config.version}/xml/features</repository>
+  <feature name='odl-protocol-framework' version='${project.version}'>
+    <bundle>mvn:org.opendaylight.controller/protocol-framework/${protocol-framework.version}</bundle>
+    <feature version='${config.version}'>odl-config-api</feature> <!-- needed by netty-config-api -->
+    <feature version='${config.version}'>odl-config-netty-config-api</feature> <!-- needed by netty-config-api -->
+  </feature>
+</features>
\ No newline at end of file
index a6ee60f65d14b5f47b6f7a6cc2db9331f6847d51..1a446b83db92fe1a690e8ac94f181b6bf75705ac 100644 (file)
@@ -23,14 +23,17 @@ public class ARPReply extends ARPEvent {
     private final byte[] tMac;
     private final byte[] sMac;
     private final InetAddress sIP;
+    private final short vlan;
 
     @Override
     public int hashCode() {
         final int prime = 31;
         int result = super.hashCode();
+        result = prime * result + ((port == null) ? 0 : port.hashCode());
         result = prime * result + ((sIP == null) ? 0 : sIP.hashCode());
         result = prime * result + Arrays.hashCode(sMac);
         result = prime * result + Arrays.hashCode(tMac);
+        result = prime * result + vlan;
         return result;
     }
 
@@ -39,13 +42,20 @@ public class ARPReply extends ARPEvent {
         if (this == obj) {
             return true;
         }
-        if (obj == null) {
+        if (!super.equals(obj)) {
             return false;
         }
         if (!(obj instanceof ARPReply)) {
             return false;
         }
         ARPReply other = (ARPReply) obj;
+        if (port == null) {
+            if (other.port != null) {
+                return false;
+            }
+        } else if (!port.equals(other.port)) {
+            return false;
+        }
         if (sIP == null) {
             if (other.sIP != null) {
                 return false;
@@ -59,23 +69,28 @@ public class ARPReply extends ARPEvent {
         if (!Arrays.equals(tMac, other.tMac)) {
             return false;
         }
+        if (vlan != other.vlan) {
+            return false;
+        }
         return true;
     }
 
-    public ARPReply(NodeConnector port, InetAddress sIP, byte[] sMAC, InetAddress tIP, byte[] tMAC) {
+    public ARPReply(NodeConnector port, InetAddress sIP, byte[] sMAC, InetAddress tIP, byte[] tMAC, short vlan) {
         super(tIP);
         this.tMac = tMAC;
         this.sIP = sIP;
         this.sMac = sMAC;
         this.port = port;
+        this.vlan = vlan;
     }
 
-    public ARPReply(InetAddress tIP, byte[] tMAC) {
+    public ARPReply(InetAddress tIP, byte[] tMAC, short vlan) {
         super(tIP);
         this.tMac = tMAC;
         this.sIP = null;
         this.sMac = null;
         this.port = null;
+        this.vlan = vlan;
     }
 
     public byte[] getTargetMac() {
@@ -94,6 +109,10 @@ public class ARPReply extends ARPEvent {
         return port;
     }
 
+    public short getVlan() {
+        return vlan;
+    }
+
     /*
      * (non-Javadoc)
      *
@@ -122,6 +141,10 @@ public class ARPReply extends ARPEvent {
             builder.append("sIP=")
                     .append(sIP);
         }
+        if (vlan != 0) {
+            builder.append(", vlan=")
+            .append(vlan);
+        }
         builder.append("]");
         return builder.toString();
     }
index e5491824397c1678b26b819b4e2691d0295f95a6..4efcada2f8ed9ef7fd0d2774c5b41cfb6e265ba1 100644 (file)
@@ -49,12 +49,12 @@ import org.opendaylight.controller.sal.core.NodeConnector;
 import org.opendaylight.controller.sal.packet.ARP;
 import org.opendaylight.controller.sal.packet.Ethernet;
 import org.opendaylight.controller.sal.packet.IDataPacketService;
+import org.opendaylight.controller.sal.packet.IEEE8021Q;
 import org.opendaylight.controller.sal.packet.IListenDataPacket;
 import org.opendaylight.controller.sal.packet.IPv4;
 import org.opendaylight.controller.sal.packet.Packet;
 import org.opendaylight.controller.sal.packet.PacketResult;
 import org.opendaylight.controller.sal.packet.RawPacket;
-import org.opendaylight.controller.sal.routing.IRouting;
 import org.opendaylight.controller.sal.utils.EtherTypes;
 import org.opendaylight.controller.sal.utils.HexEncode;
 import org.opendaylight.controller.sal.utils.NetUtils;
@@ -96,7 +96,6 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA
     private ISwitchManager switchManager;
     private ITopologyManager topologyManager;
     private IDataPacketService dataPacketService;
-    private IRouting routing;
     private IClusterContainerServices clusterContainerService;
     private IConnectionManager connectionManager;
     private Set<IfHostListener> hostListeners = new CopyOnWriteArraySet<IfHostListener>();
@@ -182,7 +181,7 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA
         }
     }
 
-    protected void sendARPReply(NodeConnector p, byte[] sMAC, InetAddress sIP, byte[] tMAC, InetAddress tIP) {
+    protected void sendARPReply(NodeConnector p, byte[] sMAC, InetAddress sIP, byte[] tMAC, InetAddress tIP, short vlan) {
         byte[] senderIP = sIP.getAddress();
         byte[] targetIP = tIP.getAddress();
         ARP arp = createARP(ARP.REPLY, sMAC, senderIP, tMAC, targetIP);
@@ -193,7 +192,7 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA
                     sIP, HexEncode.bytesToHexString(tMAC), tIP, p);
         }
 
-        Ethernet ethernet = createEthernet(sMAC, tMAC, arp);
+        Ethernet ethernet = createEthernet(sMAC, tMAC, arp, vlan);
 
         RawPacket destPkt = this.dataPacketService.encodeDataPacket(ethernet);
         destPkt.setOutgoingNodeConnector(p);
@@ -201,26 +200,24 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA
         this.dataPacketService.transmitDataPacket(destPkt);
     }
 
-    private void logArpPacket(ARP pkt, NodeConnector p) {
+    private void logArpPacket(ARP pkt, NodeConnector p, short vlan) {
         try {
-            if (pkt.getOpCode() == ARP.REQUEST) {
-                log.trace("Received Arp Request with srcMac {} - srcIp {} - dstMac {} - dstIp {} - inport {}", HexEncode.bytesToHexString(pkt.getSenderHardwareAddress()),
-                        InetAddress.getByAddress(pkt.getSenderProtocolAddress()), HexEncode.bytesToHexString(pkt.getTargetHardwareAddress()),
-                        InetAddress.getByAddress(pkt.getTargetProtocolAddress()), p);
-            } else if(pkt.getOpCode() == ARP.REPLY) {
-                log.trace("Received Arp Reply with srcMac {} - srcIp {} - dstMac {} - dstIp {} - inport {}", HexEncode.bytesToHexString(pkt.getSenderHardwareAddress()),
-                        InetAddress.getByAddress(pkt.getSenderProtocolAddress()), HexEncode.bytesToHexString(pkt.getTargetHardwareAddress()),
-                        InetAddress.getByAddress(pkt.getTargetProtocolAddress()), p);
-            }
-        } catch(UnknownHostException e) {
+            log.trace("Received Arp {} with srcMac {} - srcIp {} - dstMac {} - dstIp {} - inport {} {}",
+                    ((pkt.getOpCode() == ARP.REQUEST) ? "Request" : "Reply"),
+                    HexEncode.bytesToHexString(pkt.getSenderHardwareAddress()),
+                    InetAddress.getByAddress(pkt.getSenderProtocolAddress()),
+                    HexEncode.bytesToHexString(pkt.getTargetHardwareAddress()),
+                    InetAddress.getByAddress(pkt.getTargetProtocolAddress()), p, (vlan != 0 ? "on vlan " + vlan : ""));
+
+        } catch (UnknownHostException e) {
             log.warn("Illegal Ip Address in the ARP packet", e);
         }
     }
 
-    protected void handleARPPacket(Ethernet eHeader, ARP pkt, NodeConnector p) {
+    protected void handleARPPacket(Ethernet eHeader, ARP pkt, NodeConnector p, short vlan) {
 
         if(log.isTraceEnabled()) {
-            logArpPacket(pkt, p);
+            logArpPacket(pkt, p, vlan);
         }
 
         byte[] sourceMAC = eHeader.getSourceMACAddress();
@@ -264,7 +261,7 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA
         HostNodeConnector requestor = null;
         if (NetUtils.isUnicastMACAddr(sourceMAC) && p.getNode() != null) {
             try {
-                requestor = new HostNodeConnector(sourceMAC, sourceIP, p, subnet.getVlan());
+                requestor = new HostNodeConnector(sourceMAC, sourceIP, p, vlan);
             } catch (ConstructionException e) {
                 log.debug("Received ARP packet with invalid MAC: {}", HexEncode.bytesToHexString(sourceMAC));
                 return;
@@ -294,7 +291,7 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA
             // the true value indicates we should generate replies to requestors
             // across the cluster
             log.trace("Received ARP reply packet from {}, reply to all requestors.", sourceIP);
-            arpRequestReplyEvent.put(new ARPReply(sourceIP, sourceMAC), true);
+            arpRequestReplyEvent.put(new ARPReply(sourceIP, sourceMAC, vlan), true);
             return;
         }
 
@@ -315,11 +312,11 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA
                     log.trace("Received local ARP req. for default gateway. Replying with controller MAC: {}",
                             HexEncode.bytesToHexString(getControllerMAC()));
                 }
-                sendARPReply(p, getControllerMAC(), targetIP, pkt.getSenderHardwareAddress(), sourceIP);
+                sendARPReply(p, getControllerMAC(), targetIP, pkt.getSenderHardwareAddress(), sourceIP, vlan);
             } else {
                 log.trace("Received non-local ARP req. for default gateway. Raising reply event");
                 arpRequestReplyEvent.put(
-                        new ARPReply(p, targetIP, getControllerMAC(), sourceIP, pkt.getSenderHardwareAddress()), false);
+                        new ARPReply(p, targetIP, getControllerMAC(), sourceIP, pkt.getSenderHardwareAddress(), vlan), false);
             }
             return;
         }
@@ -353,10 +350,10 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA
                 log.trace("Received ARP req. for known host {}, sending reply...", targetIP);
                 if (connectionManager.getLocalityStatus(p.getNode()) == ConnectionLocality.LOCAL) {
                     sendARPReply(p, host.getDataLayerAddressBytes(), host.getNetworkAddress(),
-                            pkt.getSenderHardwareAddress(), sourceIP);
+                            pkt.getSenderHardwareAddress(), sourceIP, vlan);
                 } else {
                     arpRequestReplyEvent.put(new ARPReply(p, host.getNetworkAddress(), host.getDataLayerAddressBytes(),
-                            sourceIP, pkt.getSenderHardwareAddress()), false);
+                            sourceIP, pkt.getSenderHardwareAddress(), vlan), false);
                 }
             } else {
                 /*
@@ -404,7 +401,7 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA
             }
 
             byte[] destMACAddress = NetUtils.getBroadcastMACAddr();
-            Ethernet ethernet = createEthernet(getControllerMAC(), destMACAddress, arp);
+            Ethernet ethernet = createEthernet(getControllerMAC(), destMACAddress, arp, (short)0);
 
             // TODO For now send port-by-port, see how to optimize to
             // send to multiple ports at once
@@ -416,9 +413,9 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA
     }
 
     /**
-     * Send a unicast ARP Request to the known host on a specific switch/port as
-     * defined in the host. The sender IP is the networkAddress of the subnet
-     * The sender MAC is the controller's MAC
+     * Send a unicast ARP Request to the known host on specific (switch/port,
+     * vlan) as defined in the host. The sender IP is the networkAddress of the
+     * subnet The sender MAC is the controller's MAC
      */
     protected void sendUcastARPRequest(HostNodeConnector host, Subnet subnet) {
         log.trace("sendUcastARPRequest host:{} subnet:{}", host, subnet);
@@ -440,7 +437,7 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA
                     outPort);
         }
 
-        Ethernet ethernet = createEthernet(getControllerMAC(), targetMAC, arp);
+        Ethernet ethernet = createEthernet(getControllerMAC(), targetMAC, arp, host.getVlan());
 
         RawPacket destPkt = this.dataPacketService.encodeDataPacket(ethernet);
         destPkt.setOutgoingNodeConnector(outPort);
@@ -498,7 +495,7 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA
      * @param pkt
      * @param p
      */
-    protected void handlePuntedIPPacket(IPv4 pkt, NodeConnector p) {
+    protected void handlePuntedIPPacket(IPv4 pkt, NodeConnector p, short vlan) {
 
         InetAddress dIP = NetUtils.getInetAddress(pkt.getDestinationAddress());
         if (dIP == null) {
@@ -653,13 +650,19 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA
         log.trace("Received a frame of size: {}", inPkt.getPacketData().length);
         Packet formattedPak = this.dataPacketService.decodeDataPacket(inPkt);
         if (formattedPak instanceof Ethernet) {
-            Object nextPak = formattedPak.getPayload();
+            Packet nextPak = formattedPak.getPayload();
+            short vlan = 0;
+            if (nextPak instanceof IEEE8021Q) {
+                vlan = ((IEEE8021Q) nextPak).getVid();
+                log.trace("Moved after the dot1Q header");
+                nextPak = ((IEEE8021Q) nextPak).getPayload();
+            }
             if (nextPak instanceof IPv4) {
                 log.trace("Handle IP packet: {}", formattedPak);
-                handlePuntedIPPacket((IPv4) nextPak, inPkt.getIncomingNodeConnector());
+                handlePuntedIPPacket((IPv4) nextPak, inPkt.getIncomingNodeConnector(), vlan);
             } else if (nextPak instanceof ARP) {
                 log.trace("Handle ARP packet: {}", formattedPak);
-                handleARPPacket((Ethernet) formattedPak, (ARP) nextPak, inPkt.getIncomingNodeConnector());
+                handleARPPacket((Ethernet) formattedPak, (ARP) nextPak, inPkt.getIncomingNodeConnector(), vlan);
             }
         }
         return PacketResult.IGNORED;
@@ -680,12 +683,23 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA
         return arp;
     }
 
-    private Ethernet createEthernet(byte[] sourceMAC, byte[] targetMAC, ARP arp) {
+    private Ethernet createEthernet(byte[] sourceMAC, byte[] targetMAC, ARP arp, short vlan) {
         Ethernet ethernet = new Ethernet();
         ethernet.setSourceMACAddress(sourceMAC);
         ethernet.setDestinationMACAddress(targetMAC);
-        ethernet.setEtherType(EtherTypes.ARP.shortValue());
-        ethernet.setPayload(arp);
+        if (vlan == 0) {
+            ethernet.setEtherType(EtherTypes.ARP.shortValue());
+            ethernet.setPayload(arp);
+        } else {
+            IEEE8021Q dot1q = new IEEE8021Q();
+            dot1q.setVid(vlan);
+            dot1q.setEtherType(EtherTypes.ARP.shortValue());
+            dot1q.setPayload(arp);
+            dot1q.setCfi((byte)0);
+            dot1q.setPcp((byte)0);
+            ethernet.setEtherType(EtherTypes.VLANTAGGED.shortValue());
+            ethernet.setPayload(dot1q);
+        }
         return ethernet;
     }
 
@@ -731,7 +745,7 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA
         }
     }
 
-    private void generateAndSendReply(InetAddress sourceIP, byte[] sourceMAC) {
+    private void generateAndSendReply(InetAddress sourceIP, byte[] sourceMAC, short vlan) {
         if (log.isTraceEnabled()) {
             log.trace("generateAndSendReply called with params sourceIP:{} sourceMAC:{}", sourceIP,
                     HexEncode.bytesToHexString(sourceMAC));
@@ -745,13 +759,14 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA
         for (HostNodeConnector host : hosts) {
             if (log.isTraceEnabled()) {
                 log.trace(
-                        "Sending ARP Reply with src {}/{}, target {}/{}",
+                        "Sending ARP Reply with src {}/{}, target {}/{} {}",
                         new Object[] { HexEncode.bytesToHexString(sourceMAC), sourceIP,
-                                HexEncode.bytesToHexString(host.getDataLayerAddressBytes()), host.getNetworkAddress() });
+                                HexEncode.bytesToHexString(host.getDataLayerAddressBytes()), host.getNetworkAddress(),
+                                (vlan != 0 ? "on vlan " + vlan : "") });
             }
             if (connectionManager.getLocalityStatus(host.getnodeconnectorNode()) == ConnectionLocality.LOCAL) {
                 sendARPReply(host.getnodeConnector(), sourceMAC, sourceIP, host.getDataLayerAddressBytes(),
-                        host.getNetworkAddress());
+                        host.getNetworkAddress(), vlan);
             } else {
                 /*
                  * In the remote event a requestor moved to another controller
@@ -760,7 +775,7 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA
                  */
                 arpRequestReplyEvent.put(
                         new ARPReply(host.getnodeConnector(), sourceIP, sourceMAC, host.getNetworkAddress(), host
-                                .getDataLayerAddressBytes()), false);
+                                .getDataLayerAddressBytes(), vlan), false);
             }
         }
     }
@@ -822,12 +837,12 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA
                         // requestors across the cluster
                         if (ev.isNewReply()) {
                             log.trace("Trigger a generateAndSendReply in response to {}", rep);
-                            generateAndSendReply(rep.getTargetIP(), rep.getTargetMac());
+                            generateAndSendReply(rep.getTargetIP(), rep.getTargetMac(), rep.getVlan());
                             // Otherwise, a specific reply. If local, send out.
                         } else if (connectionManager.getLocalityStatus(rep.getPort().getNode()) == ConnectionLocality.LOCAL) {
                             log.trace("ARPCacheEventHandler - sendUcatARPReply locally in response to {}", rep);
                             sendARPReply(rep.getPort(), rep.getSourceMac(), rep.getSourceIP(), rep.getTargetMac(),
-                                    rep.getTargetIP());
+                                    rep.getTargetIP(), rep.getVlan());
                         }
                     }
                 } catch (InterruptedException e) {
index dbe0745725eba376b5fe6102bb12c9750401fa6a..cec780c9ecafc0f4486299b7f24cc056aaa43f70 100644 (file)
@@ -69,9 +69,10 @@ public class Context {
         initialized = true;
     }
 
-    public List<Filter> findMatchingFilters(String pathInfo) {
+    public List<Filter> findMatchingFilters(String path) {
+        logger.trace("findMatchingFilters({})", path);
         checkState(initialized, "Not initialized");
-        return urlMatcher.findMatchingFilters(pathInfo);
+        return urlMatcher.findMatchingFilters(path);
     }
 
     @XmlAttribute(name = "path")
index dc3e9dcd49201654866f6603dc0201cd38359bdd..ae9d79a63df8d24f72ac7adf916d03c5f7708741 100644 (file)
@@ -37,14 +37,14 @@ public class FilterProcessor {
             throws IOException, ServletException {
 
         String contextPath = request.getContext().getPath();
-        String pathInfo = request.getPathInfo();
+        String path = request.getDecodedRequestURI();
 
         Optional<Context> maybeContext = host.findContext(contextPath);
-        logger.trace("Processing context {} path {}, found {}", contextPath, pathInfo, maybeContext);
+        logger.trace("Processing context {} path {}, found {}", contextPath, path, maybeContext);
         if (maybeContext.isPresent()) {
             // process filters
             Context context = maybeContext.get();
-            List<Filter> matchingFilters = context.findMatchingFilters(pathInfo);
+            List<Filter> matchingFilters = context.findMatchingFilters(path);
             FilterChain fromLast = nextValveFilterChain;
             ListIterator<Filter> it = matchingFilters.listIterator(matchingFilters.size());
             final boolean trace = logger.isTraceEnabled();
index 9535fb1f70f5a51323339c02107a8ebe102f459e..210326f5d109b896ee397db321769fc7aca29544 100644 (file)
@@ -62,31 +62,31 @@ public class UrlMatcher<FILTER> {
     /**
      * Find filters matching path
      *
-     * @param pathInfo as returned by request.getPathInfo()
+     * @param path relative and decoded path to resource
      * @return list of matching filters
      */
-    public List<FILTER> findMatchingFilters(String pathInfo) {
-        checkNotNull(pathInfo);
+    public List<FILTER> findMatchingFilters(String path) {
+        checkNotNull(path);
         TreeMap<Integer, FILTER> sortedMap = new TreeMap<>();
         // add matching prefixes
         for (Entry<String, Entry<FILTER, Integer>> prefixEntry : prefixMap.entrySet()) {
-            if (pathInfo.startsWith(prefixEntry.getKey())) {
+            if (path.startsWith(prefixEntry.getKey())) {
                 put(sortedMap, prefixEntry.getValue());
             }
         }
         // add matching suffixes
         for (Entry<String, Entry<FILTER, Integer>> suffixEntry : suffixMap.entrySet()) {
-            if (pathInfo.endsWith(suffixEntry.getKey())) {
+            if (path.endsWith(suffixEntry.getKey())) {
                 put(sortedMap, suffixEntry.getValue());
             }
         }
         // add exact match
-        Entry<FILTER, Integer> exactMatch = exactMatchMap.get(pathInfo);
+        Entry<FILTER, Integer> exactMatch = exactMatchMap.get(path);
         if (exactMatch != null) {
             put(sortedMap, exactMatch);
         }
         ArrayList<FILTER> filters = new ArrayList<>(sortedMap.values());
-        logger.trace("Matching filters for path {} are {}", pathInfo, filters);
+        logger.trace("Matching filters for path {} are {}", path, filters);
         return filters;
     }
 
index 58dbef67d5264b87896d92dc53299502f79076f3..163c64ed520bb1782bf0d1778f087913f0a4b86a 100644 (file)
@@ -18,7 +18,7 @@
 
   <properties>
 
-    <akka.version>2.3.2</akka.version>
+    <akka.version>2.3.4</akka.version>
     <aopalliance.version>1.0.0</aopalliance.version>
     <appauth.version>0.4.2-SNAPSHOT</appauth.version>
     <archetype-app-northbound>0.0.1-SNAPSHOT</archetype-app-northbound>
@@ -43,7 +43,6 @@
     <commons.catalina.ha>7.0.32.v201211201952</commons.catalina.ha>
     <commons.catalina.tribes>7.0.32.v201211201952</commons.catalina.tribes>
     <commons.checkstyle.version>0.0.3-SNAPSHOT</commons.checkstyle.version>
-    <commons.codec.version>1.7</commons.codec.version>
     <commons.coyote>7.0.32.v201211201952</commons.coyote>
     <commons.el>7.0.32.v201211081135</commons.el>
     <commons.fileupload.version>1.2.2</commons.fileupload.version>
@@ -63,6 +62,7 @@
     <compiler.version>2.3.2</compiler.version>
     <commons.httpclient.version>0.1.2-SNAPSHOT</commons.httpclient.version>
     <concepts.version>0.5.2-SNAPSHOT</concepts.version>
+    <concurrentlinkedhashmap.version>1.4</concurrentlinkedhashmap.version>
     <config.version>0.2.5-SNAPSHOT</config.version>
     <configuration.implementation.version>0.4.3-SNAPSHOT</configuration.implementation.version>
     <configuration.version>0.4.3-SNAPSHOT</configuration.version>
@@ -91,6 +91,7 @@
     <forwarding.staticrouting.northbound.version>0.4.2-SNAPSHOT</forwarding.staticrouting.northbound.version>
     <forwardingrulesmanager.implementation.version>0.4.2-SNAPSHOT</forwardingrulesmanager.implementation.version>
     <forwardingrulesmanager.version>0.6.0-SNAPSHOT</forwardingrulesmanager.version>
+    <ganymed.version>1.1-SNAPSHOT</ganymed.version>
     <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>
     <karaf.branding.version>1.0.0-SNAPSHOT</karaf.branding.version>
     <karaf.shell.version>3.0.0</karaf.shell.version>
     <karaf.version>3.0.1</karaf.version>
+    <leveldb.version>0.7</leveldb.version>
+    <leveldbjni.version>1.8</leveldbjni.version>
     <lifecycle.mapping.version>1.0.0</lifecycle.mapping.version>
     <logback.version>1.0.9</logback.version>
     <logging.bridge.version>0.4.2-SNAPSHOT</logging.bridge.version>
     <maven.plugin.api.version>3.0.5</maven.plugin.api.version>
+    <mimepull.version>1.9.4</mimepull.version>
     <mdsal.version>1.1-SNAPSHOT</mdsal.version>
     <netconf.version>0.2.5-SNAPSHOT</netconf.version>
     <networkconfig.bridgedomain.northbound.version>0.0.3-SNAPSHOT</networkconfig.bridgedomain.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>
+    <parboiled.version>1.1.6</parboiled.version>
+    <parboiled.scala.version>1.1.6</parboiled.scala.version>
     <propertymavenplugin.version>1.0-alpha-2</propertymavenplugin.version>
+    <protobuf.version>2.5.0</protobuf.version>
     <protocol-framework.version>0.5.0-SNAPSHOT</protocol-framework.version>
     <protocol_plugins.openflow.version>0.4.2-SNAPSHOT</protocol_plugins.openflow.version>
     <protocol_plugins.stub.version>0.4.2-SNAPSHOT</protocol_plugins.stub.version>
     <samples.loadbalancer.northbound.version>0.4.2-SNAPSHOT</samples.loadbalancer.northbound.version>
     <samples.simpleforwarding.version>0.4.2-SNAPSHOT</samples.simpleforwarding.version>
     <sanitytest.version>0.4.2-SNAPSHOT</sanitytest.version>
-    <scala.version>2.11</scala.version>
+    <scala.version>2.10</scala.version>
+    <scala.micro.version>4</scala.micro.version>
     <security.version>0.4.2-SNAPSHOT</security.version>
+    <shapeless.version>1.2.4</shapeless.version>
     <sitedeploy>dav:http://nexus.opendaylight.org/content/sites/site</sitedeploy>
     <sonar.branch>${user.name}-private-view</sonar.branch>
     <sonar.host.url>https://sonar.opendaylight.org/</sonar.host.url>
     <!-- Sonar properties using jacoco to retrieve integration test results -->
     <sonar.java.coveragePlugin>jacoco</sonar.java.coveragePlugin>
     <sonar.language>java</sonar.language>
+    <sonar.skippedModules>org.openflow.openflowj,net.sf.jung2,org.opendaylight.controller.protobuff.messages</sonar.skippedModules>
+    <spifly.version>1.0.0</spifly.version>
+    <spring-osgi.version>1.2.1</spring-osgi.version>
+    <spring-security-karaf.version>3.1.4.RELEASE</spring-security-karaf.version>
+    <spring-security.version>3.1.3.RELEASE</spring-security.version>
+    <spring.version>3.1.3.RELEASE</spring.version>
     <sonar.skippedModules>org.openflow.openflowj,net.sf.jung2</sonar.skippedModules>
     <statistics.northbound.version>0.4.2-SNAPSHOT</statistics.northbound.version>
     <statisticsmanager.implementation.version>0.4.2-SNAPSHOT</statisticsmanager.implementation.version>
     <topology.web.version>0.4.2-SNAPSHOT</topology.web.version>
     <topologymanager.version>0.4.2-SNAPSHOT</topologymanager.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>
     <usermanager.implementation.version>0.4.2-SNAPSHOT</usermanager.implementation.version>
     <usermanager.northbound.version>0.0.2-SNAPSHOT</usermanager.northbound.version>
     <usermanager.version>0.4.2-SNAPSHOT</usermanager.version>
         <artifactId>netconf-client</artifactId>
         <version>${netconf.version}</version>
       </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>netconf-client</artifactId>
-            <version>${netconf.version}</version>
-            <type>test-jar</type>
-        </dependency>
+      <dependency>
+        <groupId>org.opendaylight.controller</groupId>
+        <artifactId>netconf-client</artifactId>
+        <version>${netconf.version}</version>
+        <type>test-jar</type>
+      </dependency>
 
       <!--Netconf config-->
       <dependency>
         <artifactId>protocol_plugins.stub</artifactId>
         <version>${protocol_plugins.stub.version}</version>
       </dependency>
-      <dependency>
-        <groupId>org.opendaylight.controller</groupId>
-        <artifactId>remoterpc-routingtable.implementation</artifactId>
-        <version>${mdsal.version}</version>
-      </dependency>
       <dependency>
         <groupId>org.opendaylight.controller</groupId>
         <artifactId>routing.dijkstra_implementation</artifactId>
       </dependency>
       <dependency>
         <groupId>org.opendaylight.controller</groupId>
-        <artifactId>sal-remoterpc-connector</artifactId>
+        <artifactId>sal-rest-connector</artifactId>
         <version>${mdsal.version}</version>
       </dependency>
       <dependency>
         <groupId>org.opendaylight.controller</groupId>
-        <artifactId>sal-rest-connector</artifactId>
+        <artifactId>sal-rest-docgen</artifactId>
         <version>${mdsal.version}</version>
       </dependency>
       <dependency>
         <groupId>org.opendaylight.controller</groupId>
-        <artifactId>sal-rest-docgen</artifactId>
+        <artifactId>sal-restconf-broker</artifactId>
         <version>${mdsal.version}</version>
       </dependency>
       <dependency>
         <groupId>org.opendaylight.controller</groupId>
-        <artifactId>sal-restconf-broker</artifactId>
+        <artifactId>sal-test-model</artifactId>
         <version>${mdsal.version}</version>
       </dependency>
 
         <artifactId>sample-toaster-provider</artifactId>
         <version>${mdsal.version}</version>
       </dependency>
-      <dependency>
-        <groupId>org.opendaylight.controller.tests</groupId>
-        <artifactId>sal-remoterpc-connector-test-consumer</artifactId>
-        <version>${mdsal.version}</version>
-      </dependency>
-      <dependency>
-        <groupId>org.opendaylight.controller.tests</groupId>
-        <artifactId>sal-remoterpc-connector-test-provider</artifactId>
-        <version>${mdsal.version}</version>
-      </dependency>
       <dependency>
         <groupId>org.opendaylight.controller.thirdparty</groupId>
         <artifactId>com.sun.jersey.jersey-servlet</artifactId>
       <dependency>
         <groupId>org.opendaylight.controller.thirdparty</groupId>
         <artifactId>ganymed</artifactId>
-        <version>1.1-SNAPSHOT</version>
+        <version>${ganymed.version}</version>
       </dependency>
       <!-- Third parties from opendaylight released -->
       <dependency>
                     <ignore></ignore>
                   </action>
                 </pluginExecution>
+                <pluginExecution>
+                  <pluginExecutionFilter>
+                    <groupId>org.codehaus.mojo</groupId>
+                    <artifactId>javacc-maven-plugin</artifactId>
+                    <versionRange>[0.0,)</versionRange>
+                    <goals>
+                      <goal>javacc</goal>
+                    </goals>
+                  </pluginExecutionFilter>
+                  <action>
+                    <execute>
+                      <runOnIncremental>false</runOnIncremental>
+                    </execute>
+                  </action>
+                </pluginExecution>
               </pluginExecutions>
             </lifecycleMappingMetadata>
           </configuration>
index fef2c7196948c007705b4444a5c9445065618648..a62bd7da06501b355c41f36230dbf30a982d61fa 100644 (file)
@@ -8,9 +8,11 @@
 package org.opendaylight.protocol.framework;
 
 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.ChannelFuture;
 import io.netty.channel.ChannelInitializer;
 import io.netty.channel.ChannelOption;
@@ -25,9 +27,11 @@ import io.netty.util.concurrent.EventExecutor;
 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;
 
@@ -94,8 +98,8 @@ public abstract class AbstractDispatcher<S extends ProtocolSession<?>, L extends
      *
      * @return ChannelFuture representing the binding process
      */
-    protected <CH extends Channel> ChannelFuture createServer(SocketAddress address, Class<? extends ServerChannel> channelClass,
-                                                              final ChannelPipelineInitializer<CH, S> initializer) {
+    protected <CH extends Channel> ChannelFuture createServer(final SocketAddress address, final Class<? extends ServerChannel> channelClass,
+            final ChannelPipelineInitializer<CH, S> initializer) {
         final ServerBootstrap b = new ServerBootstrap();
         b.childHandler(new ChannelInitializer<CH>() {
 
@@ -110,6 +114,7 @@ public abstract class AbstractDispatcher<S extends ProtocolSession<?>, L extends
             // makes no sense for LocalServer and produces warning
             b.childOption(ChannelOption.SO_KEEPALIVE, true);
         }
+        b.childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
         customizeBootstrap(b);
 
         if (b.group() == null) {
@@ -151,9 +156,8 @@ 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);
-        b.group(this.workerGroup).channel(NioSocketChannel.class).option(ChannelOption.SO_KEEPALIVE, true).handler(
+        b.option(ChannelOption.SO_KEEPALIVE, true).handler(
                 new ChannelInitializer<SocketChannel>() {
-
                     @Override
                     protected void initChannel(final SocketChannel ch) {
                         initializer.initializeChannel(ch, p);
@@ -162,6 +166,18 @@ public abstract class AbstractDispatcher<S extends ProtocolSession<?>, L extends
 
         customizeBootstrap(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);
+        }
+
         p.connect();
         LOG.debug("Client created.");
         return p;
@@ -5,7 +5,7 @@
  * 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.config.manager.impl.jmx;
+package org.opendaylight.controller.config.api.jmx;
 
 import javax.management.ObjectName;
 
index 335acc81fe67859386b3369269c15f3101d7e2f4..07bd63b7c7be8c78397b227ae40db7e53cb8da91 100644 (file)
@@ -53,12 +53,12 @@ public class DynamicWritableWrapper extends AbstractDynamicWrapper {
     private final ReadOnlyAtomicBoolean configBeanModificationDisabled;
 
     public DynamicWritableWrapper(Module module,
-            ModuleIdentifier moduleIdentifier,
-            TransactionIdentifier transactionIdentifier,
-            ReadOnlyAtomicBoolean configBeanModificationDisabled,
-            MBeanServer internalServer, MBeanServer configMBeanServer) {
+                                  ModuleIdentifier moduleIdentifier,
+                                  TransactionIdentifier transactionIdentifier,
+                                  ReadOnlyAtomicBoolean configBeanModificationDisabled,
+                                  MBeanServer internalServer, MBeanServer configMBeanServer) {
         super(module, true, moduleIdentifier, ObjectNameUtil
-                .createTransactionModuleON(transactionIdentifier.getName(), moduleIdentifier), getOperations(moduleIdentifier),
+                        .createTransactionModuleON(transactionIdentifier.getName(), moduleIdentifier), getOperations(moduleIdentifier),
                 internalServer, configMBeanServer);
         this.configBeanModificationDisabled = configBeanModificationDisabled;
     }
@@ -67,22 +67,19 @@ public class DynamicWritableWrapper extends AbstractDynamicWrapper {
             ModuleIdentifier moduleIdentifier) {
         Method validationMethod;
         try {
-            validationMethod = DynamicWritableWrapper.class.getMethod(
-                    "validate", new Class<?>[0]);
+            validationMethod = DynamicWritableWrapper.class.getMethod("validate");
         } catch (NoSuchMethodException e) {
-            throw new IllegalStateException("No such method exception on "
-                    + moduleIdentifier, e);
+            throw new IllegalStateException("No such method exception on " + moduleIdentifier, e);
         }
-        return new MBeanOperationInfo[] { new MBeanOperationInfo("Validation",
-                validationMethod) };
+        return new MBeanOperationInfo[]{new MBeanOperationInfo("Validation", validationMethod)};
     }
 
     @Override
     public synchronized void setAttribute(Attribute attribute)
-            throws AttributeNotFoundException, InvalidAttributeValueException,
-            MBeanException, ReflectionException {
-        if (configBeanModificationDisabled.get() == true)
+            throws AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException {
+        if (configBeanModificationDisabled.get() == true) {
             throw new IllegalStateException("Operation is not allowed now");
+        }
 
         if (attribute.getName().equals("Attribute")) {
             setAttribute((Attribute) attribute.getValue());
@@ -92,7 +89,7 @@ public class DynamicWritableWrapper extends AbstractDynamicWrapper {
         try {
             if (attribute.getValue() instanceof ObjectName) {
                 attribute = fixDependencyAttribute(attribute);
-            } else if(attribute.getValue() instanceof ObjectName[]) {
+            } else if (attribute.getValue() instanceof ObjectName[]) {
                 attribute = fixDependencyListAttribute(attribute);
             }
 
@@ -104,24 +101,19 @@ public class DynamicWritableWrapper extends AbstractDynamicWrapper {
     }
 
     private Attribute fixDependencyListAttribute(Attribute attribute) {
-        AttributeHolder attributeHolder = attributeHolderMap
-                .get(attribute.getName());
+        AttributeHolder attributeHolder = attributeHolderMap.get(attribute.getName());
         if (attributeHolder.getRequireInterfaceOrNull() != null) {
-            attribute = new Attribute(attribute.getName(),
-                    fixObjectNames((ObjectName[]) attribute.getValue()));
+            attribute = new Attribute(attribute.getName(), fixObjectNames((ObjectName[]) attribute.getValue()));
         }
         return attribute;
     }
 
     private Attribute fixDependencyAttribute(Attribute attribute) {
-        AttributeHolder attributeHolder = attributeHolderMap
-                .get(attribute.getName());
+        AttributeHolder attributeHolder = attributeHolderMap.get(attribute.getName());
         if (attributeHolder.getRequireInterfaceOrNull() != null) {
-            attribute = new Attribute(attribute.getName(),
-                    fixObjectName((ObjectName) attribute.getValue()));
+            attribute = new Attribute(attribute.getName(), fixObjectName((ObjectName) attribute.getValue()));
         } else {
-            attribute = new Attribute(attribute.getName(),
-                    attribute.getValue());
+            attribute = new Attribute(attribute.getName(), attribute.getValue());
         }
         return attribute;
     }
@@ -145,8 +137,7 @@ public class DynamicWritableWrapper extends AbstractDynamicWrapper {
                 setAttribute(attribute);
                 result.add(attribute);
             } catch (Exception e) {
-                logger.warn("Setting attribute {} failed on {}",
-                        attribute.getName(), moduleIdentifier, e);
+                logger.warn("Setting attribute {} failed on {}", attribute.getName(), moduleIdentifier, e);
                 throw new IllegalArgumentException(
                         "Setting attribute failed - " + attribute.getName()
                                 + " on " + moduleIdentifier, e);
index dedeeed789f5e8b9ec030f2c349beec19f1c2872..ba6676b927bb554d296b2ebaa9efd3205bdebc4c 100644 (file)
@@ -8,6 +8,7 @@
 package org.opendaylight.controller.config.manager.impl.jmx;
 
 import javax.management.ObjectName;
+import org.opendaylight.controller.config.api.jmx.ServiceReferenceMXBean;
 
 public class ServiceReferenceMXBeanImpl implements ServiceReferenceMXBean {
     private ObjectName currentImplementation;
index 3e7b65e1bdcf8f25cfe6c255e43072edc2382f6a..8c132c93b298dee714f3efa063f329efc70a7878 100644 (file)
@@ -13,7 +13,7 @@ import org.junit.Test;
 import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
 import org.opendaylight.controller.config.manager.impl.AbstractConfigTest.RecordingBundleContextServiceRegistrationHandler.RegistrationHolder;
 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
-import org.opendaylight.controller.config.manager.impl.jmx.ServiceReferenceMXBean;
+import org.opendaylight.controller.config.api.jmx.ServiceReferenceMXBean;
 import org.opendaylight.controller.config.manager.testingservices.parallelapsp.TestingParallelAPSPModuleFactory;
 import org.opendaylight.controller.config.manager.testingservices.parallelapsp.test.AbstractParallelAPSPTest;
 import org.opendaylight.controller.config.manager.testingservices.scheduledthreadpool.TestingScheduledThreadPoolModuleFactory;
index 6ddb1306c559633193b2d6e897ad09d9499ee7f1..ae041f45852fd484e2f3a51cf80059211bc36294 100644 (file)
@@ -20,6 +20,7 @@
         <dependency>
             <groupId>org.opendaylight.controller</groupId>
             <artifactId>config-api</artifactId>
+            <version>${config.version}</version>
         </dependency>
     </dependencies>
 
index c00b26d9ced898dc0dd4f4239d68b9d933332ad3..ba13ebb8f051e65d31c5a663daee15b1034d0134 100644 (file)
@@ -12,13 +12,14 @@ import java.util.SortedSet;
 public interface ConfigSnapshotHolder {
 
     /**
-     * Get part of get-config document that contains just
+     * Get XML node that should be pushed to netconf's edit-config
      */
     String getConfigSnapshot();
 
 
     /**
      * Get only required capabilities referenced by the snapshot.
+     * If no value is specified, return empty set instead of null
      */
     SortedSet<String> getCapabilities();
 
index d13052a7e273a3aa5ffb45e22e8b421ed689afde..7c069dab6b0fb04bbd511fefffbfc5ebf3be6879 100644 (file)
@@ -7,6 +7,7 @@
  */
 package org.opendaylight.controller.config.persist.storage.file.xml.model;
 
+import java.util.TreeSet;
 import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
 
 import javax.xml.bind.annotation.XmlAnyElement;
@@ -22,7 +23,7 @@ public class ConfigSnapshot {
     public static final String SNAPSHOT_ROOT_ELEMENT_NAME = "snapshot";
 
     private String configSnapshot;
-    private SortedSet<String> capabilities;
+    private SortedSet<String> capabilities = new TreeSet<>();
 
     ConfigSnapshot(String configXml, SortedSet<String> capabilities) {
         this.configSnapshot = configXml;
index b6e2efcd457653f6414ac381eb80018b0e4249f8..7429f4d57431c9922d9a33ef5e8053ef1cfd174f 100644 (file)
@@ -8,7 +8,7 @@
     <relativePath>..</relativePath>
   </parent>
   <artifactId>config-util</artifactId>
-  <packaging>jar</packaging>
+  <packaging>bundle</packaging>
   <name>${project.artifactId}</name>
 
   <dependencies>
           <threadCount>1</threadCount>
         </configuration>
       </plugin>
+      <plugin>
+        <groupId>org.apache.felix</groupId>
+        <artifactId>maven-bundle-plugin</artifactId>
+        <configuration>
+          <instructions>
+            <Export-Package>org.opendaylight.controller.config.util</Export-Package>
+          </instructions>
+        </configuration>
+      </plugin>
     </plugins>
   </build>
 
index 549ff9ffcfdb9254a4115349d1cbd65520875809..559993f2648ec013791bdcf7167e412fe9a69102 100644 (file)
@@ -26,6 +26,7 @@ import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
+import org.opendaylight.controller.config.api.jmx.ServiceReferenceMXBean;
 
 public class ConfigRegistryJMXClient implements ConfigRegistryClient {
     private final ConfigRegistryMXBean configRegistryMXBeanProxy;
@@ -65,10 +66,27 @@ public class ConfigRegistryJMXClient implements ConfigRegistryClient {
                 configMBeanServer);
     }
 
+    /**
+     * Usage of this method indicates error as config JMX uses solely MXBeans.
+     * Use {@link #newMXBeanProxy(javax.management.ObjectName, Class)}
+     * or {@link JMX#newMBeanProxy(javax.management.MBeanServerConnection, javax.management.ObjectName, Class)}
+     * This method will be removed soon.
+     */
+    @Deprecated
     public <T> T newMBeanProxy(ObjectName on, Class<T> clazz) {
+        on = translateServiceRefIfPossible(on, clazz, configMBeanServer);
         return JMX.newMBeanProxy(configMBeanServer, on, clazz);
     }
 
+    static  ObjectName translateServiceRefIfPossible(ObjectName on, Class<?> clazz, MBeanServer configMBeanServer) {
+        if (ObjectNameUtil.isServiceReference(on) && clazz.equals(ServiceReferenceMXBean.class) == false) {
+            ServiceReferenceMXBean proxy = JMX.newMXBeanProxy(configMBeanServer, on, ServiceReferenceMXBean.class);
+            on = proxy.getCurrentImplementation();
+        }
+        return on;
+    }
+
+
     public <T> T newMXBeanProxy(ObjectName on, Class<T> clazz) {
         return JMX.newMXBeanProxy(configMBeanServer, on, clazz);
     }
@@ -211,5 +229,4 @@ public class ConfigRegistryJMXClient implements ConfigRegistryClient {
     public void checkServiceReferenceExists(ObjectName objectName) throws InstanceNotFoundException {
         configRegistryMXBeanProxy.checkServiceReferenceExists(objectName);
     }
-
 }
index 4f02db5a3807095c0302ee1446eb765a2858ea77..f5381424de8c217414a326212c69b25879c52fe8 100644 (file)
@@ -41,4 +41,14 @@ public interface ConfigTransactionClient extends
     void destroyModule(String moduleName, String instanceName) throws InstanceNotFoundException;
 
     void setAttribute(ObjectName on, String jmxName, Attribute attribute);
+
+    /*
+     * Get the attribute named jmxName from the Object with ObjectName on
+     *
+     * @param on - ObjectName of the Object from which the attribute should be read
+     * @param jmxName - name of the attribute to be read
+     *
+     * @return Attribute of Object on with attribute name jmxName
+     */
+    Attribute getAttribute(ObjectName on, String jmxName);
 }
index 4adc0d9364e3392969c0c771edc4fd5ae41cdaf1..bc188515538485f9a13f87366a281a893a5984ae 100644 (file)
@@ -7,12 +7,8 @@
  */
 package org.opendaylight.controller.config.util;
 
-import org.opendaylight.controller.config.api.ConflictingVersionException;
-import org.opendaylight.controller.config.api.ValidationException;
-import org.opendaylight.controller.config.api.jmx.CommitStatus;
-import org.opendaylight.controller.config.api.jmx.ConfigRegistryMXBean;
-import org.opendaylight.controller.config.api.jmx.ConfigTransactionControllerMXBean;
-import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
+import java.util.Map;
+import java.util.Set;
 
 import javax.management.Attribute;
 import javax.management.InstanceAlreadyExistsException;
@@ -22,8 +18,13 @@ import javax.management.JMX;
 import javax.management.MBeanException;
 import javax.management.MBeanServer;
 import javax.management.ObjectName;
-import java.util.Map;
-import java.util.Set;
+
+import org.opendaylight.controller.config.api.ConflictingVersionException;
+import org.opendaylight.controller.config.api.ValidationException;
+import org.opendaylight.controller.config.api.jmx.CommitStatus;
+import org.opendaylight.controller.config.api.jmx.ConfigRegistryMXBean;
+import org.opendaylight.controller.config.api.jmx.ConfigTransactionControllerMXBean;
+import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
 
 public class ConfigTransactionJMXClient implements ConfigTransactionClient {
     private final ConfigRegistryMXBean configRegistryMXBeanProxy;
@@ -44,9 +45,21 @@ public class ConfigTransactionJMXClient implements ConfigTransactionClient {
     }
 
     public <T> T newMXBeanProxy(ObjectName on, Class<T> clazz) {
+        // if on is without transaction, add it. Reason is that when using getters on MXBeans the transaction name is stripped
+        on = ObjectNameUtil.withTransactionName(on, getTransactionName());
+        // if this is service reference and user requests for implementation, look it up
+        on = ConfigRegistryJMXClient.translateServiceRefIfPossible(on, clazz, configMBeanServer);
+        on = ObjectNameUtil.withTransactionName(on, getTransactionName());
         return JMX.newMXBeanProxy(configMBeanServer, on, clazz);
     }
 
+    /**
+     * Usage of this method indicates error as config JMX uses solely MXBeans.
+     * Use {@link #newMXBeanProxy(javax.management.ObjectName, Class)}
+     * or {@link JMX#newMBeanProxy(javax.management.MBeanServerConnection, javax.management.ObjectName, Class)}
+     * This method will be removed soon.
+     */
+    @Deprecated
     public <T> T newMBeanProxy(ObjectName on, Class<T> clazz) {
         return JMX.newMBeanProxy(configMBeanServer, on, clazz);
     }
@@ -259,6 +272,20 @@ public class ConfigTransactionJMXClient implements ConfigTransactionClient {
         }
     }
 
+    @Override
+    public Attribute getAttribute(ObjectName on, String attrName) {
+        if (ObjectNameUtil.getTransactionName(on) == null)
+            throw new IllegalArgumentException("Not in transaction instance "
+                    + on + ", no transaction name present");
+
+        try {
+            return new Attribute(attrName, configMBeanServer.getAttribute(on,attrName));
+        } catch (JMException e) {
+            throw new IllegalStateException("Unable to get attribute "
+                    + attrName + " for " + on, e);
+        }
+    }
+
     @Override
     public Set<String> getAvailableModuleFactoryQNames() {
         return configTransactionControllerMXBeanProxy.getAvailableModuleFactoryQNames();
diff --git a/opendaylight/config/feature/src/main/resources/features.xml b/opendaylight/config/feature/src/main/resources/features.xml
deleted file mode 100644 (file)
index 81972c3..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<features name="config-${project.version}" xmlns="http://karaf.apache.org/xmlns/features/v1.2.0"
-   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-   xsi:schemaLocation="http://karaf.apache.org/xmlns/features/v1.2.0 http://karaf.apache.org/xmlns/features/v1.2.0">
-    <feature name='config-all' version='${project.version}'>
-        <feature version='${project.version}'>odl-config-subsystem</feature>
-    </feature>
-
-    <feature name='odl-config-subsystem' version='${project.version}'>
-        <feature version='${yangtools.version}'>yangtools-concepts</feature>
-        <feature version='${yangtools.version}'>yangtools-binding</feature>
-        <feature version='${yangtools.version}'>yangtools-binding-generator</feature>
-        <feature version='${mdsal.version}'>odl-mdsal-commons</feature>
-        <bundle>mvn:org.opendaylight.controller/config-api/${project.version}</bundle>
-        <bundle>mvn:org.opendaylight.controller/config-manager/${project.version}</bundle>
-        <bundle>mvn:org.opendaylight.controller/yang-jmx-generator/${project.version}</bundle>
-        <bundle>mvn:org.opendaylight.controller/config-persister-api/${project.version}</bundle>
-        <bundle>mvn:org.opendaylight.controller/config-persister-file-xml-adapter/${project.version}</bundle>
-        <bundle>mvn:org.opendaylight.controller/config-persister-directory-xml-adapter/${project.version}</bundle>
-        <bundle>mvn:org.opendaylight.controller/shutdown-api/${project.version}</bundle>
-        <bundle>mvn:org.opendaylight.controller/shutdown-impl/${project.version}</bundle>
-        <bundle>mvn:org.osgi/org.osgi.core/${osgi.core.version}</bundle>
-        <bundle>wrap:mvn:com.google.guava/guava/${guava.version}</bundle>
-        <bundle>mvn:org.javassist/javassist/${javassist.version}</bundle>
-    </feature>
-</features>
\ No newline at end of file
index 76fbd7f6e55c057e6248fed354da9c8f801da2bb..66bb01f051fa1042e9fc08d4019a236f1e07bb04 100644 (file)
@@ -1,5 +1,4 @@
 <?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: -->
 <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>
 
@@ -40,7 +39,6 @@
     <module>shutdown-impl</module>
     <module>netconf-config-dispatcher</module>
     <module>config-module-archetype</module>
-    <module>feature</module>
   </modules>
 
   <dependencies>
index 3dfa6e2bc756419b18f3224b32b127255e00d35d..5036399828a539e5ec5deb451881f3e4e9218b68 100644 (file)
@@ -10,15 +10,20 @@ package org.opendaylight.controller.config.threadpool.util;
 
 import java.io.Closeable;
 import java.io.IOException;
+import java.util.concurrent.BlockingQueue;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
-import java.util.concurrent.SynchronousQueue;
+import java.util.concurrent.LinkedBlockingQueue;
+import java.util.concurrent.RejectedExecutionException;
+import java.util.concurrent.RejectedExecutionHandler;
 import java.util.concurrent.ThreadFactory;
 import java.util.concurrent.ThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
 
 import org.opendaylight.controller.config.threadpool.ThreadPool;
 
+import com.google.common.base.Optional;
+
 /**
  * Implementation of {@link ThreadPool} using flexible number of threads wraps
  * {@link ExecutorService}.
@@ -28,12 +33,33 @@ public class FlexibleThreadPoolWrapper implements ThreadPool, Closeable {
 
     public FlexibleThreadPoolWrapper(int minThreadCount, int maxThreadCount, long keepAlive, TimeUnit timeUnit,
             ThreadFactory threadFactory) {
+        this(minThreadCount, maxThreadCount, keepAlive, timeUnit, threadFactory, getQueue(Optional.<Integer>absent()));
+    }
+
+    public FlexibleThreadPoolWrapper(int minThreadCount, int maxThreadCount, long keepAlive, TimeUnit timeUnit,
+            ThreadFactory threadFactory, Optional<Integer> queueCapacity) {
+        this(minThreadCount, maxThreadCount, keepAlive, timeUnit, threadFactory, getQueue(queueCapacity));
+    }
+
+    private FlexibleThreadPoolWrapper(int minThreadCount, int maxThreadCount, long keepAlive, TimeUnit timeUnit,
+            ThreadFactory threadFactory, BlockingQueue<Runnable> queue) {
 
         executor = new ThreadPoolExecutor(minThreadCount, maxThreadCount, keepAlive, timeUnit,
-                new SynchronousQueue<Runnable>(), threadFactory);
+                queue, threadFactory, new FlexibleRejectionHandler());
         executor.prestartAllCoreThreads();
     }
 
+    /**
+     * Overriding the queue:
+     * ThreadPoolExecutor would not create new threads if the queue is not full, thus adding
+     * occurs in RejectedExecutionHandler.
+     * This impl saturates threadpool first, then queue. When both are full caller will get blocked.
+     */
+    private static ForwardingBlockingQueue getQueue(Optional<Integer> capacity) {
+        final BlockingQueue<Runnable> delegate = capacity.isPresent() ? new LinkedBlockingQueue<Runnable>(capacity.get()) : new LinkedBlockingQueue<Runnable>();
+        return new ForwardingBlockingQueue(delegate);
+    }
+
     @Override
     public ExecutorService getExecutor() {
         return Executors.unconfigurableExecutorService(executor);
@@ -77,4 +103,37 @@ public class FlexibleThreadPoolWrapper implements ThreadPool, Closeable {
         executor.shutdown();
     }
 
+    /**
+     * if the max threads are met, then it will raise a rejectedExecution. We then push to the queue.
+     */
+    private static class FlexibleRejectionHandler implements RejectedExecutionHandler {
+        @Override
+        public void rejectedExecution(final Runnable r, final ThreadPoolExecutor executor) {
+            try {
+                executor.getQueue().put(r);
+            } catch (InterruptedException e) {
+                throw new RejectedExecutionException("Interrupted while waiting on the queue", e);
+            }
+        }
+    }
+
+    private static class ForwardingBlockingQueue extends com.google.common.util.concurrent.ForwardingBlockingQueue<Runnable> {
+        private final BlockingQueue<Runnable> delegate;
+
+        public ForwardingBlockingQueue(BlockingQueue<Runnable> delegate) {
+            this.delegate = delegate;
+        }
+
+        @Override
+        protected BlockingQueue<Runnable> delegate() {
+            return delegate;
+        }
+
+        @Override
+        public boolean offer(final Runnable r) {
+            // ThreadPoolExecutor will spawn a new thread after core size is reached only
+            // if the queue.offer returns false.
+            return false;
+        }
+    }
 }
index 94639d43c0248787c736a2d7df7738597a4ef975..d6abe168fbedfa9a7d2db6fc16d1151e621ca874 100644 (file)
@@ -17,6 +17,7 @@
 */
 package org.opendaylight.controller.config.yang.threadpool.impl.flexible;
 
+import com.google.common.base.Optional;
 import java.util.concurrent.TimeUnit;
 
 import org.opendaylight.controller.config.api.JmxAttributeValidationException;
@@ -50,11 +51,15 @@ public final class FlexibleThreadPoolModule extends org.opendaylight.controller.
         JmxAttributeValidationException.checkNotNull(getMaxThreadCount(), maxThreadCountJmxAttribute);
         JmxAttributeValidationException.checkCondition(getMaxThreadCount() > 0, "must be greater than zero",
                 maxThreadCountJmxAttribute);
+
+        if(getQueueCapacity() != null) {
+            JmxAttributeValidationException.checkCondition(getQueueCapacity() > 0, "Queue capacity cannot be < 1", queueCapacityJmxAttribute);
+        }
     }
 
     @Override
     public java.lang.AutoCloseable createInstance() {
         return new FlexibleThreadPoolWrapper(getMinThreadCount(), getMaxThreadCount(), getKeepAliveMillis(),
-                TimeUnit.MILLISECONDS, getThreadFactoryDependency());
+                TimeUnit.MILLISECONDS, getThreadFactoryDependency(), Optional.fromNullable(getQueueCapacity()));
     }
 }
index be275ef4870b3797e5195d61380a8c5935f3ff83..c124f6388fb2f5f41b1c48a86f55231ea4c023b4 100644 (file)
@@ -46,6 +46,12 @@ module threadpool-impl-flexible {
                 type uint32;
             }
 
+            leaf queueCapacity {
+                type uint16;
+                mandatory false;
+                description "Capacity of queue that holds waiting tasks";
+            }
+
             container threadFactory {
                 uses config:service-ref {
                     refine type {
index aa06cb97d74eafcc35eeea7f16128e7f94743cfb..33546b1e2ae6a4d6ede0dfaddfc307495f13a325 100644 (file)
@@ -7,6 +7,7 @@
  */
 package org.opendaylight.controller.config.yangjmxgenerator.plugin.gofactory;
 
+import static com.google.common.base.Preconditions.checkState;
 import static java.lang.String.format;
 
 import com.google.common.base.Joiner;
@@ -212,7 +213,7 @@ public class AbsModuleGeneratedObjectFactory {
                         "}\n", moduleField.getName(), osgi);
                 } else {
                     str = format(
-                        "%1$sDependency = dependencyResolver.resolveInstance(%2$s.class, %1$s, %1$sJmxAttribute);",
+                        "%1$sDependency = dependencyResolver.resolveInstance(%2$s.class, %1$s, %1$sJmxAttribute);\n",
                         moduleField.getName(), osgi);
                 }
                 resolveDependenciesMap.put(moduleField, str);
@@ -222,7 +223,8 @@ public class AbsModuleGeneratedObjectFactory {
         // wrap each field resolvation statement with if !=null when dependency is not mandatory
         for (Map.Entry<ModuleField, String> entry : resolveDependenciesMap.entrySet()) {
             if (entry.getKey().getDependency().isMandatory() == false) {
-                result += format("if (%s!=null) {\n%s;\n}", entry.getKey().getName(), entry.getValue());
+                checkState(entry.getValue().endsWith(";\n"));
+                result += format("if (%s!=null) {\n%s}\n", entry.getKey().getName(), entry.getValue());
             } else {
                 result += entry.getValue();
             }
@@ -284,7 +286,7 @@ public class AbsModuleGeneratedObjectFactory {
             format("private final %s oldModule;\n", abstractFQN.getTypeName())+
             format("private final %s oldInstance;\n", AutoCloseable.class.getCanonicalName())+
             format("private %s instance;\n", AutoCloseable.class.getCanonicalName())+
-            format("private final %s dependencyResolver;\n", DependencyResolver.class.getCanonicalName())+
+            format("protected final %s dependencyResolver;\n", DependencyResolver.class.getCanonicalName())+
             format("private final %s identifier;\n", ModuleIdentifier.class.getCanonicalName())+
             "@Override\n"+
             format("public %s getIdentifier() {\n", ModuleIdentifier.class.getCanonicalName())+
@@ -401,7 +403,7 @@ public class AbsModuleGeneratedObjectFactory {
         parameters.put(ModuleIdentifier.class.getCanonicalName(), "identifier");
         parameters.put(DependencyResolver.class.getCanonicalName(), "dependencyResolver");
 
-        String setToNulls = "this.oldInstance=null;\n;" +
+        String setToNulls = "this.oldInstance=null;\n" +
                 "this.oldModule=null;\n";
         return getConstructorStart(abstractFQN, parameters, setToNulls);
     }
index ae064001956b9217fcfc1e950309ff514d17ddf6..775fa9fc20d97b10a48859703a4572f03b65d2ca 100644 (file)
@@ -7,11 +7,6 @@
  */
 package org.opendaylight.controller.config.yangjmxgenerator;
 
-import java.net.URI;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Date;
-
 import org.opendaylight.yangtools.yang.common.QName;
 
 public class ConfigConstants {
@@ -33,33 +28,14 @@ public class ConfigConstants {
     public static final QName RPC_CONTEXT_REF_GROUPING_LEAF = createRpcXQName("context-instance");
     public static final QName RPC_CONTEXT_INSTANCE_EXTENSION_QNAME = createRpcXQName("rpc-context-instance");
 
-    public static QName createConfigQName(String localName) {
-        return createQName(CONFIG_NAMESPACE, "2013-04-05", localName);
+    public static QName createConfigQName(final String localName) {
+        // FIXME: pre-construct QNameModule
+        return QName.create(CONFIG_NAMESPACE, "2013-04-05", localName);
     }
 
-    public static QName createRpcXQName(String localName) {
-        return createQName("urn:ietf:params:xml:ns:yang:rpc-context",
+    public static QName createRpcXQName(final String localName) {
+        // FIXME: pre-construct QNameModule
+        return QName.create("urn:ietf:params:xml:ns:yang:rpc-context",
                 "2013-06-17", localName);
     }
-
-    /**
-     *
-     * @param uri
-     * @param revisionDate
-     *            in format yyyy-MM-dd
-     * @param localName
-     * @return
-     */
-    private static QName createQName(String uri, String revisionDate,
-            String localName) {
-        SimpleDateFormat revisionFormat = new SimpleDateFormat("yyyy-MM-dd");
-        Date revision;
-        try {
-            revision = revisionFormat.parse(revisionDate);
-        } catch (ParseException e) {
-            throw new RuntimeException(e);
-        }
-        return new QName(URI.create(uri), revision, localName);
-    }
-
 }
index 89f3a4a51923a3f126f09b50af7e0d14b7af62a3..d8c5a56fb7a7561de457894180ad1a1b418b7f57 100644 (file)
@@ -18,6 +18,7 @@ import com.google.common.base.Optional;
 import com.google.common.collect.Collections2;
 import com.google.common.collect.Maps;
 import com.google.common.collect.Sets;
+
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
@@ -26,7 +27,9 @@ import java.util.Objects;
 import java.util.Set;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
+
 import javax.annotation.Nullable;
+
 import org.opendaylight.controller.config.yangjmxgenerator.attribute.AbstractDependencyAttribute;
 import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
 import org.opendaylight.controller.config.yangjmxgenerator.attribute.DependencyAttribute;
@@ -64,27 +67,27 @@ final class ModuleMXBeanEntryBuilder {
     private TypeProviderWrapper typeProviderWrapper;
     private String packageName;
 
-    public ModuleMXBeanEntryBuilder setModule(Module module) {
+    public ModuleMXBeanEntryBuilder setModule(final Module module) {
         this.currentModule = module;
         return this;
     }
 
-    public ModuleMXBeanEntryBuilder setqNamesToSIEs(Map<QName, ServiceInterfaceEntry> qNamesToSIEs) {
+    public ModuleMXBeanEntryBuilder setqNamesToSIEs(final Map<QName, ServiceInterfaceEntry> qNamesToSIEs) {
         this.qNamesToSIEs = qNamesToSIEs;
         return this;
     }
 
-    public ModuleMXBeanEntryBuilder setSchemaContext(SchemaContext schemaContext) {
+    public ModuleMXBeanEntryBuilder setSchemaContext(final SchemaContext schemaContext) {
         this.schemaContext = schemaContext;
         return this;
     }
 
-    public ModuleMXBeanEntryBuilder setTypeProviderWrapper(TypeProviderWrapper typeProviderWrapper) {
+    public ModuleMXBeanEntryBuilder setTypeProviderWrapper(final TypeProviderWrapper typeProviderWrapper) {
         this.typeProviderWrapper = typeProviderWrapper;
         return this;
     }
 
-    public ModuleMXBeanEntryBuilder setPackageName(String packageName) {
+    public ModuleMXBeanEntryBuilder setPackageName(final String packageName) {
         this.packageName = packageName;
         return this;
     }
@@ -147,7 +150,7 @@ final class ModuleMXBeanEntryBuilder {
         return result;
     }
 
-    private static void cleanUpNulls(Map<String, ModuleMXBeanEntry> result) {
+    private static void cleanUpNulls(final Map<String, ModuleMXBeanEntry> result) {
         for (Map.Entry<String, ModuleMXBeanEntry> entry : result.entrySet()) {
             ModuleMXBeanEntry module = entry.getValue();
             if (module.getAttributes() == null) {
@@ -160,14 +163,14 @@ final class ModuleMXBeanEntryBuilder {
         }
     }
 
-    private static void checkUnaugumentedIdentities(Map<String, IdentitySchemaNode> unaugmentedModuleIdentities) {
+    private static void checkUnaugumentedIdentities(final Map<String, IdentitySchemaNode> unaugmentedModuleIdentities) {
         if (unaugmentedModuleIdentities.size() > 0) {
             logger.warn("Augmentation not found for all currentModule identities: {}",
                     unaugmentedModuleIdentities.keySet());
         }
     }
 
-    private static void checkAttributeNamesUniqueness(Map<String, QName> uniqueGeneratedClassesNames, Map<String, ModuleMXBeanEntry> result) {
+    private static void checkAttributeNamesUniqueness(final Map<String, QName> uniqueGeneratedClassesNames, final Map<String, ModuleMXBeanEntry> result) {
         for (Map.Entry<String, ModuleMXBeanEntry> entry : result.entrySet()) {
             checkUniqueRuntimeBeanAttributesName(entry.getValue(),
                     uniqueGeneratedClassesNames);
@@ -212,29 +215,30 @@ final class ModuleMXBeanEntryBuilder {
         return moduleIdentities;
     }
 
-    private Collection<ChoiceCaseNode> castChildNodesToChoiceCases(Set<DataSchemaNode> childNodes) {
+    private Collection<ChoiceCaseNode> castChildNodesToChoiceCases(final Set<DataSchemaNode> childNodes) {
         return Collections2.transform(childNodes, new Function<DataSchemaNode, ChoiceCaseNode>() {
             @Nullable
             @Override
-            public ChoiceCaseNode apply(@Nullable DataSchemaNode input) {
+            public ChoiceCaseNode apply(@Nullable final DataSchemaNode input) {
                 return (ChoiceCaseNode) input;
             }
         });
     }
 
-    private boolean areAllChildrenChoiceCaseNodes(Set<DataSchemaNode> childNodes) {
+    private boolean areAllChildrenChoiceCaseNodes(final Set<DataSchemaNode> childNodes) {
         for (DataSchemaNode childNode : childNodes) {
-            if (childNode instanceof ChoiceCaseNode == false)
+            if (childNode instanceof ChoiceCaseNode == false) {
                 return false;
+            }
         }
         return true;
     }
 
-    private <HAS_CHILDREN_AND_QNAME extends DataNodeContainer & SchemaNode> void processChoiceCaseNode(Map<String, ModuleMXBeanEntry> result,
-            Map<String, QName> uniqueGeneratedClassesNames, String configModulePrefix,
-            Map<String, IdentitySchemaNode> moduleIdentities,
-            Map<String, IdentitySchemaNode> unaugmentedModuleIdentities, AugmentationSchema augmentation,
-            DataSchemaNode when) {
+    private <HAS_CHILDREN_AND_QNAME extends DataNodeContainer & SchemaNode> void processChoiceCaseNode(final Map<String, ModuleMXBeanEntry> result,
+            final Map<String, QName> uniqueGeneratedClassesNames, final String configModulePrefix,
+            final Map<String, IdentitySchemaNode> moduleIdentities,
+            final Map<String, IdentitySchemaNode> unaugmentedModuleIdentities, final AugmentationSchema augmentation,
+            final DataSchemaNode when) {
 
         ChoiceCaseNode choiceCaseNode = (ChoiceCaseNode) when;
         if (choiceCaseNode.getConstraints() == null || choiceCaseNode.getConstraints().getWhenCondition() == null) {
@@ -301,12 +305,12 @@ final class ModuleMXBeanEntryBuilder {
             }
             checkState(Objects.equals(nullableDummyContainerName, moduleMXBeanEntry.getNullableDummyContainerName()),
                     "Mismatch in module " + moduleMXBeanEntry.toString() + " - dummy container must be present/missing in" +
-                            " both state and configuration");
+                    " both state and configuration");
         } else {
             ModuleMXBeanEntry.ModuleMXBeanEntryInitial initial = new ModuleMXBeanEntry.ModuleMXBeanEntryInitialBuilder()
-                    .setIdSchemaNode(moduleIdentity).setPackageName(packageName).setJavaNamePrefix(javaNamePrefix)
-                    .setNamespace(currentModule.getNamespace().toString()).setqName(ModuleUtil.getQName(currentModule))
-                    .build();
+            .setIdSchemaNode(moduleIdentity).setPackageName(packageName).setJavaNamePrefix(javaNamePrefix)
+            .setNamespace(currentModule.getNamespace().toString()).setqName(ModuleUtil.getQName(currentModule))
+            .build();
 
             // construct ModuleMXBeanEntry
             ModuleMXBeanEntry moduleMXBeanEntry = new ModuleMXBeanEntry(initial, yangToAttributes, providedServices,
@@ -319,8 +323,8 @@ final class ModuleMXBeanEntryBuilder {
         }
     }
 
-    private void checkUniqueRuntimeBeansGeneratedClasses(Map<String, QName> uniqueGeneratedClassesNames,
-            DataSchemaNode when, Collection<RuntimeBeanEntry> runtimeBeans) {
+    private void checkUniqueRuntimeBeansGeneratedClasses(final Map<String, QName> uniqueGeneratedClassesNames,
+            final DataSchemaNode when, final Collection<RuntimeBeanEntry> runtimeBeans) {
         for (RuntimeBeanEntry runtimeBean : runtimeBeans) {
             final String javaNameOfRuntimeMXBean = runtimeBean.getJavaNameOfRuntimeMXBean();
             if (uniqueGeneratedClassesNames.containsKey(javaNameOfRuntimeMXBean)) {
@@ -331,8 +335,8 @@ final class ModuleMXBeanEntryBuilder {
         }
     }
 
-    private static void checkUniqueRuntimeBeanAttributesName(ModuleMXBeanEntry mxBeanEntry,
-            Map<String, QName> uniqueGeneratedClassesNames) {
+    private static void checkUniqueRuntimeBeanAttributesName(final ModuleMXBeanEntry mxBeanEntry,
+            final Map<String, QName> uniqueGeneratedClassesNames) {
         for (RuntimeBeanEntry runtimeBeanEntry : mxBeanEntry.getRuntimeBeans()) {
             for (String runtimeAttName : runtimeBeanEntry.getYangPropertiesToTypesMap().keySet()) {
                 if (mxBeanEntry.getAttributes().keySet().contains(runtimeAttName)) {
@@ -344,8 +348,8 @@ final class ModuleMXBeanEntryBuilder {
         }
     }
 
-    private void checkUniqueAttributesWithGeneratedClass(Map<String, QName> uniqueGeneratedClassNames,
-            QName parentQName, Map<String, AttributeIfc> yangToAttributes) {
+    private void checkUniqueAttributesWithGeneratedClass(final Map<String, QName> uniqueGeneratedClassNames,
+            final QName parentQName, final Map<String, AttributeIfc> yangToAttributes) {
         for (Map.Entry<String, AttributeIfc> attr : yangToAttributes.entrySet()) {
             if (attr.getValue() instanceof TOAttribute) {
                 checkUniqueTOAttr(uniqueGeneratedClassNames, parentQName, (TOAttribute) attr.getValue());
@@ -357,7 +361,7 @@ final class ModuleMXBeanEntryBuilder {
         }
     }
 
-    private void checkUniqueTOAttr(Map<String, QName> uniqueGeneratedClassNames, QName parentQName, TOAttribute attr) {
+    private void checkUniqueTOAttr(final Map<String, QName> uniqueGeneratedClassNames, final QName parentQName, final TOAttribute attr) {
         final String upperCaseCamelCase = attr.getUpperCaseCammelCase();
         if (uniqueGeneratedClassNames.containsKey(upperCaseCamelCase)) {
             QName firstDefinedQName = uniqueGeneratedClassNames.get(upperCaseCamelCase);
@@ -367,9 +371,9 @@ final class ModuleMXBeanEntryBuilder {
         }
     }
 
-    private Collection<RuntimeBeanEntry> fillRuntimeBeans(DataNodeContainer dataNodeContainer, Module currentModule,
-            TypeProviderWrapper typeProviderWrapper, String packageName, String moduleLocalNameFromXPath,
-            String javaNamePrefix) {
+    private Collection<RuntimeBeanEntry> fillRuntimeBeans(final DataNodeContainer dataNodeContainer, final Module currentModule,
+            final TypeProviderWrapper typeProviderWrapper, final String packageName, final String moduleLocalNameFromXPath,
+            final String javaNamePrefix) {
 
         return RuntimeBeanEntry.extractClassNameToRuntimeBeanMap(packageName, dataNodeContainer, moduleLocalNameFromXPath,
                 typeProviderWrapper, javaNamePrefix, currentModule).values();
@@ -383,7 +387,7 @@ final class ModuleMXBeanEntryBuilder {
      * @param choiceCaseNode state or configuration case statement
      * @return either choiceCaseNode or its only child container
      */
-    private <HAS_CHILDREN_AND_QNAME extends DataNodeContainer & SchemaNode> HAS_CHILDREN_AND_QNAME getDataNodeContainer(ChoiceCaseNode choiceCaseNode) {
+    private <HAS_CHILDREN_AND_QNAME extends DataNodeContainer & SchemaNode> HAS_CHILDREN_AND_QNAME getDataNodeContainer(final ChoiceCaseNode choiceCaseNode) {
         Set<DataSchemaNode> childNodes = choiceCaseNode.getChildNodes();
         if (childNodes.size() == 1) {
             DataSchemaNode onlyChild = childNodes.iterator().next();
@@ -398,9 +402,9 @@ final class ModuleMXBeanEntryBuilder {
         return (HAS_CHILDREN_AND_QNAME) choiceCaseNode;
     }
 
-    private Map<String, AttributeIfc> fillConfiguration(DataNodeContainer dataNodeContainer, Module currentModule,
-            TypeProviderWrapper typeProviderWrapper, Map<QName, ServiceInterfaceEntry> qNamesToSIEs,
-            SchemaContext schemaContext, String packageName) {
+    private Map<String, AttributeIfc> fillConfiguration(final DataNodeContainer dataNodeContainer, final Module currentModule,
+            final TypeProviderWrapper typeProviderWrapper, final Map<QName, ServiceInterfaceEntry> qNamesToSIEs,
+            final SchemaContext schemaContext, final String packageName) {
         Map<String, AttributeIfc> yangToAttributes = new HashMap<>();
         Set<DataSchemaNode> childNodes = dataNodeContainer.getChildNodes();
         for (DataSchemaNode attrNode : childNodes) {
@@ -411,8 +415,8 @@ final class ModuleMXBeanEntryBuilder {
         return yangToAttributes;
     }
 
-    private Map<String, QName> findProvidedServices(IdentitySchemaNode moduleIdentity, Module currentModule,
-            Map<QName, ServiceInterfaceEntry> qNamesToSIEs, SchemaContext schemaContext) {
+    private Map<String, QName> findProvidedServices(final IdentitySchemaNode moduleIdentity, final Module currentModule,
+            final Map<QName, ServiceInterfaceEntry> qNamesToSIEs, final SchemaContext schemaContext) {
         Map<String, QName> result = new HashMap<>();
         for (UnknownSchemaNode unknownNode : moduleIdentity.getUnknownSchemaNodes()) {
             if (ConfigConstants.PROVIDED_SERVICE_EXTENSION_QNAME.equals(unknownNode.getNodeType())) {
@@ -425,9 +429,9 @@ final class ModuleMXBeanEntryBuilder {
         return result;
     }
 
-    private AttributeIfc getAttributeValue(DataSchemaNode attrNode, Module currentModule,
-            Map<QName, ServiceInterfaceEntry> qNamesToSIEs, TypeProviderWrapper typeProviderWrapper,
-            SchemaContext schemaContext, String packageName) {
+    private AttributeIfc getAttributeValue(final DataSchemaNode attrNode, final Module currentModule,
+            final Map<QName, ServiceInterfaceEntry> qNamesToSIEs, final TypeProviderWrapper typeProviderWrapper,
+            final SchemaContext schemaContext, final String packageName) {
 
         if (attrNode instanceof LeafSchemaNode) {
             // simple type
@@ -460,9 +464,9 @@ final class ModuleMXBeanEntryBuilder {
         }
     }
 
-    private Optional<? extends AbstractDependencyAttribute> extractDependency(DataNodeContainer dataNodeContainer,
-            DataSchemaNode attrNode, Module currentModule, Map<QName, ServiceInterfaceEntry> qNamesToSIEs,
-            SchemaContext schemaContext) {
+    private Optional<? extends AbstractDependencyAttribute> extractDependency(final DataNodeContainer dataNodeContainer,
+            final DataSchemaNode attrNode, final Module currentModule, final Map<QName, ServiceInterfaceEntry> qNamesToSIEs,
+            final SchemaContext schemaContext) {
         if (dataNodeContainer.getUses().size() == 1 && getChildNodeSizeWithoutUses(dataNodeContainer) == 0) {
             // reference
             UsesNode usesNode = dataNodeContainer.getUses().iterator().next();
@@ -490,7 +494,7 @@ final class ModuleMXBeanEntryBuilder {
         return Optional.absent();
     }
 
-    private int getChildNodeSizeWithoutUses(DataNodeContainer csn) {
+    private int getChildNodeSizeWithoutUses(final DataNodeContainer csn) {
         int result = 0;
         for (DataSchemaNode dsn : csn.getChildNodes()) {
             if (dsn.isAddedByUses() == false) {
@@ -500,8 +504,8 @@ final class ModuleMXBeanEntryBuilder {
         return result;
     }
 
-    private ServiceInterfaceEntry findSIE(String prefixAndIdentityLocalName, Module currentModule,
-            Map<QName, ServiceInterfaceEntry> qNamesToSIEs, SchemaContext schemaContext) {
+    private ServiceInterfaceEntry findSIE(final String prefixAndIdentityLocalName, final Module currentModule,
+            final Map<QName, ServiceInterfaceEntry> qNamesToSIEs, final SchemaContext schemaContext) {
 
         Matcher m = PREFIX_COLON_LOCAL_NAME.matcher(prefixAndIdentityLocalName);
         Module foundModule;
@@ -518,13 +522,13 @@ final class ModuleMXBeanEntryBuilder {
             foundModule = currentModule; // no prefix => SIE is in currentModule
             localSIName = prefixAndIdentityLocalName;
         }
-        QName siQName = new QName(foundModule.getNamespace(), foundModule.getRevision(), localSIName);
+        QName siQName = QName.create(foundModule.getNamespace(), foundModule.getRevision(), localSIName);
         ServiceInterfaceEntry sie = qNamesToSIEs.get(siQName);
         checkState(sie != null, "Cannot find referenced Service Interface by " + prefixAndIdentityLocalName);
         return sie;
     }
 
-    private ModuleImport findModuleImport(Module module, String prefix) {
+    private ModuleImport findModuleImport(final Module module, final String prefix) {
         for (ModuleImport moduleImport : module.getImports()) {
             if (moduleImport.getPrefix().equals(prefix)) {
                 return moduleImport;
@@ -534,13 +538,13 @@ final class ModuleMXBeanEntryBuilder {
     }
 
     @VisibleForTesting
-    static Matcher getWhenConditionMatcher(String prefix, RevisionAwareXPath whenConstraint) {
+    static Matcher getWhenConditionMatcher(final String prefix, final RevisionAwareXPath whenConstraint) {
         String xpathRegex = MODULE_CONDITION_XPATH_TEMPLATE.replace(MAGIC_STRING, prefix);
         Pattern pattern = Pattern.compile(xpathRegex);
         return pattern.matcher(whenConstraint.toString());
     }
 
-    String getConfigModulePrefixFromImport(Module currentModule) {
+    String getConfigModulePrefixFromImport(final Module currentModule) {
         for (ModuleImport currentImport : currentModule.getImports()) {
             if (currentImport.getModuleName().equals(ConfigConstants.CONFIG_MODULE)) {
                 return currentImport.getPrefix();
index 5fea8fd078dfbbd95ead79b2610eb16e7bf0a4fe..ccd701d1fb36a2bba58093999a21aa23c7ac5c08 100644 (file)
@@ -12,7 +12,7 @@ import org.opendaylight.yangtools.yang.model.api.Module;
 
 public class ModuleUtil {
 
-    public static QName getQName(Module currentModule){
-        return new QName(currentModule.getNamespace(), currentModule.getRevision(), currentModule.getName());
+    public static QName getQName(final Module currentModule) {
+        return QName.create(currentModule.getNamespace(), currentModule.getRevision(), currentModule.getName());
     }
 }
index c941d1504ddae409a9fdfa0c14ec4da957d1038e..23b071c817022ac0103f7cc01c4cc5f5482ba995 100644 (file)
@@ -13,6 +13,7 @@ import static com.google.common.base.Preconditions.checkState;
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Optional;
 import com.google.common.collect.Lists;
+
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
@@ -25,6 +26,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.TreeSet;
+
 import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
 import org.opendaylight.controller.config.yangjmxgenerator.attribute.JavaAttribute;
 import org.opendaylight.controller.config.yangjmxgenerator.attribute.ListAttribute;
@@ -65,11 +67,11 @@ public class RuntimeBeanEntry {
     private final Set<Rpc> rpcs;
 
     @VisibleForTesting
-    RuntimeBeanEntry(String packageName,
-            DataNodeContainer nodeForReporting, String yangName,
-            String javaNamePrefix, boolean isRoot,
-            Optional<String> keyYangName, List<AttributeIfc> attributes,
-            List<RuntimeBeanEntry> children, Set<Rpc> rpcs) {
+    RuntimeBeanEntry(final String packageName,
+            final DataNodeContainer nodeForReporting, final String yangName,
+            final String javaNamePrefix, final boolean isRoot,
+            final Optional<String> keyYangName, final List<AttributeIfc> attributes,
+            final List<RuntimeBeanEntry> children, final Set<Rpc> rpcs) {
 
         checkArgument(isRoot == false || keyYangName.isPresent() == false,
                 "Root RuntimeBeanEntry must not have key " + "set");
@@ -86,7 +88,7 @@ public class RuntimeBeanEntry {
         for (AttributeIfc a : attributes) {
             checkState(map.containsKey(a.getAttributeYangName()) == false,
                     "Attribute already defined: " + a.getAttributeYangName()
-                            + " in " + nodeForReporting);
+                    + " in " + nodeForReporting);
             map.put(a.getAttributeYangName(), a);
         }
 
@@ -110,9 +112,9 @@ public class RuntimeBeanEntry {
      *         not contain special configuration for it.
      */
     public static Map<String, RuntimeBeanEntry> extractClassNameToRuntimeBeanMap(
-            String packageName, DataNodeContainer container,
-            String moduleYangName, TypeProviderWrapper typeProviderWrapper,
-            String javaNamePrefix, Module currentModule) {
+            final String packageName, final DataNodeContainer container,
+            final String moduleYangName, final TypeProviderWrapper typeProviderWrapper,
+            final String javaNamePrefix, final Module currentModule) {
 
         Map<QName, Set<RpcDefinition>> identitiesToRpcs = getIdentitiesToRpcs(currentModule);
 
@@ -151,7 +153,7 @@ public class RuntimeBeanEntry {
     }
 
     private static Map<QName/* of identity */, Set<RpcDefinition>> getIdentitiesToRpcs(
-            Module currentModule) {
+            final Module currentModule) {
         // currently only looks for local identities (found in currentModule)
         Map<QName, Set<RpcDefinition>> result = new HashMap<>();
         for (IdentitySchemaNode identity : currentModule.getIdentities()) {
@@ -164,14 +166,16 @@ public class RuntimeBeanEntry {
             if (input != null) {
                 for (UsesNode uses : input.getUses()) {
 
-                    if (uses.getGroupingPath().getPath().size() != 1)
+                    if (uses.getGroupingPath().getPath().size() != 1) {
                         continue;
+                    }
 
                     // check grouping path
                     QName qname = uses.getGroupingPath().getPath().get(0);
                     if (false == qname
-                            .equals(ConfigConstants.RPC_CONTEXT_REF_GROUPING_QNAME))
+                            .equals(ConfigConstants.RPC_CONTEXT_REF_GROUPING_QNAME)) {
                         continue;
+                    }
 
                     for (SchemaNode refinedNode : uses.getRefines().values()) {
 
@@ -181,7 +185,7 @@ public class RuntimeBeanEntry {
                                     .equals(unknownSchemaNode.getNodeType())) {
                                 String localIdentityName = unknownSchemaNode
                                         .getNodeParameter();
-                                QName identityQName = new QName(
+                                QName identityQName = QName.create(
                                         currentModule.getNamespace(),
                                         currentModule.getRevision(),
                                         localIdentityName);
@@ -208,9 +212,9 @@ public class RuntimeBeanEntry {
      * in subtree.
      */
     private static AttributesRpcsAndRuntimeBeans extractSubtree(
-            String packageName, DataNodeContainer subtree,
-            TypeProviderWrapper typeProviderWrapper, Module currentModule,
-            Map<QName, Set<RpcDefinition>> identitiesToRpcs) {
+            final String packageName, final DataNodeContainer subtree,
+            final TypeProviderWrapper typeProviderWrapper, final Module currentModule,
+            final Map<QName, Set<RpcDefinition>> identitiesToRpcs) {
 
         List<AttributeIfc> attributes = Lists.newArrayList();
         // List<JavaAttribute> javaAttributes = new ArrayList<>();
@@ -258,7 +262,7 @@ public class RuntimeBeanEntry {
             if (ConfigConstants.RPC_CONTEXT_INSTANCE_EXTENSION_QNAME
                     .equals(unknownSchemaNode.getNodeType())) {
                 String localIdentityName = unknownSchemaNode.getNodeParameter();
-                QName identityQName = new QName(currentModule.getNamespace(),
+                QName identityQName = QName.create(currentModule.getNamespace(),
                         currentModule.getRevision(), localIdentityName);
                 Set<RpcDefinition> rpcDefinitions = identitiesToRpcs
                         .get(identityQName);
@@ -290,8 +294,8 @@ public class RuntimeBeanEntry {
                     for (DataSchemaNode childNode : sortAttributes(rpcDefinition.getInput()
                             .getChildNodes())) {
                         if (childNode.isAddedByUses() == false) { // skip
-                                                                  // refined
-                                                                  // context-instance
+                            // refined
+                            // context-instance
                             checkArgument(childNode instanceof LeafSchemaNode, "Unexpected type of rpc input type. "
                                     + "Currently only leafs and empty output nodes are supported, got " + childNode);
                             JavaAttribute javaAttribute = new JavaAttribute(
@@ -310,8 +314,8 @@ public class RuntimeBeanEntry {
                 attributes, rpcs);
     }
 
-    private static AttributeIfc getReturnTypeAttribute(DataSchemaNode child, TypeProviderWrapper typeProviderWrapper,
-                                                       String packageName) {
+    private static AttributeIfc getReturnTypeAttribute(final DataSchemaNode child, final TypeProviderWrapper typeProviderWrapper,
+            final String packageName) {
         if (child instanceof LeafSchemaNode) {
             LeafSchemaNode leaf = (LeafSchemaNode) child;
             return new JavaAttribute(leaf, typeProviderWrapper);
@@ -328,10 +332,10 @@ public class RuntimeBeanEntry {
         }
     }
 
-    private static Collection<DataSchemaNode> sortAttributes(Set<DataSchemaNode> childNodes) {
+    private static Collection<DataSchemaNode> sortAttributes(final Set<DataSchemaNode> childNodes) {
         final TreeSet<DataSchemaNode> dataSchemaNodes = new TreeSet<>(new Comparator<DataSchemaNode>() {
             @Override
-            public int compare(DataSchemaNode o1, DataSchemaNode o2) {
+            public int compare(final DataSchemaNode o1, final DataSchemaNode o2) {
                 return o1.getQName().getLocalName().compareTo(o2.getQName().getLocalName());
             }
         });
@@ -339,20 +343,21 @@ public class RuntimeBeanEntry {
         return dataSchemaNodes;
     }
 
-    private static boolean isInnerStateBean(DataSchemaNode child) {
+    private static boolean isInnerStateBean(final DataSchemaNode child) {
         for (UnknownSchemaNode unknownSchemaNode : child
                 .getUnknownSchemaNodes()) {
             if (unknownSchemaNode.getNodeType().equals(
-                    ConfigConstants.INNER_STATE_BEAN_EXTENSION_QNAME))
+                    ConfigConstants.INNER_STATE_BEAN_EXTENSION_QNAME)) {
                 return true;
+            }
         }
         return false;
     }
 
-    private static RuntimeBeanEntry createHierarchical(String packageName,
-            ListSchemaNode listSchemaNode,
-            TypeProviderWrapper typeProviderWrapper, Module currentModule,
-            Map<QName, Set<RpcDefinition>> identitiesToRpcs) {
+    private static RuntimeBeanEntry createHierarchical(final String packageName,
+            final ListSchemaNode listSchemaNode,
+            final TypeProviderWrapper typeProviderWrapper, final Module currentModule,
+            final Map<QName, Set<RpcDefinition>> identitiesToRpcs) {
 
         // supported are numeric types, strings, enums
         // get all attributes
@@ -387,10 +392,10 @@ public class RuntimeBeanEntry {
         return rbFromAttributes;
     }
 
-    private static RuntimeBeanEntry createRoot(String packageName,
-            DataNodeContainer nodeForReporting, String attributeYangName,
-            List<AttributeIfc> attributes, String javaNamePrefix,
-            List<RuntimeBeanEntry> children, Set<Rpc> rpcs) {
+    private static RuntimeBeanEntry createRoot(final String packageName,
+            final DataNodeContainer nodeForReporting, final String attributeYangName,
+            final List<AttributeIfc> attributes, final String javaNamePrefix,
+            final List<RuntimeBeanEntry> children, final Set<Rpc> rpcs) {
         return new RuntimeBeanEntry(packageName, nodeForReporting,
                 attributeYangName, javaNamePrefix, true,
                 Optional.<String> absent(), attributes, children, rpcs);
@@ -442,8 +447,8 @@ public class RuntimeBeanEntry {
         private final Set<Rpc> rpcs;
 
         public AttributesRpcsAndRuntimeBeans(
-                List<RuntimeBeanEntry> runtimeBeanEntries,
-                List<AttributeIfc> attributes, Set<Rpc> rpcs) {
+                final List<RuntimeBeanEntry> runtimeBeanEntries,
+                final List<AttributeIfc> attributes, final Set<Rpc> rpcs) {
             this.runtimeBeanEntries = runtimeBeanEntries;
             this.attributes = attributes;
             this.rpcs = rpcs;
@@ -472,8 +477,8 @@ public class RuntimeBeanEntry {
         private final AttributeIfc returnType;
         private final String yangName;
 
-        Rpc(AttributeIfc returnType, String name, String yangName,
-                List<JavaAttribute> parameters) {
+        Rpc(final AttributeIfc returnType, final String name, final String yangName,
+                final List<JavaAttribute> parameters) {
             this.returnType = returnType;
             this.name = name;
             this.parameters = parameters;
@@ -503,12 +508,12 @@ public class RuntimeBeanEntry {
         return getJavaNameOfRuntimeMXBean(javaNamePrefix);
     }
 
-    public String getFullyQualifiedName(String typeName) {
+    public String getFullyQualifiedName(final String typeName) {
         return FullyQualifiedNameHelper.getFullyQualifiedName(packageName,
                 typeName);
     }
 
-    private static String getJavaNameOfRuntimeMXBean(String javaNamePrefix) {
+    private static String getJavaNameOfRuntimeMXBean(final String javaNamePrefix) {
         return javaNamePrefix + MXBEAN_SUFFIX;
     }
 
index dd44246867abb9af1e51bfe1bc5dbd8ea8c63f91..fab273c60093b529931e5f0ce4f02f9198327ff7 100644 (file)
@@ -7,7 +7,35 @@
  */
 package org.opendaylight.controller.config.yangjmxgenerator;
 
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThat;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+
 import com.google.common.collect.Sets;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+
+import javax.management.openmbean.ArrayType;
+import javax.management.openmbean.CompositeType;
+import javax.management.openmbean.SimpleType;
+
 import org.junit.Before;
 import org.junit.Test;
 import org.opendaylight.controller.config.yangjmxgenerator.attribute.AttributeIfc;
@@ -25,32 +53,6 @@ import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
 import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
 
-import javax.management.openmbean.ArrayType;
-import javax.management.openmbean.CompositeType;
-import javax.management.openmbean.SimpleType;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.regex.Matcher;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThat;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
 public class ModuleMXBeanEntryTest extends AbstractYangTest {
 
     public static final String PACKAGE_NAME = "pack2";
@@ -95,7 +97,7 @@ public class ModuleMXBeanEntryTest extends AbstractYangTest {
                 PACKAGE_NAME,identitiesToSIs));
         Map<String /* identity local name */, ModuleMXBeanEntry> namesToMBEs = ModuleMXBeanEntry
                 .create(jmxImplModule, modulesToSIEs, context, new TypeProviderWrapper(new TypeProviderImpl(context))
-                        , PACKAGE_NAME);
+                , PACKAGE_NAME);
         Map<String, AttributeIfc> attributes = namesToMBEs.get("impl-netconf")
                 .getAttributes();
 
@@ -120,7 +122,7 @@ public class ModuleMXBeanEntryTest extends AbstractYangTest {
         assertThat(threadFactoryAttribute.getType().getName(), is("ObjectName"));
     }
 
-    private void assertCorrectAttributesSize(Map<String, ModuleMXBeanEntry> namesToMBEs, Map<String, AttributeIfc> attributes) {
+    private void assertCorrectAttributesSize(final Map<String, ModuleMXBeanEntry> namesToMBEs, final Map<String, AttributeIfc> attributes) {
         assertEquals(14, attributes.size());
         assertEquals(1, namesToMBEs.get("impl-netconf").getRuntimeBeans().size());
         assertEquals(2, namesToMBEs.get("impl-netconf").getRuntimeBeans().iterator().next().getAttributes().size());
@@ -131,10 +133,11 @@ public class ModuleMXBeanEntryTest extends AbstractYangTest {
     }
 
     protected RuntimeBeanEntry findFirstByYangName(
-            Collection<RuntimeBeanEntry> runtimeBeans, String yangName) {
+            final Collection<RuntimeBeanEntry> runtimeBeans, final String yangName) {
         for (RuntimeBeanEntry rb : runtimeBeans) {
-            if (yangName.equals(rb.getYangName()))
+            if (yangName.equals(rb.getYangName())) {
                 return rb;
+            }
         }
         throw new IllegalArgumentException("Yang name not found:" + yangName
                 + " in " + runtimeBeans);
@@ -150,7 +153,7 @@ public class ModuleMXBeanEntryTest extends AbstractYangTest {
                 "/config:modules/config:module/config:type=\"threadpool-dynamic\"");
     }
 
-    private void assertMatches(String prefix, String input) {
+    private void assertMatches(final String prefix, final String input) {
         RevisionAwareXPath whenConstraint = mock(RevisionAwareXPath.class);
         doReturn(input).when(whenConstraint).toString();
         Matcher output = ModuleMXBeanEntryBuilder.getWhenConditionMatcher(prefix,
@@ -181,7 +184,7 @@ public class ModuleMXBeanEntryTest extends AbstractYangTest {
                         is((Type) Types.typeForClass(Long.class)));
             }
             // check dependency on thread factory
-            QName threadfactoryQName = new QName(THREADS_NAMESPACE,
+            QName threadfactoryQName = QName.create(THREADS_NAMESPACE,
                     THREADS_REVISION_DATE, "threadfactory");
             ServiceInterfaceEntry threadFactorySIEntry = modulesToSIEs
                     .get(threadfactoryQName);
@@ -192,7 +195,7 @@ public class ModuleMXBeanEntryTest extends AbstractYangTest {
 
             DataSchemaNode mockedDataSchemaNode = mock(DataSchemaNode.class);
             doReturn(Collections.emptyList()).when(mockedDataSchemaNode)
-                    .getUnknownSchemaNodes();
+            .getUnknownSchemaNodes();
             doReturn(threadfactoryQName).when(mockedDataSchemaNode).getQName();
             AttributeIfc expectedDependencyAttribute = new DependencyAttribute(
                     mockedDataSchemaNode, threadFactorySIEntry,
@@ -200,7 +203,7 @@ public class ModuleMXBeanEntryTest extends AbstractYangTest {
             assertThat(actualThreadFactory, is(expectedDependencyAttribute));
             assertThat(
                     dynamicThreadPool
-                            .getFullyQualifiedName("DynamicThreadPoolModuleMXBean"),
+                    .getFullyQualifiedName("DynamicThreadPoolModuleMXBean"),
                     is(PACKAGE_NAME + ".DynamicThreadPoolModuleMXBean"));
             assertThat(dynamicThreadPool.getNullableDescription(),
                     is("threadpool-dynamic description"));
index eed86951033bc5ec2aa5251e4f187ea0f0f3c1a9..f22edbf948f0ba93b77346cc0b55786fcc032ab5 100644 (file)
@@ -7,7 +7,12 @@
  */
 package org.opendaylight.controller.config.yangjmxgenerator;
 
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThat;
+
 import com.google.common.collect.Sets;
+
 import java.net.URI;
 import java.net.URISyntaxException;
 import java.text.ParseException;
@@ -20,13 +25,11 @@ import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;
+
 import org.hamcrest.CoreMatchers;
 import org.junit.Test;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertThat;
 
 public class ServiceInterfaceEntryTest extends AbstractYangTest {
     public static final String PACKAGE_NAME = "packages.sis";
@@ -53,15 +56,15 @@ public class ServiceInterfaceEntryTest extends AbstractYangTest {
         }
     }
 
-    public static final QName EVENTBUS_QNAME = new QName(THREADS_NAMESPACE,
+    public static final QName EVENTBUS_QNAME = QName.create(THREADS_NAMESPACE,
             THREADS_REVISION_DATE, "eventbus");
-    public static final QName THREADFACTORY_QNAME = new QName(
+    public static final QName THREADFACTORY_QNAME = QName.create(
             THREADS_NAMESPACE, THREADS_REVISION_DATE, "threadfactory");
-    public static final QName THREADPOOL_QNAME = new QName(THREADS_NAMESPACE,
+    public static final QName THREADPOOL_QNAME = QName.create(THREADS_NAMESPACE,
             THREADS_REVISION_DATE, "threadpool");
-    public static final QName SCHEDULED_THREADPOOL_QNAME = new QName(
+    public static final QName SCHEDULED_THREADPOOL_QNAME = QName.create(
             THREADS_NAMESPACE, THREADS_REVISION_DATE, "scheduled-threadpool");
-    public static final QName SCHEDULED_EXECUTOR_SERVICE_QNAME = new QName(
+    public static final QName SCHEDULED_EXECUTOR_SERVICE_QNAME = QName.create(
             THREADS_NAMESPACE, THREADS_REVISION_DATE,
             "scheduled-executor-service");
     public static final String SCHEDULED_THREADPOOL_INTERFACE_NAME = "ScheduledThreadPoolServiceInterface";
@@ -133,9 +136,10 @@ public class ServiceInterfaceEntryTest extends AbstractYangTest {
                 + SCHEDULED_THREADPOOL_INTERFACE_NAME));
     }
 
-    static String trimInnerSpacesOrNull(String input) {
-        if (input == null)
+    static String trimInnerSpacesOrNull(final String input) {
+        if (input == null) {
             return null;
+        }
         return input.replaceAll("\\s{2,}", " ");
     }
 }
diff --git a/opendaylight/config/yang-test/.gitignore b/opendaylight/config/yang-test/.gitignore
deleted file mode 100644 (file)
index 1439354..0000000
+++ /dev/null
@@ -1 +0,0 @@
-src/main/java/org/opendaylight/controller/config/yang/test/impl/*
diff --git a/opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/.gitignore b/opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/.gitignore
new file mode 100644 (file)
index 0000000..27d1535
--- /dev/null
@@ -0,0 +1 @@
+*.java
diff --git a/opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/DepTestImplModule.java b/opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/DepTestImplModule.java
deleted file mode 100644 (file)
index 6046665..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-package org.opendaylight.controller.config.yang.test.impl;
-public class DepTestImplModule extends org.opendaylight.controller.config.yang.test.impl.AbstractDepTestImplModule {
-    public DepTestImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
-        super(identifier, dependencyResolver);
-    }
-
-    public DepTestImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.controller.config.yang.test.impl.DepTestImplModule oldModule, java.lang.AutoCloseable oldInstance) {
-        super(identifier, dependencyResolver, oldModule, oldInstance);
-    }
-
-    @Override
-    public void customValidation() {
-        // add custom validation form module attributes here.
-    }
-
-    @Override
-    public java.lang.AutoCloseable createInstance() {
-        return new AutoCloseable() {
-            @Override
-            public void close() throws Exception {
-            }
-        };
-
-    }
-
-}
diff --git a/opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/DepTestImplModuleFactory.java b/opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/DepTestImplModuleFactory.java
deleted file mode 100644 (file)
index 026dd9a..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-package org.opendaylight.controller.config.yang.test.impl;
-public class DepTestImplModuleFactory extends org.opendaylight.controller.config.yang.test.impl.AbstractDepTestImplModuleFactory {
-
-}
diff --git a/opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/IdentityTestModule.java b/opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/IdentityTestModule.java
deleted file mode 100644 (file)
index bda3548..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-package org.opendaylight.controller.config.yang.test.impl;
-public class IdentityTestModule extends org.opendaylight.controller.config.yang.test.impl.AbstractIdentityTestModule {
-    public IdentityTestModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
-        super(identifier, dependencyResolver);
-    }
-
-    public IdentityTestModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.controller.config.yang.test.impl.IdentityTestModule oldModule, java.lang.AutoCloseable oldInstance) {
-        super(identifier, dependencyResolver, oldModule, oldInstance);
-    }
-
-    @Override
-    public void customValidation() {
-        // add custom validation form module attributes here.
-    }
-
-    @Override
-    public java.lang.AutoCloseable createInstance() {
-        org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(getClass());
-        logger.info("Afi: {}", getAfi());
-        logger.info("Afi class: {}", getAfiIdentity());
-
-        for (Identities identities : getIdentities()) {
-            logger.info("Identities Afi class: {}", identities.resolveAfi());
-            logger.info("Identities Safi class: {}", identities.resolveSafi());
-
-        }
-        logger.info("IdentityContainer Afi class: {}", getIdentitiesContainer().resolveAfi());
-
-        return new AutoCloseable() {
-            @Override
-            public void close() throws Exception {
-            }
-        };
-
-    }
-
-}
diff --git a/opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/IdentityTestModuleFactory.java b/opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/IdentityTestModuleFactory.java
deleted file mode 100644 (file)
index 3a4348d..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-package org.opendaylight.controller.config.yang.test.impl;
-public class IdentityTestModuleFactory extends org.opendaylight.controller.config.yang.test.impl.AbstractIdentityTestModuleFactory {
-
-}
diff --git a/opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/MultipleDependenciesModuleStub.txt b/opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/MultipleDependenciesModuleStub.txt
new file mode 100644 (file)
index 0000000..80c1e54
--- /dev/null
@@ -0,0 +1,5 @@
+        return new AutoCloseable() {
+            @Override
+            public void close() throws Exception {
+            }
+        };
diff --git a/opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/NetconfTestImplModule.java b/opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/NetconfTestImplModule.java
deleted file mode 100644 (file)
index ab43dea..0000000
+++ /dev/null
@@ -1,22 +0,0 @@
-package org.opendaylight.controller.config.yang.test.impl;
-public class NetconfTestImplModule extends org.opendaylight.controller.config.yang.test.impl.AbstractNetconfTestImplModule {
-    public NetconfTestImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
-        super(identifier, dependencyResolver);
-    }
-
-    public NetconfTestImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModule oldModule, java.lang.AutoCloseable oldInstance) {
-        super(identifier, dependencyResolver, oldModule, oldInstance);
-    }
-
-    @Override
-    public void customValidation() {
-        // add custom validation form module attributes here.
-    }
-
-    @Override
-    public java.lang.AutoCloseable createInstance() {
-return NetconfTestImplModuleUtil.registerRuntimeBeans(this);
-
-    }
-
-}
diff --git a/opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/NetconfTestImplModuleFactory.java b/opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/NetconfTestImplModuleFactory.java
deleted file mode 100644 (file)
index 587089b..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-package org.opendaylight.controller.config.yang.test.impl;
-public class NetconfTestImplModuleFactory extends org.opendaylight.controller.config.yang.test.impl.AbstractNetconfTestImplModuleFactory {
-
-}
diff --git a/opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/TestImplModule.java b/opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/TestImplModule.java
deleted file mode 100644 (file)
index 2880b46..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-package org.opendaylight.controller.config.yang.test.impl;
-public class TestImplModule extends org.opendaylight.controller.config.yang.test.impl.AbstractTestImplModule {
-    public TestImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
-        super(identifier, dependencyResolver);
-    }
-
-    public TestImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.controller.config.yang.test.impl.TestImplModule oldModule, java.lang.AutoCloseable oldInstance) {
-        super(identifier, dependencyResolver, oldModule, oldInstance);
-    }
-
-    @Override
-    public void customValidation() {
-        // add custom validation form module attributes here.
-    }
-
-    @Override
-    public java.lang.AutoCloseable createInstance() {
-        return new AutoCloseable() {
-            @Override
-            public void close() throws Exception {
-            }
-        };
-
-    }
-
-}
diff --git a/opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/TestImplModuleFactory.java b/opendaylight/config/yang-test/src/main/java/org/opendaylight/controller/config/yang/test/impl/TestImplModuleFactory.java
deleted file mode 100644 (file)
index de9ac2f..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-
-
-package org.opendaylight.controller.config.yang.test.impl;
-public class TestImplModuleFactory extends org.opendaylight.controller.config.yang.test.impl.AbstractTestImplModuleFactory {
-
-}
@@ -1,13 +1,34 @@
 
 
-package org.opendaylight.controller.config.yang.test.impl;
+/*
+ * 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
+ */
 
-import com.google.common.collect.Lists;
+package org.opendaylight.controller.config.yang.test.util;
 
+import com.google.common.collect.Lists;
 import java.util.List;
+import org.opendaylight.controller.config.yang.test.impl.Asdf;
+import org.opendaylight.controller.config.yang.test.impl.Deep2;
+import org.opendaylight.controller.config.yang.test.impl.Deep3;
+import org.opendaylight.controller.config.yang.test.impl.Deep4;
+import org.opendaylight.controller.config.yang.test.impl.InnerInnerRunningDataRuntimeMXBean;
+import org.opendaylight.controller.config.yang.test.impl.InnerRunningDataAdditionalRuntimeMXBean;
+import org.opendaylight.controller.config.yang.test.impl.InnerRunningDataRuntimeMXBean;
+import org.opendaylight.controller.config.yang.test.impl.InnerRunningDataRuntimeRegistration;
+import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModule;
+import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplRuntimeMXBean;
+import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplRuntimeRegistration;
+import org.opendaylight.controller.config.yang.test.impl.NotStateBean;
+import org.opendaylight.controller.config.yang.test.impl.RetValContainer;
+import org.opendaylight.controller.config.yang.test.impl.RetValList;
 
 public class NetconfTestImplModuleUtil {
-    static NetconfTestImplRuntimeRegistration registerRuntimeBeans(final NetconfTestImplModule module) {
+    public static NetconfTestImplRuntimeRegistration registerRuntimeBeans(final NetconfTestImplModule module) {
         NetconfTestImplRuntimeRegistration reg = module.getRootRuntimeBeanRegistratorWrapper().register(new NetconfTestImplRuntimeMXBean() {
 
             @Override
index 4b006bc72e52c3026130db4b556e62fd340523da..e7aa64d7a621cc5ecdfa4781c6389e576b7865c1 100644 (file)
@@ -41,6 +41,12 @@ module config-test-impl {
         config:java-name-prefix IdentityTest;
     }
 
+    identity multiple-dependencies {
+        base config:module-type;
+        config:provided-service test:testing;
+        config:java-name-prefix MultipleDependencies;
+    }
+
     augment "/config:modules/config:module/config:configuration" {
             case impl-identity-test {
                 when "/config:modules/config:module/config:type = 'impl-identity-test'";
@@ -444,6 +450,24 @@ module config-test-impl {
         }
     }
 
+
+    augment "/config:modules/config:module/config:configuration" {
+        case multiple-dependencies {
+            when "/config:modules/config:module/config:type = 'multiple-dependencies'";
+            container multiple-dependencies {
+                list testing-deps {
+                    uses config:service-ref {
+                        refine type {
+                            mandatory true;
+                            config:required-identity test:testing;
+                        }
+                    }
+                }
+            }
+        }
+    }
+
+
     identity test-rpc;
     identity inner-test-rpc;
     identity inner-inner-test-rpc;
diff --git a/opendaylight/config/yang-test/src/test/java/org/opendaylight/controller/config/yang/test/impl/MultipleDependenciesModuleTest.java b/opendaylight/config/yang-test/src/test/java/org/opendaylight/controller/config/yang/test/impl/MultipleDependenciesModuleTest.java
new file mode 100644 (file)
index 0000000..2df15d0
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.config.yang.test.impl;
+
+import static java.util.Arrays.asList;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.opendaylight.controller.config.api.jmx.ObjectNameUtil.getInstanceName;
+import static org.opendaylight.controller.config.api.jmx.ObjectNameUtil.getTransactionName;
+
+import java.util.List;
+import javax.management.ObjectName;
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
+import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
+import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
+
+public class MultipleDependenciesModuleTest extends AbstractConfigTest {
+    private static final MultipleDependenciesModuleFactory factory = new MultipleDependenciesModuleFactory();
+
+    @Before
+    public void setUp() throws Exception {
+        super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, factory));
+    }
+
+    @Test
+    public void testMultipleDependencies() throws Exception {
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
+        ObjectName d1 = transaction.createModule(factory.getImplementationName(), "d1");
+        ObjectName d2 = transaction.createModule(factory.getImplementationName(), "d2");
+
+        assertEquals(transaction.getTransactionName(), getTransactionName(d1));
+
+        ObjectName parent = transaction.createModule(factory.getImplementationName(), "parent");
+        MultipleDependenciesModuleMXBean multipleDependenciesModuleMXBean = transaction.newMXBeanProxy(parent, MultipleDependenciesModuleMXBean.class);
+        multipleDependenciesModuleMXBean.setTestingDeps(asList(d1, d2));
+        List<ObjectName> found = multipleDependenciesModuleMXBean.getTestingDeps();
+        ObjectName d1WithoutTxName = found.get(0);
+        assertEquals(getInstanceName(d1), getInstanceName(d1WithoutTxName));
+        // check that transaction name gets stripped automatically from attribute.
+        // d1,2 contained tx name, found doesn't
+        assertNull(getTransactionName(d1WithoutTxName));
+        transaction.commit();
+    }
+}
index 7970b3aa00f6fc38bf334ce93b8b52a8597581b2..4ef0b8e86bf926062ff0e7071775efd79d0f531a 100644 (file)
       <version>${karaf.version}</version>
       <type>kar</type>
     </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>base-features</artifactId>
+      <version>${project.version}</version>
+      <type>kar</type>
+    </dependency>
     <dependency>
       <groupId>org.opendaylight.controller</groupId>
       <artifactId>karaf.branding</artifactId>
       <type>xml</type>
       <scope>runtime</scope>
     </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>base-features</artifactId>
+      <version>${project.parent.version}</version>
+      <classifier>features</classifier>
+      <type>xml</type>
+      <scope>runtime</scope>
+    </dependency>
     <!-- scope is compile so all features (there is only one) are installed
             into startup.properties and the feature repo itself is not installed -->
     <dependency>
       <groupId>org.opendaylight.controller</groupId>
-      <artifactId>base-features</artifactId>
+      <artifactId>extras-features</artifactId>
       <version>${project.version}</version>
-      <type>pom</type>
+      <type>kar</type>
       <scope>runtime</scope>
     </dependency>
     <dependency>
       <groupId>org.opendaylight.controller</groupId>
-      <artifactId>config-features</artifactId>
-      <version>${config.version}</version>
+      <artifactId>features-odl-protocol-framework</artifactId>
+      <version>${protocol-framework.version}</version>
       <classifier>features</classifier>
       <type>xml</type>
       <scope>runtime</scope>
     </dependency>
-    <!--<dependency>
+    <dependency>
       <groupId>org.opendaylight.controller</groupId>
-      <artifactId>base-features</artifactId>
-      <version>${project.version}</version>
+      <artifactId>netconf-features</artifactId>
+      <version>${netconf.version}</version>
       <classifier>features</classifier>
       <type>xml</type>
       <scope>runtime</scope>
-    </dependency>-->
-    <!-- <dependency>
+    </dependency>
+    <dependency>
       <groupId>org.opendaylight.controller</groupId>
-      <artifactId>controller-features</artifactId>
-      <version>${project.version}</version>
+      <artifactId>config-features</artifactId>
+      <version>${config.version}</version>
       <classifier>features</classifier>
       <type>xml</type>
       <scope>runtime</scope>
     </dependency>
-  -->
     <dependency>
       <groupId>org.opendaylight.controller</groupId>
-      <artifactId>mdsal-features</artifactId>
-      <version>${mdsal.version}</version>
+      <artifactId>features-adsal</artifactId>
+      <version>${sal.version}</version>
       <classifier>features</classifier>
       <type>xml</type>
       <scope>runtime</scope>
     </dependency>
     <dependency>
-      <groupId>org.opendaylight.yangtools</groupId>
-      <artifactId>features-yangtools</artifactId>
-      <version>${yangtools.version}</version>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>mdsal-features</artifactId>
+      <version>${mdsal.version}</version>
       <classifier>features</classifier>
       <type>xml</type>
       <scope>runtime</scope>
diff --git a/opendaylight/distribution/opendaylight-karaf/src/main/resources/configuration/initial/02-clustering.xml b/opendaylight/distribution/opendaylight-karaf/src/main/resources/configuration/initial/02-clustering.xml
deleted file mode 100644 (file)
index 7853b86..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-<snapshot>
-    <configuration>
-        <data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
-            <modules xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
-                <module>
-                   <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote:rpc">prefix:remote-zeromq-rpc-server</type>
-                   <name>remoter</name>
-                   <port xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote:rpc">5666</port>
-                   <dom-broker xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote:rpc">
-                       <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">prefix:dom-broker-osgi-registry</type>
-                       <name>dom-broker</name>
-                   </dom-broker>
-               </module>
-            </modules>
-            <services xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
-            </services>
-        </data>
-    </configuration>
-
-    <required-capabilities>
-       <capability>urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom?module=opendaylight-md-sal-dom&amp;revision=2013-10-28</capability>
-        <capability>urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl?module=opendaylight-sal-dom-broker-impl&amp;revision=2013-10-28</capability>
-        <capability>urn:opendaylight:params:xml:ns:yang:controller:md:sal:common?module=opendaylight-md-sal-common&amp;revision=2013-10-28</capability>
-        <capability>urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote:rpc?module=odl-sal-dom-rpc-remote-cfg&amp;revision=2013-10-28</capability>
-    </required-capabilities>
-</snapshot>
-
index 502e1a261c713b1ea030ec014e663dcb82f4b51b..6c1ca421c257ab81807c20f4a939d556cb5338c6 100644 (file)
@@ -1,11 +1,17 @@
 # Extra packages to import from the boot class loader
 org.osgi.framework.system.packages.extra=org.apache.karaf.branding,sun.reflect,sun.reflect.misc,sun.misc,sun.nio.ch
 
+# https://bugs.eclipse.org/bugs/show_bug.cgi?id=325578
+# Extend the framework to avoid the resources to be presented with
+# a URL of type bundleresource: but to be presented as file:
+osgi.hook.configurators.include=org.eclipse.virgo.kernel.equinox.extensions.hooks.ExtensionsHookConfigurator
 
 # Embedded Tomcat configuration File
 org.eclipse.gemini.web.tomcat.config.path=configuration/tomcat-server.xml
 org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true
 
+# Use Equinox as default OSGi Framework Implementation
+karaf.framework=equinox
 
 # Netconf startup configuration
 netconf.tcp.address=127.0.0.1
index 288fe629f806ff74a3c241a3d27e95a39e86fcf5..ca8c83c380aea4f1c51c801a3e846a82e364fbeb 100644 (file)
@@ -7,7 +7,7 @@ mvn\:org.ops4j.pax.swissbox/pax-swissbox-bnd/1.7.0 = 5
 mvn\:org.ops4j.pax.url/pax-url-maven-commons/1.6.0 = 5
 mvn\:org.ops4j.pax.url/pax-url-aether/1.6.0 = 5
 mvn\:org.ops4j.pax.url/pax-url-wrap/1.6.0 = 5
-#mvn\:javax.annotation/javax.annotation-api/1.2 = 5
+mvn\:javax.annotation/javax.annotation-api/1.2 = 5
 mvn\:org.ops4j.pax.logging/pax-logging-api/1.7.2 = 8
 mvn\:org.ops4j.pax.logging/pax-logging-service/1.7.2 = 8
 mvn\:org.apache.karaf.service/org.apache.karaf.service.guard/3.0.1 = 10
index 149154334dbb77172270fbf32503d6b5334a1497..d238ee75cc1f0bd8df7bb52931c4499917f56db9 100644 (file)
           <groupId>org.opendaylight.controller</groupId>
           <artifactId>config-manager</artifactId>
         </dependency>
+        <dependency>
+          <groupId>org.opendaylight.controller</groupId>
+          <artifactId>config-util</artifactId>
+        </dependency>
         <dependency>
           <groupId>org.opendaylight.controller</groupId>
           <artifactId>config-netconf-connector</artifactId>
           <artifactId>protocol-framework</artifactId>
         </dependency>
 
-        <!-- clustering -->
-        <dependency>
-          <groupId>org.opendaylight.controller</groupId>
-          <artifactId>remoterpc-routingtable.implementation</artifactId>
-          <version>${mdsal.version}</version>
-        </dependency>
         <dependency>
           <groupId>org.opendaylight.controller</groupId>
           <artifactId>sal-binding-api</artifactId>
           <groupId>org.opendaylight.controller</groupId>
           <artifactId>sal-remote</artifactId>
         </dependency>
-        <dependency>
-          <groupId>org.opendaylight.controller</groupId>
-          <artifactId>sal-remoterpc-connector</artifactId>
-        </dependency>
         <dependency>
           <groupId>org.opendaylight.controller</groupId>
           <artifactId>sal-rest-connector</artifactId>
           <groupId>org.opendaylight.controller.model</groupId>
           <artifactId>model-flow-base</artifactId>
         </dependency>
-        <dependency>
-          <groupId>org.opendaylight.controller.model</groupId>
-          <artifactId>model-flow-management</artifactId>
-        </dependency>
         <dependency>
           <groupId>org.opendaylight.controller.model</groupId>
           <artifactId>model-flow-service</artifactId>
index f05afbb346f7f157162b313981874c4d3d6bdd40..b2fc3cb386ffa4525fb42dd3fae685c7b6a39e97 100644 (file)
@@ -113,8 +113,8 @@ org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true
 ovsdb.listenPort=6640
 
 # ovsdb creates Openflow nodes/bridges. This configuration configures the bridge's Openflow version.
-# default Openflow version = 1.0, we also support 1.3.
-ovsdb.of.version=1.3
+# default Openflow version = 1.3, we also support 1.0.
+ovsdb.of.version=1.3
 
 # TLS configuration
 # To enable TLS, set secureChannelEnabled=true and specify the location of controller Java KeyStore and TrustStore files.
@@ -149,3 +149,6 @@ hosttracker.keyscheme=IP
 lisp.mappingOverwrite = true
 # Enable the Solicit-Map-Request (SMR) mechanism
 lisp.smr = false
+
+#RESTConf websocket listen port (default is 8181)
+restconf.websocket.port=8181
index 00abf6cf339a036de0fe3285fdfb73a817232808..c148b83a7a136d47905bcbb0019169e3f2c097f3 100644 (file)
@@ -7,48 +7,61 @@
   -->
 
 <Host>
-    <!-- Filters are allowed here, only serving as a template -->
-    <filter-template>
-        <filter-name>CorsFilter</filter-name>
-        <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
-        <init-param>
-            <param-name>cors.allowed.origins</param-name>
-            <param-value>*</param-value>
-        </init-param>
-        <init-param>
-            <param-name>cors.allowed.methods</param-name>
-            <param-value>GET,POST,HEAD,OPTIONS,PUT,DELETE</param-value>
-        </init-param>
-        <init-param>
-            <param-name>cors.allowed.headers</param-name>
-            <param-value>Content-Type,X-Requested-With,accept,authorization,
-                origin,Origin,Access-Control-Request-Method,Access-Control-Request-Headers
-            </param-value>
-        </init-param>
-        <init-param>
-            <param-name>cors.exposed.headers</param-name>
-            <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
-        </init-param>
-        <init-param>
-            <param-name>cors.support.credentials</param-name>
-            <param-value>true</param-value>
-        </init-param>
-        <init-param>
-            <param-name>cors.preflight.maxage</param-name>
-            <param-value>10</param-value>
-        </init-param>
-    </filter-template>
+  <!-- Filters are allowed here, only serving as a template -->
+  <filter-template>
+    <filter-name>CorsFilter</filter-name>
+    <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
+    <init-param>
+      <param-name>cors.allowed.origins</param-name>
+      <param-value>*</param-value>
+    </init-param>
+    <init-param>
+      <param-name>cors.allowed.methods</param-name>
+      <param-value>GET,POST,HEAD,OPTIONS,PUT,DELETE</param-value>
+    </init-param>
+    <init-param>
+      <param-name>cors.allowed.headers</param-name>
+      <param-value>Content-Type,X-Requested-With,accept,authorization,
+        origin,Origin,Access-Control-Request-Method,Access-Control-Request-Headers
+      </param-value>
+    </init-param>
+    <init-param>
+      <param-name>cors.exposed.headers</param-name>
+      <param-value>Access-Control-Allow-Origin,Access-Control-Allow-Credentials</param-value>
+    </init-param>
+    <init-param>
+      <param-name>cors.support.credentials</param-name>
+      <param-value>true</param-value>
+    </init-param>
+    <init-param>
+      <param-name>cors.preflight.maxage</param-name>
+      <param-value>10</param-value>
+    </init-param>
+  </filter-template>
+
+  <Context path="/restconf">
+    <filter>
+      <filter-name>CorsFilter</filter-name>
+      <!-- init params can be added/overriden if template is used -->
+    </filter>
+    <!-- references to templates without <filter> declaration are not allowed -->
+    <filter-mapping>
+      <filter-name>CorsFilter</filter-name>
+      <url-pattern>/*</url-pattern>
+    </filter-mapping>
+  </Context>
+
+  <Context path="/apidoc">
+    <filter>
+      <filter-name>CorsFilter</filter-name>
+      <!-- init params can be added/overriden if template is used -->
+    </filter>
+    <!-- references to templates without <filter> declaration are not allowed -->
+    <filter-mapping>
+      <filter-name>CorsFilter</filter-name>
+      <url-pattern>/*</url-pattern>
+    </filter-mapping>
+  </Context>
 
-    <Context path="/restconf">
-        <filter>
-            <filter-name>CorsFilter</filter-name>
-            <!-- init params can be added/overriden if template is used -->
-        </filter>
-        <!-- references to templates without <filter> declaration are not allowed -->
-        <filter-mapping>
-            <filter-name>CorsFilter</filter-name>
-            <url-pattern>/*</url-pattern>
-        </filter-mapping>
-    </Context>
 
 </Host>
index 7b1df982471006c073b6b1b4b654149cc665bedc..38df344f858641d60d4913e0dc251efc6427d64d 100644 (file)
                         <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">binding:binding-data-broker</type>
                         <name>binding-data-broker</name>
                     </data-broker>
+                    <root-data-broker xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
+                        <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">binding:binding-async-data-broker</type>
+                        <name>binding-data-broker</name>
+                    </root-data-broker>
                 </module>
 
 
                     </schema-service>
                 </module>
 
+                <!-- DISTRIBUTED_DATA_STORE -->
+                <!-- Enable the following modules if you want to use the Distributed Data Store instead of the InMemoryDataStore -->
+                <!--
+                <module>
+                    <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:config:distributed-datastore-provider">prefix:distributed-operational-datastore-provider</type>
+                    <name>distributed-operational-store-module</name>
+                    <schema-service>
+                        <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:schema-service</type>
+                        <name>yang-schema-service</name>
+                    </schema-service>
+                </module>
+
+                <module>
+                    <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:config:distributed-datastore-provider">prefix:distributed-config-datastore-provider</type>
+                    <name>distributed-config-store-module</name>
+                    <schema-service>
+                        <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">dom:schema-service</type>
+                        <name>yang-schema-service</name>
+                    </schema-service>
+                </module>
+                -->
+
                 <module>
                     <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:inmemory-datastore-provider">prefix:inmemory-operational-datastore-provider</type>
                     <name>operational-store-service</name>
@@ -55,7 +81,6 @@
                         <name>yang-schema-service</name>
                     </schema-service>
                 </module>
-
                 <!--
                      Tree-based in-memory data store. This is the data store which is currently
                      recommended for single-node deployments.
                    <config-data-store>
                         <type xmlns:config-dom-store-spi="urn:opendaylight:params:xml:ns:yang:controller:md:sal:core:spi:config-dom-store">config-dom-store-spi:config-dom-datastore</type>
                         <name>config-store-service</name>
+                        <!-- DISTRIBUTED_DATA_STORE -->
+                        <!--
+                        <name>distributed-config-store-service</name>
+                        -->
                     </config-data-store>
 
                     <operational-data-store>
                         <type xmlns:operational-dom-store-spi="urn:opendaylight:params:xml:ns:yang:controller:md:sal:core:spi:operational-dom-store">operational-dom-store-spi:operational-dom-datastore</type>
                         <name>operational-store-service</name>
+                        <!-- DISTRIBUTED_DATA_STORE -->
+                        <!--
+                        <name>distributed-operational-store-service</name>
+                        -->
+
                     </operational-data-store>
                 </module>
                 <module>
                             <provider>/modules/module[type='schema-service-singleton'][name='yang-schema-service']</provider>
                         </instance>
                     </service>
+
+                <!-- DISTRIBUTED_DATA_STORE -->
+                <!-- Enable the following if you want to use the Distributed Data Store instead of the InMemory Data Store -->
+                <!-- Note that you MUST delete the InMemoryDataStore related services which provide config-dom-datastore and operational-dom-datastore -->
+                <!--
+                <service>
+                    <type xmlns:config-dom-store-spi="urn:opendaylight:params:xml:ns:yang:controller:md:sal:core:spi:config-dom-store">config-dom-store-spi:config-dom-datastore</type>
+                    <instance>
+                        <name>distributed-config-store-service</name>
+                        <provider>/modules/module[type='distributed-config-datastore-provider'][name='distributed-config-store-module']</provider>
+                    </instance>
+                </service>
+                <service>
+                    <type xmlns:operational-dom-store-spi="urn:opendaylight:params:xml:ns:yang:controller:md:sal:core:spi:operational-dom-store">operational-dom-store-spi:operational-dom-datastore</type>
+                    <instance>
+                        <name>distributed-operational-store-service</name>
+                        <provider>/modules/module[type='distributed-operational-datastore-provider'][name='distributed-operational-store-module']</provider>
+                    </instance>
+                </service>
+                -->
+
+                <!-- DISTRIBUTED_DATA_STORE -->
+                <!-- Delete the following two services (config-store-service and operational-store-service) if you want to use the distributed data store instead -->
                 <service>
                     <type xmlns:config-dom-store-spi="urn:opendaylight:params:xml:ns:yang:controller:md:sal:core:spi:config-dom-store">config-dom-store-spi:config-dom-datastore</type>
                     <instance>
diff --git a/opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/01-netconf.xml b/opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/01-netconf.xml
new file mode 100644 (file)
index 0000000..f81a332
--- /dev/null
@@ -0,0 +1,85 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- vi: set et smarttab sw=4 tabstop=4: -->
+<!--
+ 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
+-->
+<snapshot>
+  <configuration>
+    <data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
+      <modules xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
+
+        <!-- Netconf dispatcher to be used by all netconf-connectors -->
+        <module>
+          <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:config:netconf:client:dispatcher">prefix:netconf-client-dispatcher</type>
+          <name>global-netconf-dispatcher</name>
+          <boss-thread-group xmlns="urn:opendaylight:params:xml:ns:yang:controller:config:netconf:client:dispatcher">
+            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:netty">prefix:netty-threadgroup</type>
+            <name>global-boss-group</name>
+          </boss-thread-group>
+          <worker-thread-group xmlns="urn:opendaylight:params:xml:ns:yang:controller:config:netconf:client:dispatcher">
+            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:netty">prefix:netty-threadgroup</type>
+            <name>global-worker-group</name>
+          </worker-thread-group>
+          <timer xmlns="urn:opendaylight:params:xml:ns:yang:controller:config:netconf:client:dispatcher">
+            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:netty">prefix:netty-timer</type>
+            <name>global-timer</name>
+          </timer>
+        </module>
+
+        <!-- Thread factory to be used by all threadpools in netconf-connectors -->
+        <module>
+          <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl">prefix:threadfactory-naming</type>
+          <name>global-netconf-processing-executor-threadfactory</name>
+          <name-prefix xmlns="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl">remote-connector-processing-executor</name-prefix>
+        </module>
+        <!-- flexible threadpool for all netconf connectors, Max thread count is set to 4.  -->
+        <module>
+          <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl:flexible">prefix:threadpool-flexible</type>
+          <name>global-netconf-processing-executor</name>
+          <minThreadCount xmlns="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl:flexible">1</minThreadCount>
+          <max-thread-count xmlns="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl:flexible">4</max-thread-count>
+          <keepAliveMillis xmlns="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl:flexible">600000</keepAliveMillis>
+
+          <threadFactory xmlns="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl:flexible">
+            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:threadpool">prefix:threadfactory</type>
+            <name>global-netconf-processing-executor-threadfactory</name>
+          </threadFactory>
+        </module>
+      </modules>
+
+      <services xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
+        <service>
+          <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:config:netconf">prefix:netconf-client-dispatcher</type>
+          <instance>
+            <name>global-netconf-dispatcher</name>
+            <provider>/modules/module[type='netconf-client-dispatcher'][name='global-netconf-dispatcher']</provider>
+          </instance>
+        </service>
+        <service>
+          <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:threadpool">prefix:threadfactory</type>
+          <instance>
+            <name>global-netconf-processing-executor-threadfactory</name>
+            <provider>/modules/module[type='threadfactory-naming'][name='global-netconf-processing-executor-threadfactory']</provider>
+          </instance>
+        </service>
+        <service>
+          <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:threadpool">prefix:threadpool</type>
+          <instance>
+            <name>global-netconf-processing-executor</name>
+            <provider>/modules/module[type='threadpool-flexible'][name='global-netconf-processing-executor']</provider>
+          </instance>
+        </service>
+      </services>
+
+    </data>
+  </configuration>
+  <required-capabilities>
+      <capability>urn:opendaylight:params:xml:ns:yang:controller:config:netconf:client:dispatcher?module=odl-netconfig-client-cfg&amp;revision=2014-04-08</capability>
+      <capability>urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl?module=threadpool-impl&amp;revision=2013-04-05</capability>
+      <capability>urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl:flexible?module=threadpool-impl-flexible&amp;revision=2013-12-01</capability>
+  </required-capabilities>
+</snapshot>
diff --git a/opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/02-clustering.xml b/opendaylight/distribution/opendaylight/src/main/resources/configuration/initial/02-clustering.xml
deleted file mode 100644 (file)
index c5f99fd..0000000
+++ /dev/null
@@ -1,36 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: -->
-<!--
- 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
--->
-<snapshot>
-    <configuration>
-        <data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
-            <modules xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
-                <module>
-                   <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote:rpc">prefix:remote-zeromq-rpc-server</type>
-                   <name>remoter</name>
-                   <port xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote:rpc">5666</port>
-                   <dom-broker xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote:rpc">
-                       <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">prefix:dom-broker-osgi-registry</type>
-                       <name>dom-broker</name>
-                   </dom-broker>
-               </module>
-            </modules>
-            <services xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
-            </services>
-        </data>
-    </configuration>
-
-    <required-capabilities>
-       <capability>urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom?module=opendaylight-md-sal-dom&amp;revision=2013-10-28</capability>
-        <capability>urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl?module=opendaylight-sal-dom-broker-impl&amp;revision=2013-10-28</capability>
-        <capability>urn:opendaylight:params:xml:ns:yang:controller:md:sal:common?module=opendaylight-md-sal-common&amp;revision=2013-10-28</capability>
-        <capability>urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote:rpc?module=odl-sal-dom-rpc-remote-cfg&amp;revision=2013-10-28</capability>
-    </required-capabilities>
-</snapshot>
-
index 502bdebca26588cfc481793a0abd69731b6d708b..3958e185605e155f8b4b092e927ff5e8a679cbd1 100644 (file)
@@ -23,7 +23,7 @@
                     </rpc-registry>
 
                     <data-broker>
-                        <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">binding:binding-data-broker</type>
+                        <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>
                     
index b4b433dbca7c332787a8e14aa29e8b981dc308ed..7155eb88839b661372d83309a7dad27e8831c796 100644 (file)
   <configuration>
     <data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
       <modules xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
-
-        <!-- Netconf dispatcher to be used by all netconf-connectors --> 
-        <module>
-          <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:config:netconf:client:dispatcher">prefix:netconf-client-dispatcher</type>
-          <name>global-netconf-dispatcher</name>
-          <boss-thread-group xmlns="urn:opendaylight:params:xml:ns:yang:controller:config:netconf:client:dispatcher">
-            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:netty">prefix:netty-threadgroup</type>
-            <name>global-boss-group</name>
-          </boss-thread-group>
-          <worker-thread-group xmlns="urn:opendaylight:params:xml:ns:yang:controller:config:netconf:client:dispatcher">
-            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:netty">prefix:netty-threadgroup</type>
-            <name>global-worker-group</name>
-          </worker-thread-group>
-          <timer xmlns="urn:opendaylight:params:xml:ns:yang:controller:config:netconf:client:dispatcher">
-            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:netty">prefix:netty-timer</type>
-            <name>global-timer</name>
-          </timer>
-        </module>
-
-        <!-- Netconf dispatcher to be used by all netconf-connectors --> 
-        <module>
-          <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl">prefix:threadfactory-naming</type>
-          <name>global-netconf-processing-executor-threadfactory</name>
-          <name-prefix xmlns="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl">remote-connector-processing-executor</name-prefix>
-        </module>  
-        <module>
-          <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl:flexible">prefix:threadpool-flexible</type>
-          <name>global-netconf-processing-executor</name>
-          <minThreadCount xmlns="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl:flexible">1</minThreadCount>
-          <max-thread-count xmlns="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl:flexible">4</max-thread-count>
-          <keepAliveMillis xmlns="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl:flexible">600000</keepAliveMillis>
-          <threadFactory xmlns="urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl:flexible">
-            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:threadpool">prefix:threadfactory</type>
-            <name>global-netconf-processing-executor-threadfactory</name>
-          </threadFactory>
-        </module>  
-
         <!-- Loopback connection to netconf server in controller using netconf-connector -->
         <module>
           <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:connector:netconf">prefix:sal-netconf-connector</type>
           </processing-executor>
         </module>
       </modules>
-
-      <services xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
-        <service>
-          <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:config:netconf">prefix:netconf-client-dispatcher</type>
-          <instance>
-            <name>global-netconf-dispatcher</name>
-            <provider>/modules/module[type='netconf-client-dispatcher'][name='global-netconf-dispatcher']</provider>
-          </instance>
-        </service>
-        <service>
-          <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:threadpool">prefix:threadfactory</type>
-          <instance>
-            <name>global-netconf-processing-executor-threadfactory</name>
-            <provider>/modules/module[type='threadfactory-naming'][name='global-netconf-processing-executor-threadfactory']</provider>
-          </instance>
-        </service>
-        <service>
-          <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:threadpool">prefix:threadpool</type>
-          <instance>
-            <name>global-netconf-processing-executor</name>
-            <provider>/modules/module[type='threadpool-flexible'][name='global-netconf-processing-executor']</provider>
-          </instance>
-        </service>
-      </services>
-
     </data>
   </configuration>
   <required-capabilities>
       <capability>urn:opendaylight:params:xml:ns:yang:controller:md:sal:connector:netconf?module=odl-sal-netconf-connector-cfg&amp;revision=2013-10-28</capability>
-      <capability>urn:opendaylight:params:xml:ns:yang:controller:config:netconf:client:dispatcher?module=odl-netconfig-client-cfg&amp;revision=2014-04-08</capability>
-      <capability>urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl?module=threadpool-impl&amp;revision=2013-04-05</capability>
-      <capability>urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl:flexible?module=threadpool-impl-flexible&amp;revision=2013-12-01</capability>
   </required-capabilities>
 </snapshot>
index d1a5dcc416cc190dd3dabd80fdc5e8963a6af9a3..94a3702fdbc56d70073d593f6ed7b50a4a35d46a 100644 (file)
     <appender-ref ref="opendaylight.log"/>
   </logger>
 
+  <!-- BGPCEP plugin -->
+  <logger name="org.opendaylight.protocol" level="INFO"/>
+  <logger name="org.opendaylight.bgpcep" level="INFO"/>
+
   <!-- To debug MD-SAL schema loading issues, uncomment this -->
   <!--logger name="org.opendaylight.yangtools.yang.parser.impl.util.URLSchemaContextResolver" level="DEBUG"/>
   <logger name="org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl" level="TRACE"/-->
diff --git a/opendaylight/distribution/opendaylight/src/main/resources/functions.sh b/opendaylight/distribution/opendaylight/src/main/resources/functions.sh
new file mode 100644 (file)
index 0000000..21dd4c1
--- /dev/null
@@ -0,0 +1,18 @@
+#!/bin/bash
+
+# Function harvestHelp searches in run.sh part for line starting with "##<name command>".
+# Next lines starting with "#<text>" will be printed without first char # (=help content).
+# Help content has to end with "##" on new line.
+# Example:
+##foo
+#   Foo is world wide used synnonym for bar.
+##
+function harvestHelp() {
+    key="$1"
+    if [ -z "${key}" ]; then
+         key='HELP'
+    fi
+    echo
+    sed -rn "/^##${key}$/,/^##/ p" $0 | sed -r '1 d; $ d; s/^#/  /'
+    grep "##${key}" $0 > /dev/null
+}
index 72ccd02707ba7f5c76f064e5a16767a42f5fd37f..ce13e3396862a042a37aeb89dad5b3ca66d59094 100644 (file)
@@ -14,6 +14,7 @@ SET jvmMaxMemory=
 SET extraJVMOpts=
 SET consoleOpts=-console -consoleLog
 SET PID=
+SET JAVA_H=%JAVA_HOME%\bin\jps.exe
 
 :LOOP
 IF "%~1" NEQ "" (
@@ -61,7 +62,7 @@ IF "%~1" NEQ "" (
        GOTO :LOOP
     )
     IF "!CARG!"=="-status" (
-       for /F "TOKENS=1" %%G in ('%JAVA_HOME%\bin\jps.exe -lvV ^| find /I "opendaylight"') do (
+       for /F "TOKENS=1" %%G in ('""!JAVA_H!" -lvV ^| find /I "opendaylight""') do (
            set PID=%%G
        )
        if "!PID!" NEQ "" (
@@ -72,7 +73,7 @@ IF "%~1" NEQ "" (
        GOTO :EOF
     )
     IF "!CARG!"=="-stop" (
-       for /F "TOKENS=1" %%G in ('%JAVA_HOME%\bin\jps.exe -lvV ^| find /I "opendaylight"') do (
+       for /F "TOKENS=1" %%G in ('""!JAVA_H!" -lvV ^| find /I "opendaylight""') do (
            set PID=%%G
        )
        if "!PID!" NEQ "" (
@@ -89,18 +90,23 @@ IF "%~1" NEQ "" (
        GOTO :LOOP
     )
     IF "!CARG:~0,2!"=="-D" (
-       SET extraJVMOpts=%extraJVMOpts% !CARG!
+       SET extraJVMOpts=!extraJVMOpts! !CARG!
        SHIFT
        GOTO :LOOP
     )
     IF "!CARG:~0,2!"=="-X" (
-       SET extraJVMOpts=%extraJVMOpts% !CARG!
+       SET extraJVMOpts=!extraJVMOpts! !CARG!
        SHIFT
        GOTO :LOOP
     )
     IF "!CARG!"=="-help" (
-        ECHO "Usage: %0 [-jmx] [-jmxport <num>] [-debug] [-debugsuspend] [-debugport <num>] [-start] [-consoleport <num>]] [-stop] [-status] [-console] [-help] [<other args will automatically be used for the JVM>]"
-        ECHO Note: Enclose any JVM or System properties within double quotes.
+        SHIFT
+        SET CARG=%2
+        IF "!CARG!" NEQ "" (
+             CALL:!CARG!
+        ) ELSE (
+              CALL:helper
+         )
         GOTO :EOF
     )
 
@@ -110,28 +116,24 @@ IF "%~1" NEQ "" (
 
 IF "%debugEnabled%" NEQ "" (
     REM ECHO "DEBUG enabled"
-    SET extraJVMOpts=%extraJVMOpts% -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=%debugport%
+    SET extraJVMOpts=!extraJVMOpts! -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=%debugport%
 )
+
 IF "%debugSuspended%" NEQ "" (
     REM ECHO "DEBUG enabled suspended"
-    SET extraJVMOpts=%extraJVMOpts% -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=%debugport%
+    SET extraJVMOpts=!extraJVMOpts! -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=%debugport%
 )
 
 IF "%jvmMaxMemory%"=="" (
     SET jvmMaxMemory=-Xmx1G
-    ECHO *****************************************************************
-    ECHO JVM maximum memory was not defined. Setting maximum memory to 1G.
-    ECHO To define the maximum memory, specify the -Xmx setting on the
-    ECHO command line.
-    ECHO                    e.g. run.bat -Xmx1G
-    ECHO *****************************************************************"
+    ECHO Setting maximum memory to 1G.
 )
 
-SET extraJVMOpts=%extraJVMOpts%  %jvmMaxMemory%
+SET extraJVMOpts=!extraJVMOpts!  %jvmMaxMemory%
 
 IF "%jmxEnabled%" NEQ "" (
     REM ECHO "JMX enabled "
-    SET extraJVMOpts=%extraJVMOpts% -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=%jmxport% -Dcom.sun.management.jmxremote
+    SET extraJVMOpts=!extraJVMOpts! -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=%jmxport% -Dcom.sun.management.jmxremote
 )
 IF "%startEnabled%" NEQ "" (
     REM ECHO "START enabled "
@@ -139,7 +141,7 @@ IF "%startEnabled%" NEQ "" (
 )
 
 REM       Check if controller is already running
-for /F "TOKENS=1" %%G in ('%JAVA_HOME%\bin\jps.exe -lvV ^| find /I "opendaylight"') do (
+for /F "TOKENS=1" %%G in ('""!JAVA_H!" -lvV ^| find /I "opendaylight""') do (
     SET PID=%%G
 )
 if "!PID!" NEQ "" (
@@ -154,16 +156,125 @@ SET cp="%basedir%lib\org.eclipse.osgi-3.8.1.v20120830-144521.jar;%basedir%lib\or
 REM       Now set framework classpath
 SET fwcp="file:\%basedir%lib\org.eclipse.osgi-3.8.1.v20120830-144521.jar,file:\%basedir%lib\org.eclipse.virgo.kernel.equinox.extensions-3.6.0.RELEASE.jar,file:\%basedir%lib\org.eclipse.equinox.launcher-1.3.0.v20120522-1813.jar"
 
-SET RUN_CMD="%JAVA_HOME%\bin\java.exe" -Dopendaylight.controller %extraJVMOpts% -Djava.io.tmpdir="%basedir%work\tmp" -Djava.awt.headless=true -Dosgi.install.area=%basedir% -Dosgi.configuration.area="%basedir%configuration" -Dosgi.frameworkClassPath=%fwcp% -Dosgi.framework="file:\%basedir%lib\org.eclipse.osgi-3.8.1.v20120830-144521.jar" -classpath %cp% org.eclipse.equinox.launcher.Main %consoleOpts%
+SET RUN_CMD="%JAVA_HOME%\bin\java.exe" -Dopendaylight.controller !extraJVMOpts! -Djava.io.tmpdir="%basedir%work\tmp" -Djava.awt.headless=true -Dosgi.install.area=%basedir% -Dosgi.configuration.area="%basedir%configuration" -Dosgi.frameworkClassPath=%fwcp% -Dosgi.framework="file:\%basedir%lib\org.eclipse.osgi-3.8.1.v20120830-144521.jar" -classpath %cp% org.eclipse.equinox.launcher.Main %consoleOpts%
 
-ECHO %RUN_CMD%
+ECHO !RUN_CMD!
 
 if "%startEnabled%" NEQ "" (
-    START /B cmd /C CALL %RUN_CMD% > %basedir%\logs\controller.out 2>&1
+    START /B cmd /C CALL !RUN_CMD! > %basedir%\logs\controller.out 2>&1
     ECHO Running controller in the background.
+    EXIT /B 1
 ) else (
-    %RUN_CMD%
+    !RUN_CMD!
     EXIT /B %ERRORLEVEL%
 )
 
+:helper
+echo. For more information on a specific command, type -help command-name.
+echo.
+echo   jmx              ^[-jmx^]
+echo   jmxport          ^[-jmxport ^<num^>^] - DEFAULT is 1088
+echo   debug            ^[-debug^]
+echo   debugsuspend     ^[-debugsuspend^]
+echo   debugport        ^[-debugport ^<num^>^] - DEFAULT is 8000
+echo   start            ^[-start ^[^<console port^>^]^] - DEFAULT port is 2400
+echo   stop             ^[-stop^]
+echo   status           ^[-status^]
+echo   console          ^[-console^]
+echo   agentpath        ^[-agentpath:^<path to lib^>^]
+exit/B 1
+
+:debugsuspend
+ECHO.
+ECHO. debugsuspend     ^[-debugsuspend^]
+ECHO.
+ECHO. This command sets suspend on true in runjdwp in extra JVM options. If its true, VMStartEvent has a suspendPolicy of SUSPEND_ALL. If its false, VMStartEvent has a suspendPolicy of SUSPEND_NONE.
+ECHO.
+EXIT /B 1
+
+:debugport
+ECHO.
+ECHO. debugport        ^[-debugport ^<num^>^] - DEFAULT is 8000
+ECHO.
+ECHO. Set address for settings in runjdwp in extra JVM options.
+ECHO. The address is transport address for the connection.
+ECHO. The address has to be in the range ^[1024,65535^]. If the option was not call, port will be set to default value.
+ECHO.
+EXIT /B 1
+
+:jmxport
+ECHO.
+ECHO. jmxport          ^[-jmxport ^<num^>^] - DEFAULT is 1088
+ECHO.
+ECHO.    Set jmx port for com.sun.management.jmxremote.port in JMX support. Port has to be in the range ^[1024,65535^]. If this option was not call, port will be set to default value.
+ECHO.
+EXIT /B 1
+
+:debug
+ECHO.
+ECHO. debug            [-debug]
+ECHO.
+ECHO. Run ODL controller with -Xdebug and -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=^$^{debugport^}
+ECHO.
+ECHO.    -Xdebug enables debugging capabilities in the JVM which are used by the Java Virtual Machine Tools Interface (JVMTI). JVMTI is a low-level debugging interface used by debuggers and profiling tools.
+ECHO.
+ECHO.    -Xrunjdwp option loads the JPDA reference implementation of JDWP. This library resides in the target VM and uses JVMDI and JNI to interact with it. It uses a transport and the JDWP protocol to communicate with a separate debugger application.
+ECHO.
+ECHO. settings for -Xrunjdwp:
+ECHO.            transport -  name of the transport to use in connecting to debugger application
+ECHO.            server    -  if 'y', listen for a debugger application to attach; otherwise, attach to the debugger application at the specified address
+ECHO.                      -  if 'y' and no address is specified, choose a transport address at which to listen for a debugger application, and print the address to the standard output stream
+ECHO.            suspend   -  if 'y', VMStartEvent has a suspend Policy of SUSPEND_ALL
+ECHO.                      -  if 'n', VMStartEvent has a suspend policy of SUSPEND_NONE
+ECHO.            address   -  transport address for the connection
+ECHO.                      -  if server=n, attempt to attach to debugger application at this address
+ECHO.          -  if server=y, listen for a connection at this address
+ECHO.
+EXIT /B 1
+
+:jmx
+ECHO.
+ECHO. jmx              [-jmx]
+ECHO.
+ECHO. Add JMX support. With settings for extra JVM options: -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=^$^{jmxport^} -Dcom.sun.management.jmxremote
+ECHO. jmxport can by set with option -jmxport ^<num^>. Default num for the option is 1088.
+ECHO.
+EXIT /B 1
+
+:stop
+ECHO.
+ECHO. stop             ^[-stop^]
+ECHO.
+ECHO. If a controller is running, the command stop controller. Pid will be clean.
+ECHO.
+EXIT /B 1
+
+:status
+ECHO.
+ECHO. status           ^[-status^]
+ECHO.
+ECHO. Find out whether a controller is running and print it.
+ECHO.
+EXIT /B 1
+
+:start
+ECHO.
+ECHO. start            ^[-start ^[^<console port^>^]^]
+ECHO.
+ECHO.    If controller is not running, the command with argument^(for set port, where controller has start^) will start new controller on a port. The port has to be in the range ^[1024,65535^]. If this option was not call, port will be set to default value. Pid will be create.
+EXIT /B 1
+
+:console
+ECHO.
+ECHO. console          [-console]
+ECHO.     Default option.
+EXIT /B 1
+
+:agentpath
+ECHO.
+ECHO. agentpath        ^[-agentpath:^<path to lib^>^]
+ECHO.
+ECHO.    Agentpath option passes path to agent to jvm in order to load native agent library, e.g. yourkit profiler agent.
+EXIT /B 1
+
 
index 1e903d06503c286d7a0e8b41556c826eb5d6d105..13be2336b6db94304d944b78ba912530bee25c5f 100755 (executable)
@@ -1,5 +1,20 @@
 #!/bin/bash
 
+##HELP
+# For more information on a specific command, type -help command-name.
+#
+#   jmx              [-jmx]
+#   jmxport          [-jmxport <num>] - DEFAULT is 1088
+#   debug            [-debug]
+#   debugsuspend     [-debugsuspend]
+#   debugport        [-debugport <num>] - DEFAULT is 8000
+#   start            [-start [<console port>]] - DEFAULT port is 2400
+#   stop             [-stop]
+#   status           [-status]
+#   console          [-console]
+#   agentpath        [-agentpath:<path to lib>]
+##
+
 platform='unknown'
 unamestr=`uname`
 if [[ "$unamestr" == 'Linux' ]]; then
@@ -58,11 +73,6 @@ else
     datadir=${ODL_DATADIR}
 fi
 
-function usage {
-    echo "Usage: $0 [-jmx] [-jmxport <num>] [-debug] [-debugsuspend] [-debugport <num>] [-start [<console port>]] [-stop] [-status] [-console] [-help] [-agentpath:<path to lib>] [<other args will automatically be used for the JVM>]"
-    exit 1
-}
-
 if [ -z ${TMP} ]; then
     pidfile="/tmp/opendaylight.PID"
 else
@@ -82,13 +92,15 @@ stopdaemon=0
 statusdaemon=0
 consolestart=1
 dohelp=0
-jvmMaxMemory=""
+jvmMaxMemory="-Xmx1G"
 extraJVMOpts=""
 agentPath=""
 unknown_option=0
+helper=""
 while true ; do
     case "$1" in
         -debug) debug=1; shift ;;
+        -help) dohelp=1; shift;  helper=$1; break ;;
         -jmx) startjmx=1; shift ;;
         -debugsuspend) debugsuspend=1; shift ;;
         -debugport) shift; debugportread="$1"; if [[ "${debugportread}" =~ ^[0-9]+$ ]] ; then debugport=${debugportread}; shift; else echo "-debugport expects a number but was not found"; exit -1; fi;;
@@ -97,37 +109,39 @@ while true ; do
         -stop) stopdaemon=1; shift ;;
         -status) statusdaemon=1; shift ;;
         -console) shift ;;
-        -help) dohelp=1; shift;;
         -Xmx*) jvmMaxMemory="$1"; shift;;
         -D*) extraJVMOpts="${extraJVMOpts} $1"; shift;;
         -X*) extraJVMOpts="${extraJVMOpts} $1"; shift;;
         -agentpath:*) agentPath="$1"; shift;;
         "") break ;;
-        *) echo "Unknown option $1"; unknown_option=1; shift ;;
+        *) echo "Unknown option $1"; unknown_option=1; break ;;
     esac
 done
 
-# Unknown Options and help
+
+
 if [ "${unknown_option}" -eq 1 ]; then
-    usage
+    echo "Use -help for more information."
+    exit 1
 fi
 
-if [ "${dohelp}" -eq 1 ]; then
-    usage
-fi
 
-if [ "${jvmMaxMemory}" == "" ]; then
-    jvmMaxMemory="-Xmx1G"
-    echo "*****************************************************************"
-    echo "JVM maximum memory was not defined. Setting maximum memory to 1G."
-    echo "To define the maximum memory, specify the -Xmx setting on the"
-    echo "command line. "
-    echo "        e.g. ./run.sh -Xmx1G"
-    echo "*****************************************************************"
+if [ "${dohelp}" -eq 1 ]; then
+    . ${basedir}/functions.sh
+    harvestHelp ${helper}
+    echo -e '\nFor other information type -help.\n'
+    exit 1
 fi
 
 extraJVMOpts="${extraJVMOpts} ${jvmMaxMemory}"
 
+##debugport
+#debugport        [-debugport <num>] - DEFAULT is 8000
+#
+#    Set address for settings in runjdwp in extra JVM options.
+#    The address is transport address for the connection.
+#    The address has to be in the range [1024,65535]. If this option was not call, port will be set to default value.
+##
 # Validate debug port
 if [[ "${debugport}" -lt 1024 ]] || [[ "${debugport}" -gt 65535 ]]; then
     echo "Debug Port not in the range [1024,65535] ${debugport}"
@@ -140,19 +154,51 @@ if [[ "${daemonport}" -lt 1024 ]] || [[ "${daemonport}" -gt 65535 ]]; then
     exit -1
 fi
 
+##jmxport
+#jmxport          [-jmxport <num>] - DEFAULT is 1088
+#
+#    Set jmx port for com.sun.management.jmxremote.port in JMX support. Port has to be in the range [1024,65535]. If this option was not call, port will be set to default value.
+##
 # Validate jmx port
 if [[ "${jmxport}" -lt 1024 ]] || [[ "${jmxport}" -gt 65535 ]]; then
     echo "JMX Port not in the range [1024,65535] value is ${jmxport}"
     exit -1
 fi
+##debug
+#debug            [-debug]
+#
+#Run ODL controller with -Xdebug and -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=\${debugport}
+#-Xdebug enables debugging capabilities in the JVM which are used by the Java Virtual Machine Tools Interface (JVMTI). JVMTI is a low-level debugging interface used by debuggers and profiling tools.
+#-Xrunjdwp option loads the JPDA reference implementation of JDWP. This library resides in the target VM and uses JVMDI and JNI to interact with it. It uses a transport and the JDWP protocol to
+#communicate with a separate debugger application.
+#settings for -Xrunjdwp:
+#            transport -  name of the transport to use in connecting to debugger application
+#            server    -  if “y”, listen for a debugger application to attach; otherwise, attach to the debugger application at the specified address
+#                      -  if “y” and no address is specified, choose a transport address at which to listen for a debugger application, and print the address to the standard output stream
+#            suspend   -  if “y”, VMStartEvent has a suspend Policy of SUSPEND_ALL
+#                      -  if “n”, VMStartEvent has a suspend policy of SUSPEND_NONE
+#            address   -  transport address for the connection
+#                      -  if server=n, attempt to attach to debugger application at this address
+#          -  if server=y, listen for a connection at this address
+##
 
+##debugsuspend
+#debugsuspend     [-debugsuspend]
+#
+#This command sets suspend on true in runjdwp in extra JVM options. If its true, VMStartEvent has a suspendPolicy of SUSPEND_ALL. If its false, VMStartEvent has a suspendPolicy of SUSPEND_NONE.
+##
 # Debug options
 if [ "${debugsuspend}" -eq 1 ]; then
     extraJVMOpts="${extraJVMOpts} -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=${debugport}"
 elif [ "${debug}" -eq 1 ]; then
     extraJVMOpts="${extraJVMOpts} -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=${debugport}"
 fi
-
+##jmx
+#jmx              [-jmx]
+#
+#Add JMX support. With settings for extra JVM options: -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=\${jmxport} -Dcom.sun.management.jmxremote
+#jmxport can by set with command -jmxport <num>. Default num for the option is 1088.
+##
 # Add JMX support
 if [ "${startjmx}" -eq 1 ]; then
     extraJVMOpts="${extraJVMOpts} -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.port=${jmxport} -Dcom.sun.management.jmxremote"
@@ -182,6 +228,11 @@ FWCLASSPATH=${FWCLASSPATH},file:${basedir}/lib/org.eclipse.equinox.launcher-1.3.
 
 cd $basedir
 
+##stop
+#stop             [-stop]
+#
+#If a controller is running, the command stop controller. Pid will be clean.
+##
 if [ "${stopdaemon}" -eq 1 ]; then
     if [ -e "${pidfile}" ]; then
         daemonpid=`cat "${pidfile}"`
@@ -195,6 +246,11 @@ if [ "${stopdaemon}" -eq 1 ]; then
     fi
 fi
 
+##status
+#status           [-status]
+#
+#Find out whether a controller is running and print it.
+##
 if [ "${statusdaemon}" -eq 1 ]; then
     if [ -e "${pidfile}" ]; then
         daemonpid=`cat "${pidfile}"`
@@ -219,6 +275,22 @@ bdir=`echo "${basedir}" | sed 's/ /\\ /g'`
 confarea=`echo "${datadir}" | sed 's/ /\\ /g'`
 fwclasspath=`echo "${FWCLASSPATH}" | sed 's/ /\\ /g'`
 
+##start
+#start            [-start [<console port>]]
+#
+#    If controller is not running, the command with argument(for set port, where controller has start) will start new controller on a port. The port has to be in the range [1024,65535]. If this option was not call, port will be set to default value. Pid will be create.
+##
+##console
+#console          [-console]
+#
+#    Default option.
+##
+##agentpath
+#agentpath        [-agentpath:<path to lib>]
+#
+#   Agentpath option passes path to agent to jvm in order to load native agent library, e.g. yourkit profiler agent.
+##
+echo "JVM maximum memory was set to ${jvmMaxMemory}."
 if [ "${startdaemon}" -eq 1 ]; then
     if [ -e "${pidfile}" ]; then
         echo "Another instance of controller running, check with $0 -status"
index be3add104289951ef29a9564d03f7a197fcf73c7..ff68176f1fed36f3b8c606421cee8790a73ec582 100644 (file)
@@ -7,8 +7,6 @@
  */
 package org.opendaylight.controller.md.frm.compatibility;
 
-import java.util.Collections;
-
 import org.opendaylight.controller.forwardingrulesmanager.FlowConfig;
 import org.opendaylight.controller.forwardingrulesmanager.IForwardingRulesManager;
 import org.opendaylight.controller.md.sal.common.api.data.DataChangeListener;
@@ -17,7 +15,6 @@ import org.opendaylight.controller.md.sal.common.api.data.DataModification;
 import org.opendaylight.controller.sal.binding.api.data.DataProviderService;
 import org.opendaylight.controller.sal.binding.api.data.RuntimeDataProvider;
 import org.opendaylight.controller.sal.common.util.Arguments;
-import org.opendaylight.controller.sal.common.util.Rpcs;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.config.rev130819.Flows;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.config.rev130819.flows.FlowKey;
 import org.opendaylight.yangtools.concepts.Registration;
@@ -26,8 +23,8 @@ import org.opendaylight.yangtools.yang.binding.Identifier;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
-import org.opendaylight.yangtools.yang.common.RpcError;
 import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 
 import com.google.common.base.Objects;
 import com.google.common.base.Preconditions;
@@ -89,7 +86,7 @@ public class FRMRuntimeDataProvider implements RuntimeDataProvider, DataCommitHa
             this.manager.removeStaticFlow(flow.getName(), flow.getNode());
             this.manager.addStaticFlow(flow);
         }
-        return Rpcs.<Void> getRpcResult(true, null, Collections.<RpcError> emptySet());
+        return RpcResultBuilder.<Void> success().build();
     }
 
     public RpcResult<Void> rollback(final FlowCommitTransaction transaction) {
index ba68d523af7faf32efd1e17ee040558f7a4b1323..d71858e5c36750cb33b206b6b6977ffcf604ffc8 100644 (file)
@@ -83,6 +83,7 @@ public class ComponentActivator extends ComponentActivatorAbstractBase {
 
     @Override
     protected void init() {
+        // TODO: deprecated, should be removed soon
         NodeIDType.registerIDType(NodeMapping.MD_SAL_TYPE, String.class);
         NodeConnectorIDType.registerIDType(NodeMapping.MD_SAL_TYPE, String.class, NodeMapping.MD_SAL_TYPE);
     }
@@ -232,8 +233,8 @@ public class ComponentActivator extends ComponentActivatorAbstractBase {
 
     private Dictionary<String,Object> properties() {
         final Hashtable<String,Object> props = new Hashtable<String, Object>();
-        props.put(GlobalConstants.PROTOCOLPLUGINTYPE.toString(), NodeMapping.MD_SAL_TYPE);
-        props.put("protocolName", NodeMapping.MD_SAL_TYPE);
+        props.put(GlobalConstants.PROTOCOLPLUGINTYPE.toString(), NodeIDType.OPENFLOW);
+        props.put("protocolName", NodeIDType.OPENFLOW);
         return props;
     }
 }
index ba7377e8ff3dd1b8fd6c69df70e70435d39cb2a9..acb54ba51aeb3bb6b3f00f2930d7e2c212755bf3 100644 (file)
@@ -247,7 +247,8 @@ public class FlowProgrammerAdapter implements IPluginInFlowProgrammerService, Sa
 
         flowId = UUID.randomUUID();
         cache.put(flow, flowId);
-        return this.writeFlowAsync(MDFlowMapping.toMDFlow(flow, flowId.toString()), new NodeKey(new NodeId(node.getNodeIDString())));
+        return this.writeFlowAsync(MDFlowMapping.toMDFlow(flow, flowId.toString()), new NodeKey(
+                new NodeId(NodeMapping.OPENFLOW_ID_PREFIX + node.getID())));
     }
 
     private Future<RpcResult<TransactionStatus>> internalModifyFlowAsync(final Node node, final Flow oldFlow, final Flow newFlow, final long rid) {
@@ -261,7 +262,8 @@ public class FlowProgrammerAdapter implements IPluginInFlowProgrammerService, Sa
         }
 
         cache.put(newFlow, flowId);
-        return this.writeFlowAsync(MDFlowMapping.toMDFlow(newFlow, flowId.toString()), new NodeKey(new NodeId(node.getNodeIDString())));
+        return this.writeFlowAsync(MDFlowMapping.toMDFlow(newFlow, flowId.toString()), new NodeKey(
+                new NodeId(NodeMapping.OPENFLOW_ID_PREFIX + node.getID())));
     }
 
     private Future<RpcResult<TransactionStatus>> internalRemoveFlowAsync(final Node node, final Flow adflow, final long rid) {
@@ -275,7 +277,8 @@ public class FlowProgrammerAdapter implements IPluginInFlowProgrammerService, Sa
 
         final org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow flow = MDFlowMapping.toMDFlow(adflow, flowId.toString());
         final DataModificationTransaction modification = this.dataBrokerService.beginTransaction();
-        modification.removeConfigurationData(flowPath(flow, new NodeKey(new NodeId(node.getNodeIDString()))));
+        modification.removeConfigurationData(flowPath(flow, new NodeKey(
+                new NodeId(NodeMapping.OPENFLOW_ID_PREFIX + node.getID()))));
         return modification.commit();
     }
 
index 36045cabf4bfefc672d3edde8001a75deba46385..1b648dc98c36c0c6e05bfce6740b294dd730e8b8 100644 (file)
@@ -103,7 +103,8 @@ public class FromSalConversionsUtils {
     private static NodeConnectorId inPortMatch(Match sourceMatch) {
         MatchField inPort = sourceMatch.getField(MatchType.IN_PORT);
         if(inPort != null && inPort.getValue() != null && (inPort.getValue() instanceof NodeConnector)) {
-            return new NodeConnectorId(((NodeConnector) inPort.getValue()).getNodeConnectorIdAsString());
+            NodeConnector port = (NodeConnector)inPort.getValue();
+            return (NodeConnectorId)MDFlowMapping.toUri(port);
         }
         return null;
     }
@@ -203,9 +204,11 @@ public class FromSalConversionsUtils {
         MatchField vlan = sourceMatch.getField(MatchType.DL_VLAN);
         if (vlan != null && vlan.getValue() != null) {
             VlanIdBuilder vlanIDBuilder = new VlanIdBuilder();
+            short vid = (short)vlan.getValue();
+            boolean present = (vid != MatchType.DL_VLAN_NONE);
             vlanIDBuilder.setVlanId(new VlanId((NetUtils
-                    .getUnsignedShort((short) vlan.getValue()))));
-            vlanIDBuilder.setVlanIdPresent(true);
+                    .getUnsignedShort(vid))));
+            vlanIDBuilder.setVlanIdPresent(present);
             vlanMatchBuild.setVlanId(vlanIDBuilder.build());
         }
 
index 28301654258407536725408981e986c79e1082d1..e2c13867754d187f26f9f9a1dc4414a2b4114572 100644 (file)
@@ -7,9 +7,12 @@
  */
 package org.opendaylight.controller.sal.compatibility;
 
+import com.google.common.collect.Iterables;
+
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashSet;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -26,6 +29,7 @@ import org.opendaylight.controller.sal.core.Edge;
 import org.opendaylight.controller.sal.core.Node;
 import org.opendaylight.controller.sal.core.NodeConnector;
 import org.opendaylight.controller.sal.core.NodeTable;
+import org.opendaylight.controller.sal.core.NodeTable.NodeTableIDType;
 import org.opendaylight.controller.sal.core.Property;
 import org.opendaylight.controller.sal.core.UpdateType;
 import org.opendaylight.controller.sal.inventory.IPluginInInventoryService;
@@ -489,7 +493,7 @@ public class InventoryAndReadAdapter implements IPluginInReadService, IPluginInI
                 }
 
                 try {
-                    final Node adNode = new Node(NodeMapping.MD_SAL_TYPE, NodeMapping.toADNodeId(node.getId()));
+                    final Node adNode = NodeMapping.toADNode(node.getId());
                     props.put(adNode, perNodePropMap);
                 } catch (ConstructionException e) {
                     LOG.warn("Failed to construct node for {}, skipping it", node, e);
@@ -572,7 +576,7 @@ public class InventoryAndReadAdapter implements IPluginInReadService, IPluginInI
         it.setLookupCount(tableStats.getPacketsLookedUp().getValue().longValue());
         it.setMatchedCount(tableStats.getPacketsMatched().getValue().longValue());
         it.setName(tableId.toString());
-        it.setNodeTable(new NodeTable(NodeMapping.MD_SAL_TYPE, tableId, node));
+        it.setNodeTable(new NodeTable(NodeTableIDType.OPENFLOW, tableId.byteValue(), node));
         return it;
     }
 
@@ -732,26 +736,45 @@ public class InventoryAndReadAdapter implements IPluginInReadService, IPluginInI
     }
 
     private boolean isKnownNodeConnector(final InstanceIdentifier<? extends Object> nodeConnectorIdentifier) {
-        final List<PathArgument> path = nodeConnectorIdentifier.getPath();
-        if (path.size() >= 3) {
-            final PathArgument nodePath = path.get(1);
-            final PathArgument nodeConnectorPath = path.get(2);
-            final List<PathArgument> nodeConnectors = nodeToNodeConnectorsMap.get(nodePath);
-            if (nodeConnectors != null) {
-                return nodeConnectors.contains(nodeConnectorPath);
-            }
+        final Iterator<PathArgument> it = nodeConnectorIdentifier.getPathArguments().iterator();
+
+        if (!it.hasNext()) {
+            return false;
         }
-        return false;
+        it.next();
+
+        if (!it.hasNext()) {
+            return false;
+        }
+        final PathArgument nodePath = it.next();
+
+        if (!it.hasNext()) {
+            return false;
+        }
+        final PathArgument nodeConnectorPath = it.next();
+
+        final List<PathArgument> nodeConnectors = nodeToNodeConnectorsMap.get(nodePath);
+        return nodeConnectors == null ? false :
+            nodeConnectors.contains(nodeConnectorPath);
     }
 
     private boolean recordNodeConnector(final InstanceIdentifier<? extends Object> nodeConnectorIdentifier) {
-        final List<PathArgument> path = nodeConnectorIdentifier.getPath();
-        if (path.size() < 3) {
+        final Iterator<PathArgument> it = nodeConnectorIdentifier.getPathArguments().iterator();
+
+        if (!it.hasNext()) {
             return false;
         }
+        it.next();
 
-        final PathArgument nodePath = path.get(1);
-        final PathArgument nodeConnectorPath = path.get(2);
+        if (!it.hasNext()) {
+            return false;
+        }
+        final PathArgument nodePath = it.next();
+
+        if (!it.hasNext()) {
+            return false;
+        }
+        final PathArgument nodeConnectorPath = it.next();
 
         synchronized (this) {
             List<PathArgument> nodeConnectors = this.nodeToNodeConnectorsMap.get(nodePath);
@@ -765,6 +788,6 @@ public class InventoryAndReadAdapter implements IPluginInReadService, IPluginInI
     }
 
     private List<PathArgument> removeNodeConnectors(final InstanceIdentifier<? extends Object> nodeIdentifier) {
-        return this.nodeToNodeConnectorsMap.remove(nodeIdentifier.getPath().get(1));
+        return this.nodeToNodeConnectorsMap.remove(Iterables.get(nodeIdentifier.getPathArguments(), 1));
     }
 }
index 67af3e428f8ff22caca6db1b9e60a892673314eb..9b5d0e887541da50e9a802811b84e046f3573b7d 100644 (file)
@@ -357,7 +357,7 @@ public final class MDFlowMapping {
     }
 
     public static Uri toUri(final NodeConnector connector) {
-        return new NodeConnectorId(((String) connector.getID()));
+        return new NodeConnectorId(NodeMapping.OPENFLOW_ID_PREFIX + connector.getNode().getID() + ":" + (connector.getID()));
     }
 
     public static MacAddress toMacAddress(final byte[] bytes) {
index f5701bfaf23419c9c2beaed1bde59f2037095c3c..02964c6d5531553d23abaa0cce39dfae1db30881 100644 (file)
@@ -19,8 +19,10 @@ import org.opendaylight.controller.sal.core.Buffers;
 import org.opendaylight.controller.sal.core.Capabilities;
 import org.opendaylight.controller.sal.core.Config;
 import org.opendaylight.controller.sal.core.ConstructionException;
+import org.opendaylight.controller.sal.core.Description;
 import org.opendaylight.controller.sal.core.MacAddress;
 import org.opendaylight.controller.sal.core.Name;
+import org.opendaylight.controller.sal.core.Node.NodeIDType;
 import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType;
 import org.opendaylight.controller.sal.core.PeerBandwidth;
 import org.opendaylight.controller.sal.core.Property;
@@ -44,6 +46,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.fl
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortConfig;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortFeatures;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.flow.capable.port.State;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.OutputPortValues;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorUpdated;
@@ -56,12 +59,22 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.No
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Objects;
 import com.google.common.base.Preconditions;
 
 public final class NodeMapping {
-    public final static String MD_SAL_TYPE = "MD_SAL";
+
+    private static final Logger LOG = LoggerFactory
+            .getLogger(NodeMapping.class);
+
+    /** openflow id prefix */
+    public static final String OPENFLOW_ID_PREFIX = "openflow:";
+
+    public final static String MD_SAL_TYPE = "MD_SAL_DEPRECATED";
 
     private final static Class<Node> NODE_CLASS = Node.class;
 
@@ -77,8 +90,20 @@ public final class NodeMapping {
     }
 
     public static org.opendaylight.controller.sal.core.Node toADNode(final NodeId id) throws ConstructionException {
-        String aDNodeId = NodeMapping.toADNodeId(id);
-        return new org.opendaylight.controller.sal.core.Node(NodeMapping.MD_SAL_TYPE, aDNodeId);
+        Long aDNodeId = openflowFullNodeIdToLong(NodeMapping.toADNodeId(id));
+        return new org.opendaylight.controller.sal.core.Node(NodeIDType.OPENFLOW, aDNodeId);
+    }
+
+    /**
+     * @param adNodeId
+     * @return nodeId as long
+     */
+    @VisibleForTesting
+    public static Long openflowFullNodeIdToLong(String adNodeId) {
+        if (adNodeId == null) {
+            return null;
+        }
+        return new BigInteger(adNodeId.replaceFirst("^.*:", "")).longValue();
     }
 
     public static NodeId toNodeId(final InstanceIdentifier<?> id) {
@@ -87,7 +112,14 @@ public final class NodeMapping {
         return key.getId();
     }
 
+    /**
+     * @param nodeId containing "&lt;NodeTypeString&gt;:&lt;plainIntegerId&gt;"
+     * @return adNodeId form
+     */
     public static String toADNodeId(final NodeId nodeId) {
+        if (nodeId == null) {
+            return null;
+        }
         return nodeId.getValue();
     }
 
@@ -104,6 +136,28 @@ public final class NodeMapping {
         return new org.opendaylight.controller.sal.core.NodeConnector(nodeConnectorType, aDNodeConnectorId, aDNode);
     }
 
+    /**
+     * @param ncid nodeConnector identifier, e.g.: OF:21 or CTRL
+     * @param node
+     * @return nodeConnector attached to given node
+     * @throws ConstructionException
+     */
+    public static org.opendaylight.controller.sal.core.NodeConnector toADNodeConnector(
+            final NodeConnectorId ncid, final org.opendaylight.controller.sal.core.Node aDNode) throws ConstructionException {
+        NodeId nid = NodeMapping.toNodeId(aDNode);
+        String nodeConnectorType = NodeMapping.toNodeConnectorType(ncid, nid);
+        Object aDNodeConnectorId = NodeMapping.toADNodeConnectorId(ncid, nid);
+        return new org.opendaylight.controller.sal.core.NodeConnector(nodeConnectorType, aDNodeConnectorId, aDNode);
+    }
+
+    /**
+     * @param aDNode
+     * @return
+     */
+    private static NodeId toNodeId(org.opendaylight.controller.sal.core.Node aDNode) {
+        return new NodeId(aDNode.getType() + ":" +String.valueOf(aDNode.getID()));
+    }
+
     public static String toNodeConnectorType(final NodeConnectorId ncId, final NodeId nodeId) {
         if (ncId.equals(toLocalNodeConnectorId(nodeId))) {
             return NodeConnectorIDType.SWSTACK;
@@ -112,7 +166,7 @@ public final class NodeMapping {
         } else if (ncId.equals(toControllerNodeConnectorId(nodeId))) {
             return NodeConnectorIDType.CONTROLLER;
         }
-        return MD_SAL_TYPE;
+        return NodeConnectorIDType.OPENFLOW;
     }
 
     public static Object toADNodeConnectorId(final NodeConnectorId nodeConnectorId, final NodeId nodeId) {
@@ -121,7 +175,18 @@ public final class NodeMapping {
                 nodeConnectorId.equals(toControllerNodeConnectorId(nodeId))) {
             return org.opendaylight.controller.sal.core.NodeConnector.SPECIALNODECONNECTORID;
         }
-        return nodeConnectorId.getValue();
+
+        String nodeConnectorIdStripped = nodeConnectorId.getValue().replaceFirst("^.*:", "");
+        if (nodeConnectorIdStripped.matches("[0-9]+")) {
+            Short nodeConnectorIdVal = null;
+            try {
+                nodeConnectorIdVal = Short.valueOf(nodeConnectorIdStripped);
+            } catch (NumberFormatException e) {
+                LOG.warn("nodeConnectorId not supported (short): {}", nodeConnectorIdStripped, e);
+            }
+            return nodeConnectorIdVal;
+        }
+        return nodeConnectorIdStripped;
     }
 
     public static NodeId toAdNodeId(final NodeConnectorId nodeConnectorId) {
@@ -133,21 +198,21 @@ public final class NodeMapping {
     }
 
     public static NodeConnectorId toControllerNodeConnectorId(final NodeId node) {
-        return new NodeConnectorId(node.getValue() + ":" + 4294967293L);
+        return new NodeConnectorId(node.getValue() + ":" + OutputPortValues.CONTROLLER.toString());
     }
 
     public static NodeConnectorId toLocalNodeConnectorId(final NodeId node) {
-        return new NodeConnectorId(node.getValue() + ":" + 4294967294L);
+        return new NodeConnectorId(node.getValue() + ":" + OutputPortValues.LOCAL.toString());
     }
 
     public static NodeConnectorId toNormalNodeConnectorId(final NodeId node) {
-        return new NodeConnectorId(node.getValue() + ":" + 4294967290L);
+        return new NodeConnectorId(node.getValue() + ":" + OutputPortValues.NORMAL.toString());
     }
 
     public static NodeRef toNodeRef(final org.opendaylight.controller.sal.core.Node node) {
-        Preconditions.checkArgument(MD_SAL_TYPE.equals(node.getType()));
-        final String nodeId = Arguments.<String>checkInstanceOf(node.getID(), String.class);
-        final NodeKey nodeKey = new NodeKey(new NodeId(nodeId));
+        Preconditions.checkArgument(NodeIDType.OPENFLOW.equals(node.getType()));
+        final Long nodeId = Arguments.<Long>checkInstanceOf(node.getID(), Long.class);
+        final NodeKey nodeKey = new NodeKey(new NodeId(OPENFLOW_ID_PREFIX+nodeId));
         final InstanceIdentifier<Node> nodePath = InstanceIdentifier.builder(Nodes.class).child(NODE_CLASS, nodeKey).toInstance();
         return new NodeRef(nodePath);
     }
@@ -170,7 +235,8 @@ public final class NodeMapping {
                 nodeConnectorId = toControllerNodeConnectorId(nodeId);
             }
         } else {
-            nodeConnectorId = new NodeConnectorId(Arguments.<String>checkInstanceOf(nodeConnector.getID(), String.class));
+            nodeConnectorId = new NodeConnectorId(OPENFLOW_ID_PREFIX
+                    + Arguments.<Short>checkInstanceOf(nodeConnector.getID(), Short.class));
         }
         final NodeConnectorKey connectorKey = new NodeConnectorKey(nodeConnectorId);
         final InstanceIdentifier<NodeConnector> path = nodePath.child(NODECONNECTOR_CLASS, connectorKey);
@@ -184,11 +250,27 @@ public final class NodeMapping {
     public static HashSet<Property> toADNodeConnectorProperties(final NodeConnectorUpdated nc) {
         final FlowCapableNodeConnectorUpdated fcncu = nc.<FlowCapableNodeConnectorUpdated>getAugmentation(FlowCapableNodeConnectorUpdated.class);
         if (!Objects.equal(fcncu, null)) {
-            return NodeMapping.toADNodeConnectorProperties(fcncu);
+            HashSet<Property> adNodeConnectorProperties = NodeMapping.toADNodeConnectorProperties(fcncu);
+            return adNodeConnectorProperties;
         }
         return new HashSet<Property>();
     }
 
+    /**
+     * @param id
+     * @return node description in AD form, e.g.: OF|00:00:00:...:01
+     */
+    private static Description toADDescription(NodeRef nodeRef) {
+        Description desc;
+        try {
+            desc = new Description(toADNode(nodeRef).toString());
+        } catch (ConstructionException e) {
+            desc = new Description("none");
+            LOG.warn("node description extraction failed: {}", nodeRef);
+        }
+        return desc;
+    }
+
     public static HashSet<Property> toADNodeConnectorProperties(final NodeConnector nc) {
         final FlowCapableNodeConnector fcnc = nc.<FlowCapableNodeConnector>getAugmentation(FlowCapableNodeConnector.class);
         if (!Objects.equal(fcnc, null)) {
@@ -303,7 +385,9 @@ public final class NodeMapping {
     public static HashSet<Property> toADNodeProperties(final NodeUpdated nu) {
         final FlowCapableNodeUpdated fcnu = nu.getAugmentation(FlowCapableNodeUpdated.class);
         if (fcnu != null) {
-            return toADNodeProperties(fcnu, nu.getId());
+            HashSet<Property> adNodeProperties = toADNodeProperties(fcnu, nu.getId());
+            adNodeProperties.add(toADDescription(nu.getNodeRef()));
+            return adNodeProperties;
         }
         return new HashSet<org.opendaylight.controller.sal.core.Property>();
     }
@@ -342,7 +426,7 @@ public final class NodeMapping {
     }
 
     public static MacAddress toADMacAddress(final NodeId id) {
-        final String nodeId = id.getValue().replaceAll("openflow:", "");
+        final String nodeId = id.getValue().replaceAll(OPENFLOW_ID_PREFIX, "");
         BigInteger nodeIdRaw = new BigInteger(nodeId);
         long lNodeId = nodeIdRaw.longValue();
         byte[] bytesFromDpid = ToSalConversionsUtils.bytesFromDpid(lNodeId);
index 97a25bf71cd9789df1ca0a31f006dc7b99a37e19..58cfb20650930f82f5768fa9f96bbcd1e287ad14 100644 (file)
@@ -208,7 +208,8 @@ public class ToSalConversionsUtils {
                 Uri nodeConnector = ((OutputActionCase) sourceAction).getOutputAction().getOutputNodeConnector();
                 if (nodeConnector != null) {
                     //for (Uri uri : nodeConnectors) {
-                        targetAction.add(new Output(fromNodeConnectorRef(nodeConnector, node)));
+                    Uri fullNodeConnector = new Uri(node.getType()+":"+node.getID()+":"+nodeConnector.getValue());
+                        targetAction.add(new Output(fromNodeConnectorRef(fullNodeConnector, node)));
                     //}
                 }
             } else if (sourceAction instanceof PopMplsActionCase) {
@@ -376,12 +377,19 @@ public class ToSalConversionsUtils {
         return null;
     }
 
-    private static NodeConnector fromNodeConnectorRef(Uri uri, Node node) {
+    /**
+     * @param openflow nodeConnector uri
+     * @param node
+     * @return assembled nodeConnector
+     */
+    public static NodeConnector fromNodeConnectorRef(Uri uri, Node node) {
         NodeConnector nodeConnector = null;
         try {
-            nodeConnector = new NodeConnector(NodeMapping.MD_SAL_TYPE,node.getNodeIDString()+":"+uri.getValue(),node);
+            NodeConnectorId nodeConnectorId = new NodeConnectorId(uri.getValue());
+            nodeConnector = NodeMapping.toADNodeConnector(nodeConnectorId, node);
         } catch (ConstructionException e) {
-            e.printStackTrace();
+            LOG.warn("nodeConnector creation failed at node: {} with nodeConnectorUri: {}",
+                    node, uri.getValue());
         }
         return nodeConnector;
     }
@@ -422,13 +430,17 @@ public class ToSalConversionsUtils {
         if (vlanMatch != null) {
             VlanId vlanId = vlanMatch.getVlanId();
             if (vlanId != null) {
-                org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId vlanIdInner = vlanId
-                        .getVlanId();
-                if (vlanIdInner != null) {
-                    Integer vlanValue = vlanIdInner.getValue();
-                    if (vlanValue != null) {
-                        target.setField(DL_VLAN, vlanValue.shortValue());
+                if (Boolean.TRUE.equals(vlanId.isVlanIdPresent())) {
+                    org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId vlanIdInner = vlanId
+                            .getVlanId();
+                    if (vlanIdInner != null) {
+                        Integer vlanValue = vlanIdInner.getValue();
+                        if (vlanValue != null) {
+                            target.setField(DL_VLAN, vlanValue.shortValue());
+                        }
                     }
+                } else {
+                    target.setField(DL_VLAN, MatchType.DL_VLAN_NONE);
                 }
             }
             VlanPcp vlanPcp = vlanMatch.getVlanPcp();
index 01d75acfe6332b3e6574683ad49736efdf58655f..56c7afb253a5224547f848b40b1b125bd376b553 100644 (file)
@@ -10,7 +10,6 @@ package org.opendaylight.controller.sal.compatibility.adsal;
 import java.math.BigInteger;
 
 import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
-import org.opendaylight.controller.sal.common.util.Rpcs;
 import org.opendaylight.controller.sal.compatibility.InventoryMapping;
 import org.opendaylight.controller.sal.compatibility.ToSalConversionsUtils;
 import org.opendaylight.controller.sal.flowprogrammer.Flow;
@@ -32,6 +31,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev131103.
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -70,7 +70,8 @@ public class FlowServiceAdapter implements SalFlowService, IFlowProgrammerListen
         AddFlowOutputBuilder builder = new AddFlowOutputBuilder();
         builder.setTransactionId(new TransactionId(BigInteger.valueOf(status.getRequestId())));
         AddFlowOutput rpcResultType = builder.build();
-        return Futures.immediateFuture(Rpcs.getRpcResult(status.isSuccess(), rpcResultType, null));
+        return Futures.immediateFuture(RpcResultBuilder.<AddFlowOutput>status(status.isSuccess())
+                .withResult(rpcResultType).build());
     }
 
     @Override
@@ -84,7 +85,8 @@ public class FlowServiceAdapter implements SalFlowService, IFlowProgrammerListen
         RemoveFlowOutputBuilder builder = new RemoveFlowOutputBuilder();
         builder.setTransactionId(new TransactionId(BigInteger.valueOf(status.getRequestId())));
         RemoveFlowOutput rpcResultType = builder.build();
-        return Futures.immediateFuture(Rpcs.getRpcResult(status.isSuccess(), rpcResultType, null));
+        return Futures.immediateFuture(RpcResultBuilder.<RemoveFlowOutput>status(status.isSuccess())
+                                                         .withResult(rpcResultType).build());
 
     }
 
index c5cbecabedae35c96eb1fd0cad2ae5059253d074..e63cb54b8685174fafc7367bbe76bc130104a107 100644 (file)
@@ -13,7 +13,6 @@ import java.util.List;
 import java.util.concurrent.Future;
 
 import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
-import org.opendaylight.controller.sal.common.util.Rpcs;
 import org.opendaylight.controller.sal.compatibility.FromSalConversionsUtils;
 import org.opendaylight.controller.sal.compatibility.InventoryMapping;
 import org.opendaylight.controller.sal.compatibility.NodeMapping;
@@ -60,6 +59,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.n
 import org.opendaylight.yang.gen.v1.urn.opendaylight.port.statistics.rev131214.node.connector.statistics.and.port.number.map.NodeConnectorStatisticsAndPortNumberMapBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.table.types.rev131026.TableId;
 import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -107,7 +107,8 @@ public class FlowStatisticsAdapter implements OpendaylightFlowStatisticsService,
             LOG.error(e.getMessage());
         }
 
-        return Futures.immediateFuture(Rpcs.getRpcResult(rpcResultBool, rpcResultType, null));
+        return Futures.immediateFuture(RpcResultBuilder.<GetAllFlowStatisticsFromFlowTableOutput>
+                                                status(rpcResultBool).withResult(rpcResultType).build());
     }
 
     /**
@@ -133,7 +134,8 @@ public class FlowStatisticsAdapter implements OpendaylightFlowStatisticsService,
             LOG.error(e.getMessage());
         }
 
-        return Futures.immediateFuture(Rpcs.getRpcResult(rpcResultBool, rpcResultType, null));
+        return Futures.immediateFuture(RpcResultBuilder.<GetAllFlowsStatisticsFromAllFlowTablesOutput>
+                                               status(rpcResultBool).withResult(rpcResultType).build());
     }
 
     @Override
@@ -154,7 +156,8 @@ public class FlowStatisticsAdapter implements OpendaylightFlowStatisticsService,
             LOG.error(e.getMessage());
         }
 
-        return Futures.immediateFuture(Rpcs.getRpcResult(rpcResultBool, rpcResultType, null));
+        return Futures.immediateFuture(RpcResultBuilder.<GetFlowStatisticsFromFlowTableOutput>
+                                              status(rpcResultBool).withResult(rpcResultType).build());
     }
 
     @Override
index 476a71a4acd0602a7b36ca41b664fcb00b3d5135..6bc669f60b17a378369ae837081c43cab38be244 100644 (file)
@@ -18,7 +18,9 @@ import org.opendaylight.controller.sal.compatibility.NodeMapping;
 import org.opendaylight.controller.sal.core.ConstructionException;
 import org.opendaylight.controller.sal.core.Edge;
 import org.opendaylight.controller.sal.core.Node;
+import org.opendaylight.controller.sal.core.Node.NodeIDType;
 import org.opendaylight.controller.sal.core.NodeConnector;
+import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType;
 import org.opendaylight.controller.sal.core.Property;
 import org.opendaylight.controller.sal.core.UpdateType;
 import org.opendaylight.controller.sal.topology.TopoEdgeUpdate;
@@ -93,20 +95,20 @@ public final class TopologyMapping {
     }
 
     public static String toADNodeId(final NodeId nodeId) {
-        return nodeId.getValue();
+        return nodeId.getValue().replaceFirst("^.*:", "");
     }
 
     public static NodeConnector toADNodeConnector(final TpId source, final NodeId nodeId) throws ConstructionException {
         checkNotNull(source);
-        return new NodeConnector(NodeMapping.MD_SAL_TYPE, toADNodeConnectorId(source), toADNode(nodeId));
+        return new NodeConnector(NodeConnectorIDType.OPENFLOW, Short.valueOf(toADNodeConnectorId(source)), toADNode(nodeId));
     }
 
     public static String toADNodeConnectorId(final TpId nodeConnectorId) {
-        return nodeConnectorId.getValue();
+        return nodeConnectorId.getValue().replaceFirst("^.*:", "");
     }
 
     public static Node toADNode(final NodeId nodeId) throws ConstructionException {
         checkNotNull(nodeId);
-        return new Node(NodeMapping.MD_SAL_TYPE, toADNodeId(nodeId));
+        return new Node(NodeIDType.OPENFLOW, Long.valueOf(toADNodeId(nodeId)));
     }
 }
diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/MDFlowMappingTest.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/test/MDFlowMappingTest.java
new file mode 100644 (file)
index 0000000..4e5f318
--- /dev/null
@@ -0,0 +1,39 @@
+/**
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.sal.compatibility.test;
+
+import junit.framework.Assert;
+
+import org.junit.Test;
+import org.opendaylight.controller.sal.compatibility.MDFlowMapping;
+import org.opendaylight.controller.sal.core.ConstructionException;
+import org.opendaylight.controller.sal.core.Node;
+import org.opendaylight.controller.sal.core.Node.NodeIDType;
+import org.opendaylight.controller.sal.core.NodeConnector;
+import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Uri;
+
+/**
+ * test for {@link MDFlowMapping}
+ */
+public class MDFlowMappingTest {
+
+    /**
+     * Test method for {@link org.opendaylight.controller.sal.compatibility.MDFlowMapping#toUri(org.opendaylight.controller.sal.core.NodeConnector)}.
+     * @throws ConstructionException
+     */
+    @Test
+    public void testToUri() throws ConstructionException {
+        Node node = new Node(NodeIDType.OPENFLOW, 41L);
+        NodeConnector connector = new NodeConnector(NodeConnectorIDType.OPENFLOW, (short) 42, node);
+        Uri observed = MDFlowMapping.toUri(connector );
+
+        Assert.assertEquals("openflow:41:42", observed.getValue());
+    }
+
+}
index b418e6dc25879050d7e9525e671cf080c0444401..cef7ae7a427672b8276411b2e1ace77f66dc04fd 100644 (file)
@@ -10,9 +10,18 @@ package org.opendaylight.controller.sal.compatibility.test;
 import org.junit.Assert;
 import org.junit.Test;
 import org.opendaylight.controller.sal.compatibility.NodeMapping;
+import org.opendaylight.controller.sal.core.ConstructionException;
 import org.opendaylight.controller.sal.core.MacAddress;
+import org.opendaylight.controller.sal.core.Node.NodeIDType;
+import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.OutputPortValues;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 
 /**
  * test of {@link NodeMapping} utility class
@@ -67,8 +76,130 @@ public class NodeMappingTest {
         observed = NodeMapping.toAdNodeId(null);
         Assert.assertNull(observed);
 
-        observed = NodeMapping.toAdNodeId(new NodeConnectorId("MD_SAL|openflow:5:2"));
-        Assert.assertEquals("MD_SAL|openflow:5", observed.getValue());
+        observed = NodeMapping.toAdNodeId(new NodeConnectorId("openflow:5:2"));
+        Assert.assertEquals("openflow:5", observed.getValue());
     }
 
+    /**
+     * Test method for
+     * {@link org.opendaylight.controller.sal.compatibility.NodeMapping#toADNode(NodeId)}
+     * .
+     */
+    @Test
+    public void testToAdNode1() {
+        org.opendaylight.controller.sal.core.Node observed;
+        try {
+            observed = NodeMapping.toADNode((NodeId) null);
+        } catch (NullPointerException | ConstructionException e) {
+            //expected
+        }
+
+        NodeId nodeId = new NodeId("openflow:1");
+        try {
+            observed = NodeMapping.toADNode(nodeId);
+            Assert.assertEquals("OF|00:00:00:00:00:00:00:01", observed.toString());
+        } catch (ConstructionException e) {
+            Assert.fail("should succeed to construct Node: "+e.getMessage());
+        }
+    }
+
+    /**
+     * Test method for
+     * {@link org.opendaylight.controller.sal.compatibility.NodeMapping#toNodeConnectorType(NodeConnectorId, NodeId)}
+     * .
+     */
+    @Test
+    public void testToNodeConnectorType() {
+        NodeConnectorId ncId;
+        NodeId nodeId = buildNodeId("1");
+
+        ncId = buildNodeConnectorId("1", "42");
+        Assert.assertEquals(NodeConnectorIDType.OPENFLOW, NodeMapping.toNodeConnectorType(ncId, nodeId ));
+
+        ncId = buildNodeConnectorId("1", OutputPortValues.CONTROLLER.toString());
+        Assert.assertEquals(NodeConnectorIDType.CONTROLLER, NodeMapping.toNodeConnectorType(ncId, nodeId ));
+
+        ncId = buildNodeConnectorId("1", OutputPortValues.NORMAL.toString());
+        Assert.assertEquals(NodeConnectorIDType.HWPATH, NodeMapping.toNodeConnectorType(ncId, nodeId ));
+
+        ncId = buildNodeConnectorId("1", OutputPortValues.LOCAL.toString());
+        Assert.assertEquals(NodeConnectorIDType.SWSTACK, NodeMapping.toNodeConnectorType(ncId, nodeId ));
+    }
+
+    /**
+     * Test method for
+     * {@link org.opendaylight.controller.sal.compatibility.NodeMapping#toADNodeConnectorId(NodeConnectorId, NodeId)}
+     * .
+     */
+    @Test
+    public void testToAdNodeConnectorId() {
+        NodeConnectorId nodeConnectorId = buildNodeConnectorId("1", "2");
+        NodeId nodeId = buildNodeId("1");
+        Assert.assertEquals(Short.valueOf((short) 2), NodeMapping.toADNodeConnectorId(nodeConnectorId , nodeId));
+    }
+
+    /**
+     * Test method for
+     * {@link org.opendaylight.controller.sal.compatibility.NodeMapping#toNodeRef(Node)}
+     * .
+     * @throws ConstructionException
+     */
+    @Test
+    public void testToNodeRef() throws ConstructionException {
+        org.opendaylight.controller.sal.core.Node node = new org.opendaylight.controller.sal.core.Node(NodeIDType.OPENFLOW, 42L);
+        InstanceIdentifier<?> nodePath = NodeMapping.toNodeRef(node).getValue();
+
+        String observedId = nodePath.firstKeyOf(Node.class, NodeKey.class).getId().getValue();
+        Assert.assertEquals("openflow:42", observedId);
+    }
+
+    /**
+     * Test method for
+     * {@link org.opendaylight.controller.sal.compatibility.NodeMapping#toNodeConnectorRef(org.opendaylight.controller.sal.core.NodeConnector)}
+     * .
+     * @throws ConstructionException
+     */
+    @Test
+    public void testToNodeConnectorRef() throws ConstructionException {
+        org.opendaylight.controller.sal.core.Node node = new org.opendaylight.controller.sal.core.Node(NodeIDType.OPENFLOW, 42L);
+        org.opendaylight.controller.sal.core.NodeConnector nodeConnector =
+                new org.opendaylight.controller.sal.core.NodeConnector(
+                        NodeConnectorIDType.OPENFLOW, (short) 1, node);
+
+        InstanceIdentifier<?> nodeConnectorPath = NodeMapping.toNodeConnectorRef(nodeConnector ).getValue();
+        String observedNodeId = nodeConnectorPath.firstKeyOf(Node.class, NodeKey.class).getId().getValue();
+        Assert.assertEquals("openflow:42", observedNodeId);
+
+        String observedNodeConnectorId = nodeConnectorPath.firstKeyOf(NodeConnector.class, NodeConnectorKey.class).getId().getValue();
+        Assert.assertEquals("openflow:1", observedNodeConnectorId);
+    }
+
+    /**
+     * Test method for
+     * {@link org.opendaylight.controller.sal.compatibility.NodeMapping#openflowFullNodeIdToLong(String)}
+     * .
+     * @throws ConstructionException
+     */
+    @Test
+    public void testOpenflowFullNodeIdToLong() throws ConstructionException {
+        Assert.assertEquals(42L, NodeMapping.openflowFullNodeIdToLong("42").longValue());
+        Assert.assertEquals(0xCC4E241C4A000000L, NodeMapping.openflowFullNodeIdToLong("14721743935839928320").longValue());
+    }
+
+    /**
+     * @param nodeId
+     * @param portId
+     * @return nodeConnectorId
+     */
+    public static NodeConnectorId buildNodeConnectorId(String nodeId, String portId) {
+        return new NodeConnectorId(NodeConnectorIDType.OPENFLOW+"|" + nodeId + ":" + portId);
+    }
+
+    /**
+     * @param id
+     * @return nodeId
+     */
+    public static NodeId buildNodeId(String id) {
+        return new NodeId(NodeConnectorIDType.OPENFLOW+"|" + id);
+    }
 }
index 5d5a409445a4708bf3b04472ded1e3bac89be496..b6e611bf1155087e4faf965e148443e34692308b 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013-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,
@@ -41,6 +41,11 @@ import org.opendaylight.controller.sal.action.SetVlanPcp;
 import org.opendaylight.controller.sal.action.SwPath;
 import org.opendaylight.controller.sal.compatibility.MDFlowMapping;
 import org.opendaylight.controller.sal.compatibility.ToSalConversionsUtils;
+import org.opendaylight.controller.sal.core.ConstructionException;
+import org.opendaylight.controller.sal.core.Node;
+import org.opendaylight.controller.sal.core.Node.NodeIDType;
+import org.opendaylight.controller.sal.core.NodeConnector;
+import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType;
 import org.opendaylight.controller.sal.flowprogrammer.Flow;
 import org.opendaylight.controller.sal.match.Match;
 import org.opendaylight.controller.sal.match.MatchType;
@@ -79,11 +84,11 @@ import com.google.common.net.InetAddresses;
 
 public class TestFromSalConversionsUtils {
     private enum MtchType {
-        other, ipv4, ipv6, arp, sctp, tcp, udp
+        other, untagged, ipv4, ipv6, arp, sctp, tcp, udp
     }
 
     @Test
-    public void testFromSalConversion() {
+    public void testFromSalConversion() throws ConstructionException {
 
         Flow salFlow = prepareSalFlowCommon();
         NodeFlow odNodeFlow = MDFlowMapping.flowAdded(salFlow);
@@ -93,6 +98,9 @@ public class TestFromSalConversionsUtils {
         odNodeFlow = MDFlowMapping.flowAdded(prepareSalMatch(salFlow, MtchType.other));
         checkOdMatch(odNodeFlow.getMatch(), MtchType.other);
 
+        odNodeFlow = MDFlowMapping.flowAdded(prepareSalMatch(salFlow, MtchType.untagged));
+        checkOdMatch(odNodeFlow.getMatch(), MtchType.untagged);
+
         odNodeFlow = MDFlowMapping.flowAdded(prepareSalMatch(salFlow, MtchType.arp));
         checkOdMatch(odNodeFlow.getMatch(), MtchType.arp);
 
@@ -160,15 +168,26 @@ public class TestFromSalConversionsUtils {
             assertNotNull("Ipv6 wasn't found", ipv6Found);
             break;
         case other:
+            assertEquals("Incoming port is wrong.", "openflow:12345:10", match.getInPort().getValue());
             assertEquals("Source MAC address is wrong.", "ff:ee:dd:cc:bb:aa", match.getEthernetMatch()
                     .getEthernetSource().getAddress().getValue());
             assertEquals("Destinatio MAC address is wrong.", "ff:ee:dd:cc:bb:aa", match.getEthernetMatch()
                     .getEthernetDestination().getAddress().getValue());
+            assertEquals("Vlan ID is not present.", Boolean.TRUE, match.getVlanMatch().getVlanId().isVlanIdPresent());
             assertEquals("Vlan ID is wrong.", (Integer) 0xfff, match.getVlanMatch().getVlanId().getVlanId().getValue());
             assertEquals("Vlan ID priority is wrong.", (short) 0x7, (short) match.getVlanMatch().getVlanPcp()
                     .getValue());
             assertEquals("DCSP is wrong.", (short) 0x3f, (short) match.getIpMatch().getIpDscp().getValue());
             break;
+        case untagged:
+            assertEquals("Source MAC address is wrong.", "ff:ee:dd:cc:bb:aa", match.getEthernetMatch()
+                    .getEthernetSource().getAddress().getValue());
+            assertEquals("Destinatio MAC address is wrong.", "ff:ee:dd:cc:bb:aa", match.getEthernetMatch()
+                    .getEthernetDestination().getAddress().getValue());
+            assertEquals("Vlan ID is present.", Boolean.FALSE, match.getVlanMatch().getVlanId().isVlanIdPresent());
+            assertEquals("Vlan ID is wrong.", Integer.valueOf(0), match.getVlanMatch().getVlanId().getVlanId().getValue());
+            assertEquals("DCSP is wrong.", (short) 0x3f, (short) match.getIpMatch().getIpDscp().getValue());
+            break;
         case sctp:
             boolean sctpFound = false;
             assertEquals("Wrong protocol", CRUDP, match.getIpMatch().getIpProtocol().byteValue());
@@ -334,7 +353,7 @@ public class TestFromSalConversionsUtils {
         return salFlow;
     }
 
-    private Flow prepareSalMatch(Flow salFlow, MtchType mt) {
+    private Flow prepareSalMatch(Flow salFlow, MtchType mt) throws ConstructionException {
         Match salMatch = new Match();
         switch (mt) {
         case arp:
@@ -355,12 +374,21 @@ public class TestFromSalConversionsUtils {
             salMatch.setField(MatchType.NW_DST, InetAddresses.forString("2001:0db8:85a3:0000:0000:8a2e:0370:7336"));
             break;
         case other:
+            Node node = new Node(NodeIDType.OPENFLOW, 12345L);
+            NodeConnector port = new NodeConnector(NodeConnectorIDType.OPENFLOW, Short.valueOf((short)10), node);
+            salMatch.setField(MatchType.IN_PORT, port);
             salMatch.setField(MatchType.DL_SRC, new byte[]{(byte )0xff,(byte )0xee,(byte )0xdd,(byte )0xcc,(byte )0xbb,(byte )0xaa});
             salMatch.setField(MatchType.DL_DST, new byte[]{(byte )0xff,(byte )0xee,(byte )0xdd,(byte )0xcc,(byte )0xbb,(byte )0xaa});
             salMatch.setField(MatchType.DL_VLAN, (short) 0xfff);
             salMatch.setField(MatchType.DL_VLAN_PR, (byte) 0x7);
             salMatch.setField(MatchType.NW_TOS, (byte) 0x3f);
             break;
+        case untagged:
+            salMatch.setField(MatchType.DL_SRC, new byte[]{(byte )0xff,(byte )0xee,(byte )0xdd,(byte )0xcc,(byte )0xbb,(byte )0xaa});
+            salMatch.setField(MatchType.DL_DST, new byte[]{(byte )0xff,(byte )0xee,(byte )0xdd,(byte )0xcc,(byte )0xbb,(byte )0xaa});
+            salMatch.setField(MatchType.DL_VLAN, MatchType.DL_VLAN_NONE);
+            salMatch.setField(MatchType.NW_TOS, (byte) 0x3f);
+            break;
         case sctp:
             salMatch.setField(MatchType.NW_PROTO, CRUDP);
             salMatch.setField(MatchType.TP_SRC, (short) 0xffff);
index 4d3509769c5c791e399e6a98357759c6c009d952..7601a7d9cf67ba543d50d8e49b3fb0d6bbe1ae82 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013-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,
@@ -22,6 +22,8 @@ import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 
+import junit.framework.Assert;
+
 import org.junit.Test;
 import org.opendaylight.controller.sal.action.Flood;
 import org.opendaylight.controller.sal.action.FloodAll;
@@ -47,6 +49,8 @@ import org.opendaylight.controller.sal.compatibility.ToSalConversionsUtils;
 import org.opendaylight.controller.sal.core.ConstructionException;
 import org.opendaylight.controller.sal.core.Node;
 import org.opendaylight.controller.sal.core.Node.NodeIDType;
+import org.opendaylight.controller.sal.core.NodeConnector;
+import org.opendaylight.controller.sal.core.NodeConnector.NodeConnectorIDType;
 import org.opendaylight.controller.sal.flowprogrammer.Flow;
 import org.opendaylight.controller.sal.match.MatchType;
 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Dscp;
@@ -115,6 +119,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instru
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.instruction.apply.actions._case.ApplyActionsBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.EtherType;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.l2.types.rev130827.VlanPcp;
@@ -148,7 +153,7 @@ public class TestToSalConversionsUtils {
     // prefix:
     // od|Od = Open Daylight
     private enum MtchType {
-        other, ipv4, ipv6, arp, sctp, tcp, udp
+        other, untagged, ipv4, ipv6, arp, sctp, tcp, udp
     }
 
     @Test
@@ -161,6 +166,9 @@ public class TestToSalConversionsUtils {
         Flow salFlow = ToSalConversionsUtils.toFlow(prepareOdFlow(odNodeFlowBuilder, MtchType.other), node);
         checkSalMatch(salFlow.getMatch(), MtchType.other);
 
+        salFlow = ToSalConversionsUtils.toFlow(prepareOdFlow(odNodeFlowBuilder, MtchType.untagged), node);
+        checkSalMatch(salFlow.getMatch(), MtchType.untagged);
+
         salFlow = ToSalConversionsUtils.toFlow(prepareOdFlow(odNodeFlowBuilder, MtchType.ipv4), node);
         checkSalMatch(salFlow.getMatch(), MtchType.ipv4);
 
@@ -182,7 +190,18 @@ public class TestToSalConversionsUtils {
         checkSalFlow(salFlow);
     }
 
-    private void checkSalMatch(org.opendaylight.controller.sal.match.Match match, MtchType mt) {
+    /**
+     * test of {@link ToSalConversionsUtils#fromNodeConnectorRef(Uri, Node)}
+     * @throws ConstructionException
+     */
+    @Test
+    public void testFromNodeConnectorRef() throws ConstructionException {
+        Node node = new Node(NodeIDType.OPENFLOW, 42L);
+        NodeConnector nodeConnector = ToSalConversionsUtils.fromNodeConnectorRef(new Uri("1"), node);
+        Assert.assertEquals("OF|1@OF|00:00:00:00:00:00:00:2a", nodeConnector.toString());
+    }
+
+    private void checkSalMatch(org.opendaylight.controller.sal.match.Match match, MtchType mt) throws ConstructionException {
         switch (mt) {
         case other:
             /*assertNotNull("DL_DST isn't equal.", "3C:A9:F4:00:E0:C8",
@@ -190,12 +209,21 @@ public class TestToSalConversionsUtils {
             assertEquals("DL_SRC isn't equal.", "24:77:03:7C:C5:F1",
                     new String((byte[]) match.getField(MatchType.DL_SRC).getValue()));
             */
+            Node node = new Node(NodeIDType.OPENFLOW, 12L);
+            NodeConnector port = new NodeConnector(NodeConnectorIDType.OPENFLOW, Short.valueOf((short)345), node);
+            assertEquals("IN_PORT isn't equal.", port, match.getField(MatchType.IN_PORT).getValue());
             assertEquals("DL_TYPE isn't equal.", (short) 0xffff, (short) match.getField(MatchType.DL_TYPE).getValue());
             assertEquals("NW_TOS isn't equal.", (byte) 0x33, (byte) match.getField(MatchType.NW_TOS).getValue());
             assertEquals("NW_PROTO isn't equal.", (byte) 0x3f, (byte) match.getField(MatchType.NW_PROTO).getValue());
             assertEquals("DL_VLAN isn't equal.", (short) 0xfff, (short) match.getField(MatchType.DL_VLAN).getValue());
             assertEquals("DL_VLAN_PR isn't equal.", (byte) 0x7, (byte) match.getField(MatchType.DL_VLAN_PR).getValue());
             break;
+        case untagged:
+            assertEquals("DL_TYPE isn't equal.", (short) 0xffff, (short) match.getField(MatchType.DL_TYPE).getValue());
+            assertEquals("NW_TOS isn't equal.", (byte) 0x33, (byte) match.getField(MatchType.NW_TOS).getValue());
+            assertEquals("NW_PROTO isn't equal.", (byte) 0x3f, (byte) match.getField(MatchType.NW_PROTO).getValue());
+            assertEquals("DL_VLAN isn't equal.", MatchType.DL_VLAN_NONE, (short) match.getField(MatchType.DL_VLAN).getValue());
+            break;
         case arp:
             /*
             assertEquals("DL_SRC isn't equal.", "22:44:66:88:AA:CC",
@@ -564,10 +592,16 @@ public class TestToSalConversionsUtils {
         MatchBuilder odMatchBuilder = new MatchBuilder();
         switch (mt) {
         case other:
+            odMatchBuilder.setInPort(new NodeConnectorId("openflow:12:345"));
             odMatchBuilder.setEthernetMatch(prepEthernetMatch());
             odMatchBuilder.setIpMatch(prepIpMatch());
             odMatchBuilder.setVlanMatch(prepVlanMatch());
             break;
+        case untagged:
+            odMatchBuilder.setEthernetMatch(prepEthernetMatch());
+            odMatchBuilder.setIpMatch(prepIpMatch());
+            odMatchBuilder.setVlanMatch(prepVlanNoneMatch());
+            break;
         case ipv4:
             odMatchBuilder.setLayer3Match(prepLayer3MatchIpv4());
             break;
@@ -650,11 +684,20 @@ public class TestToSalConversionsUtils {
         VlanMatchBuilder vlanMatchBuilder = new VlanMatchBuilder();
 
         VlanIdBuilder vlanIdBuilder = new VlanIdBuilder().setVlanId(new VlanId(0xfff));
-        vlanMatchBuilder.setVlanId(vlanIdBuilder.build());
+        vlanMatchBuilder.setVlanId(vlanIdBuilder.setVlanIdPresent(true).build());
         vlanMatchBuilder.setVlanPcp(new VlanPcp((short) 0x7));
 
         return vlanMatchBuilder.build();
+    }
 
+    private VlanMatch prepVlanNoneMatch() {
+        VlanMatchBuilder vlanMatchBuilder = new VlanMatchBuilder();
+
+        VlanIdBuilder vlanIdBuilder = new VlanIdBuilder().
+            setVlanIdPresent(false);
+        vlanMatchBuilder.setVlanId(vlanIdBuilder.build());
+
+        return vlanMatchBuilder.build();
     }
 
     private IpMatch prepIpMatch() {
diff --git a/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/topology/test/TopologyMappingTest.java b/opendaylight/md-sal/compatibility/sal-compatibility/src/test/java/org/opendaylight/controller/sal/compatibility/topology/test/TopologyMappingTest.java
new file mode 100644 (file)
index 0000000..b76370a
--- /dev/null
@@ -0,0 +1,72 @@
+/**
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.sal.compatibility.topology.test;
+
+import junit.framework.Assert;
+
+import org.junit.Test;
+import org.opendaylight.controller.sal.compatibility.topology.TopologyMapping;
+import org.opendaylight.controller.sal.core.ConstructionException;
+import org.opendaylight.controller.sal.core.Node;
+import org.opendaylight.controller.sal.core.NodeConnector;
+import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId;
+import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TpId;
+
+/**
+ * test for {@link TopologyMapping}
+ */
+public class TopologyMappingTest {
+
+    /**
+     * Test method for {@link org.opendaylight.controller.sal.compatibility.topology.TopologyMapping#toADNodeId(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId)}.
+     */
+    @Test
+    public void testToADNodeId() {
+        NodeId nodeId = new NodeId("openflow:1");
+        String observedNodeId = TopologyMapping.toADNodeId(nodeId);
+
+        Assert.assertEquals("1", observedNodeId);
+    }
+
+    /**
+     * Test method for {@link org.opendaylight.controller.sal.compatibility.topology.TopologyMapping#toADNodeConnector(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TpId, org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId)}.
+     * @throws ConstructionException
+     */
+    @Test
+    public void testToADNodeConnector() throws ConstructionException {
+        NodeId nodeId = new NodeId("openflow:1");
+        TpId source = new TpId("foo:2");
+        NodeConnector observedNodeConnector = TopologyMapping.toADNodeConnector(source, nodeId);
+
+        Assert.assertEquals("OF|2@OF|00:00:00:00:00:00:00:01", observedNodeConnector.toString());
+    }
+
+    /**
+     * Test method for {@link org.opendaylight.controller.sal.compatibility.topology.TopologyMapping#toADNodeConnectorId(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TpId)}.
+     */
+    @Test
+    public void testToADNodeConnectorId() {
+        TpId source = new TpId("foo:2");
+        String observedNodeConnectorId = TopologyMapping.toADNodeConnectorId(source);
+
+        Assert.assertEquals("2", observedNodeConnectorId);
+    }
+
+    /**
+     * Test method for {@link org.opendaylight.controller.sal.compatibility.topology.TopologyMapping#toADNode(org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId)}.
+     * @throws ConstructionException
+     */
+    @Test
+    public void testToADNode() throws ConstructionException {
+        NodeId nodeId = new NodeId("openflow:1");
+        Node observedNode = TopologyMapping.toADNode(nodeId);
+
+        Assert.assertEquals("OF|00:00:00:00:00:00:00:01", observedNode.toString());
+    }
+
+}
diff --git a/opendaylight/md-sal/model/model-flow-base/src/main/java/org/opendaylight/yang/gen/v1/urn/opendaylight/flow/types/port/rev130925/PortNumberBuilder.java b/opendaylight/md-sal/model/model-flow-base/src/main/java/org/opendaylight/yang/gen/v1/urn/opendaylight/flow/types/port/rev130925/PortNumberBuilder.java
new file mode 100644 (file)
index 0000000..ff78a74
--- /dev/null
@@ -0,0 +1,24 @@
+/*
+ * 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.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.CommonPort.PortNumber;
+
+
+public class PortNumberBuilder {
+
+    public static PortNumber getDefaultInstance(java.lang.String defaultValue) {
+        try {
+            long uint32 = Long.parseLong(defaultValue);
+            return new PortNumber(uint32);
+        } catch(NumberFormatException e){
+            return new PortNumber(defaultValue);
+        }
+    }
+
+}
index efe1ce3e3aaebad8d2b2a0a866d5d12392238a7c..deff6f17984cce55c8bcf97b43159f42852ebfec 100644 (file)
@@ -275,6 +275,17 @@ module opendaylight-match-types {
         }
     }
 
+    grouping "tunnel-ipv4-match-fields" {
+        leaf tunnel-ipv4-source {
+            description "IPv4 source tunnel endpoint address.";
+            type inet:ipv4-prefix;
+        }
+        leaf tunnel-ipv4-destination {
+            description "IPv4 destination tunnel endpoint address.";
+            type inet:ipv4-prefix;
+        }
+    }
+
     grouping match {
         leaf in-port {
             type inv:node-connector-id;
@@ -321,6 +332,9 @@ module opendaylight-match-types {
             case "arp-match" {
                 uses "arp-match-fields";
             }
+            case "tunnel-ipv4-match" {
+                uses "tunnel-ipv4-match-fields";
+            }
         }
 
         choice layer-4-match {
index f1cbd8dc29e7b2a5d0b29cef831c9c0068752a7d..9e880987524c3cee54d7f0486f7dce5df272ae17 100644 (file)
@@ -62,7 +62,10 @@ module opendaylight-port-types {
     grouping common-port {
 
         leaf port-number {
-            type uint32;
+            type union {
+                type uint32;
+                type string;
+            }
         }
         
         leaf hardware-address {
index c271f8f4d00a6b99318bc25baeae9251ac13ea97..393f6db9febbc0970b36c3dca1d8bf4d24ae674d 100644 (file)
@@ -192,6 +192,14 @@ module opendaylight-table-types {
         base match-field;
         description "TCP Flag Match";
     }
+    identity tunnel_ipv4_dst {
+        base match-field;
+        description "IPv4 destination tunnel endpoint address.";
+    }
+    identity tunnel_ipv4_src {
+        base match-field;
+        description "IPv4 source tunnel endpoint address.";
+    }
         
     grouping set-field-match {
         list set-field-match {
diff --git a/opendaylight/md-sal/model/model-flow-management/pom.xml b/opendaylight/md-sal/model/model-flow-management/pom.xml
deleted file mode 100644 (file)
index 64f1158..0000000
+++ /dev/null
@@ -1,36 +0,0 @@
-<?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.model</groupId>
-    <artifactId>model-parent</artifactId>
-    <version>1.1-SNAPSHOT</version>
-  </parent>
-  <artifactId>model-flow-management</artifactId>
-  <packaging>bundle</packaging>
-
-  <dependencies>
-    <dependency>
-      <groupId>${project.groupId}</groupId>
-      <artifactId>model-flow-base</artifactId>
-      <version>${project.version}</version>
-    </dependency>
-    <dependency>
-      <groupId>${project.groupId}</groupId>
-      <artifactId>model-inventory</artifactId>
-      <version>${project.version}</version>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.yangtools.model</groupId>
-      <artifactId>opendaylight-l2-types</artifactId>
-    </dependency>
-  </dependencies>
-  <scm>
-    <connection>scm:git:ssh://git.opendaylight.org:29418/controller.git</connection>
-    <developerConnection>scm:git:ssh://git.opendaylight.org:29418/controller.git</developerConnection>
-    <tag>HEAD</tag>
-    <url>https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL</url>
-  </scm>
-</project>
diff --git a/opendaylight/md-sal/model/model-flow-management/src/main/yang/flow-management.yang b/opendaylight/md-sal/model/model-flow-management/src/main/yang/flow-management.yang
deleted file mode 100644 (file)
index b8579bc..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-module flow-management {
-    namespace "urn:opendaylight:flow:config";
-    prefix flow-cfg;
-
-    import opendaylight-inventory {prefix inv;revision-date "2013-08-19";}
-    import opendaylight-flow-types {prefix flow;}
-
-    revision "2013-08-19" {
-        description "Initial revision of flow service";
-    }
-
-
-    grouping flow-entry {
-        leaf node {
-            type inv:node-ref;
-        }
-        uses flow:flow;
-    }
-
-    container flows {
-        list flow {
-            key "node id"; 
-
-            leaf id {
-                type uint32;
-            }
-            uses flow-entry;
-        }
-    }
-}
diff --git a/opendaylight/md-sal/model/model-flow-management/src/main/yang/group-management.yang b/opendaylight/md-sal/model/model-flow-management/src/main/yang/group-management.yang
deleted file mode 100644 (file)
index 814c7e4..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-module group-management {
-    namespace "urn:opendaylight:group:config";
-    prefix group-cfg;
-
-    import opendaylight-inventory {prefix inv;revision-date "2013-08-19";}  
-    import opendaylight-group-types {prefix group;}
-
-    revision "2013-10-24" {
-        description "Initial revision of group service";
-    }
-
-    grouping group-entry {
-        leaf node {
-            type inv:node-ref;
-        }
-        uses group:group;
-    }   
-     
-    container groups {
-        list group {
-            key "id node"; 
-                        
-            leaf id {
-                type uint32;
-            }                       
-            
-            uses group-entry;
-        }
-    }    
-}
diff --git a/opendaylight/md-sal/model/model-flow-management/src/main/yang/meter-management.yang b/opendaylight/md-sal/model/model-flow-management/src/main/yang/meter-management.yang
deleted file mode 100644 (file)
index 6d86c50..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-module meter-management {
-    namespace "urn:opendaylight:meter:config";
-    prefix meter-cfg;
-
-    import opendaylight-inventory {prefix inv;revision-date "2013-08-19";}  
-    import opendaylight-meter-types {prefix meter;}
-
-    revision "2013-10-24" {
-        description "Initial revision of meter service";
-    }
-
-    grouping meter-entry {
-        leaf node {
-            type inv:node-ref;
-        }
-        uses meter:meter;
-    }   
-     
-    container meters {
-        list meter {
-            key "id node"; 
-                        
-            leaf id {
-                type uint32;
-            }                    
-            
-            uses meter-entry;
-        }
-    }    
-}
diff --git a/opendaylight/md-sal/model/model-flow-management/src/main/yang/port-management.yang b/opendaylight/md-sal/model/model-flow-management/src/main/yang/port-management.yang
deleted file mode 100644 (file)
index 77483de..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-module port-management {
-    namespace "urn:opendaylight:port:config";
-    prefix port-cfg;
-
-    import opendaylight-inventory {prefix inv;revision-date "2013-08-19";}    
-    import opendaylight-port-types {prefix port;}
-
-    revision "2013-10-24" {
-        description "Initial revision of port service";
-    }
-
-    grouping port-entry {
-        leaf node {
-            type inv:node-ref;
-        }
-        uses port:port-mod;
-    }   
-     
-    container ports {
-        list port {
-            key "id node"; 
-                        
-            leaf id {
-                type uint32;
-            }                       
-            
-            uses port-entry;
-        }
-    }    
-}
diff --git a/opendaylight/md-sal/model/model-flow-management/src/main/yang/queue-management.yang b/opendaylight/md-sal/model/model-flow-management/src/main/yang/queue-management.yang
deleted file mode 100644 (file)
index c8a7fbb..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-module queue-management {
-    namespace "urn:opendaylight:queue:config";
-    prefix queue-cfg;
-
-    import opendaylight-inventory {prefix inv;revision-date "2013-08-19";}      
-     
-    import opendaylight-queue-types {prefix queue; revision-date "2013-09-25";}
-
-   
-    revision "2013-10-24" {
-        description "Initial revision of queue service";
-    }
-
-    grouping queue-entry {
-        leaf node {
-            type inv:node-connector-ref;
-           
-        }
-        uses queue:queue-config-request;
-    }   
-     
-    container queues {
-        list queue {
-            key "id node"; 
-                        
-            leaf id {
-                type uint32;
-            }                       
-            
-            uses queue-entry;
-        }
-    }    
-}
diff --git a/opendaylight/md-sal/model/model-flow-management/src/main/yang/table-management.yang b/opendaylight/md-sal/model/model-flow-management/src/main/yang/table-management.yang
deleted file mode 100644 (file)
index 06edb04..0000000
+++ /dev/null
@@ -1,32 +0,0 @@
-module table-management {
-    namespace "urn:opendaylight:table:config";
-    prefix table-cfg;
-    
-    import opendaylight-inventory {prefix inv;revision-date "2013-08-19";}
-    import opendaylight-table-types {prefix table;}
-
-    revision "2013-10-24" {
-        description "Initial revision of table service";
-    }
-
-    grouping table-entry {
-    
-        leaf node {
-            type inv:node-ref;
-        }
-        
-        uses table:table-features;
-    }   
-     
-    container tables {
-        list table {
-            key "id node"; 
-                        
-            leaf id {
-                type uint32;
-            }                    
-            
-            uses table-entry;
-        }
-    }    
-}
index a8eec2693615a55ab49ffd6d566ef8e503bffd72..69db856b73b172fa7f2bd966b5ba6f29984a54ca 100644 (file)
@@ -73,7 +73,6 @@ module node-error {
             uses tr:transaction-metadata;
             uses flow:base-node-error-notification;
             uses flow:node-error-reference;
-            uses flow:node-error-reference;
         }
 
     notification group-mod-error-notification {
index 396206e28ed30f1a03c8b28f72fec645911fa86f..64d212e9bc57e514f4616d4fb5078d636315003a 100644 (file)
@@ -9,8 +9,8 @@ module opendaylight-inventory {
     revision "2013-08-19" {
         description "Initial revision of Inventory model";
     }
-    
-    
+
+
     typedef support-type {
         type enumeration {
             enum native;
@@ -21,43 +21,79 @@ module opendaylight-inventory {
 
     typedef node-id {
         type inet:uri;
+        description "Identifier for a particular node. For example:
+
+                        myprotocol:<unique_node_id>
+
+                        myprotocol:12
+
+                    It is a good practice to always lead with a scoping identifier.
+                    In the example above the scoping was 'myprotocol'. In your app you
+                    could use 'myapp' etc.";
     }
 
     typedef node-connector-id {
         type inet:uri;
+        description "Identifier for a particular node-connector. For example:
+
+                        myprotocol:<unique_node_connector_id>
+                        myprotocol:3
+
+                    It is a good practice to always lead with a scoping identifier.
+                    In the example above the scoping was 'myprotocol'. In your app you
+                    could use 'myapp' etc.";
+
     }
 
+    //YANG does not have a statement which limits the scope of an instance-identifier to a particular subtree,
+    //which is why we are using a type capture and not an instance-identifier to define a node-ref and a node-connector-ref.
     typedef node-ref {
         type instance-identifier;
+        description "A reference that points to an opendaylight-light:nodes/node in the data tree.";
     }
 
     typedef node-connector-ref {
         type instance-identifier;
+        description "A reference that points to an opendaylight-list:nodes/node/{node-id}/node-connector in the data tree.";
     }
 
     identity node-context {
-        description "Identity used to mark node context";
+        description "A node-context is a classifier for node elements which allows an RPC to provide a service on behalf of a particular element in the data tree.";
     }
 
     identity node-connector-context {
-        description "Identity used to mark node connector context";
+        description "A node-connector-context is a classifier for node-connector elements which allows an RPC to provide a service on behalf of a particular element in the data tree.";
     }
 
+    //We are defining a base identity here because there are limitations with yang enums. Yang doesn't allow you to extend enumeratations.
+    //Therefore by defining a base identity we allow other yang files to extend this identity to define additional "enumerations". By
+    //using node-type as their base they are able to pass their object to fields that accept "node-types" while uniquely describing their
+    //type of node, such as "router-node" or "switch-node" etc.
+    //See https://wiki.opendaylight.org/view/YANG_Tools:YANG_to_Java_Mapping#Identity for more information.
     identity node-type {
-        description "Base identity for node types";
+        description "A base identity definition which represents a generic node type and can be extended in other yang files.";
     }
 
     identity node-connector-type {
-        description "Base identity for node connectors type";
+        description "A base identity definition which represents a generic node connector type and can be extended in other yang files.";
     }
 
     grouping node {
+
+        description "Describes the contents of a generic node -
+                     essentially an ID and a list of node-connectors.
+                     Acts as an augmentation point where other yang files
+                      can add additional information.";
+
         leaf id {
             type node-id;
+            description "The unique identifier for the node.";
         }
 
         list "node-connector" {
             key "id";
+
+            description "A list of node connectors that belong this node.";
             ext:context-instance "node-connector-context";
 
             uses node-connector;
@@ -65,55 +101,117 @@ module opendaylight-inventory {
     }
 
     grouping node-connector {
+
+        description "Describes a generic node connector which consists of an ID.
+                     Acts as an augmentation point where other yang files can
+                      add additional information.";
+
         leaf id {
             type node-connector-id;
+            description "The unique identifier for the node-connector.";
         }
     }
 
     grouping node-context-ref {
-        description 
-        "Helper grouping which contains a reference to node context.";
+        description
+        "A helper grouping which contains a reference to a node classified with a node-context. This allows RPCs in other yang files to refine their input to a particular node instance.";
+
         leaf node {
             ext:context-reference "node-context";
             type node-ref;
+            description "A reference to a particular node.";
         }
     }
 
     /** Base structure **/
     container nodes {
+
+        description "The root container of all nodes.";
+
         list node {
             key "id";
             ext:context-instance "node-context";
-
-            uses node;
+            description "A list of nodes (as defined by the 'grouping node').";
+            uses node; //this refers to the 'grouping node' defined above.
         }
     }
 
+    //The following notifications should really be replaced by direct writes to the data tree with data change listeners listening to those changes.
+    //Notifications should be reserved for one time events which do not require persistence to the data tree.
     notification node-updated {
+
+        status deprecated;
+
+        description "A notification sent by someone who realized there was a modification to a node, but did not modify the data tree.
+                    Describes that something on the node has been updated (including addition of a new node), but is for
+                    whatever reason is not modifying the data tree.
+
+                    Deprecated: If a process determines that a node was updated, then that
+                    logic should update the node using the DataBroker directly. Listeners interested
+                    update changes should register a data change listener for notifications on removals.";
+
         leaf node-ref {
             ext:context-reference "node-context";
+            description "A reference to the node which changed.";
+
             type node-ref;
         }
         uses node;
     }
 
     notification node-connector-updated {
+
+        status deprecated;
+
+        description "A notification sent by someone who realized there was a modification to a node-connector, but did not modify the data tree.
+                    Describes that something on the node-connector has been updated (including addition of a new node-connector), but is for
+                    whatever reason is not modifying the data tree.
+
+                    Deprecated: If a process determines that a node-connector was updated, then that
+                    logic should update the node-connector using the DataBroker directly. Listeners interested
+                    update changes should register a data change listener for notifications on removals.";
+
         leaf node-connector-ref {
             ext:context-reference "node-connector-context";
             type node-connector-ref;
+            description "A reference to the node-connector which changed.";
         }
         uses node-connector;
     }
 
     notification node-removed {
+
+        status deprecated;
+
+        description "A notification sent by someone who realized there was a node was removed, but did not modify the data tree.
+                    Describes that a node has been removed but is for
+                    whatever reason is not modifying the data tree.
+
+                    Deprecated: If a process determines that a node was removed, then that
+                    logic should remove the node from the DataBroker directly. Listeners interested
+                    in changes should register a data change listener for notifications on removals.";
+
         leaf node-ref {
+            description "A reference to the node that was removed.";
             ext:context-reference "node-context";
             type node-ref;
         }
     }
 
     notification node-connector-removed {
+
+        status deprecated;
+
+        description "A notification sent by someone who realized there was a node-connector was removed, but did not modify the data tree.
+                    Describes that a node-connector has been removed but is for
+                    whatever reason is not modifying the data tree.
+
+                    Deprecated: If a process determines that a node-connector was removed, then that
+                    logic should remove the node-connector from the DataBroker directly. Listeners interested
+                    in changes should register a data change listener for notifications on removals.";
+
         leaf node-connector-ref {
+            description "A reference to the node-connector that was removed.";
             ext:context-reference "node-connector-context";
             type node-connector-ref;
         }
index 12b5f766254c933221217d0962f399139a436781..5e6a86745c0ae09b9bd200a5d49f495aafeba276 100644 (file)
@@ -17,7 +17,6 @@
     <module>model-flow-base</module>
     <module>model-flow-service</module>
     <module>model-flow-statistics</module>
-    <module>model-flow-management</module>
     <module>model-topology</module>
   </modules>
 
index 8f11b955a0e37605d9ff741c305f4ef269add851..1cfd5a66399eb4991fedb3cb59098aa62e1d8249 100644 (file)
@@ -54,9 +54,6 @@
     <!-- Compability Packages -->
     <module>compatibility</module>
 
-    <!-- Clustering -->
-    <module>remoterpc-routingtable/implementation</module>
-    <module>sal-remoterpc-connector/implementation</module>
     <!-- Documentation -->
     <module>sal-rest-docgen</module>
 
@@ -66,9 +63,8 @@
     <!--sal-protocolbuffer-encoding-->
     <module>sal-protocolbuffer-encoding</module>
 
-      <!--  Karaf feature -->
-      <module>feature</module>
-
+    <!-- Yang Test Models for MD-SAL -->
+    <module>sal-test-model</module>
   </modules>
 
   <build>
diff --git a/opendaylight/md-sal/remoterpc-routingtable/implementation/pom.xml b/opendaylight/md-sal/remoterpc-routingtable/implementation/pom.xml
deleted file mode 100644 (file)
index 8cab0b5..0000000
+++ /dev/null
@@ -1,97 +0,0 @@
-<?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>sal-parent</artifactId>
-    <version>1.1-SNAPSHOT</version>
-    <relativePath>../..</relativePath>
-  </parent>
-
-  <artifactId>remoterpc-routingtable.implementation</artifactId>
-  <packaging>bundle</packaging>
-  <dependencies>
-
-    <dependency>
-      <groupId>com.google.guava</groupId>
-      <artifactId>guava</artifactId>
-    </dependency>
-
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>clustering.services</artifactId>
-      <version>${clustering.services.version}</version>
-    </dependency>
-
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>sal</artifactId>
-      <exclusions>
-        <exclusion>
-          <groupId>org.osgi</groupId>
-          <artifactId>org.osgi.compendium</artifactId>
-        </exclusion>
-      </exclusions>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>sal-connector-api</artifactId>
-      <version>${project.version}</version>
-    </dependency>
-
-    <dependency>
-      <groupId>junit</groupId>
-      <artifactId>junit</artifactId>
-      <scope>test</scope>
-    </dependency>
-    <dependency>
-      <groupId>org.mockito</groupId>
-      <artifactId>mockito-all</artifactId>
-      <scope>test</scope>
-    </dependency>
-
-  </dependencies>
-
-  <build>
-    <plugins>
-      <plugin>
-        <groupId>org.apache.felix</groupId>
-        <artifactId>maven-bundle-plugin</artifactId>
-        <version>${bundle.plugin.version}</version>
-        <extensions>true</extensions>
-        <configuration>
-          <instructions>
-            <Export-Package>org.opendaylight.controller.sal.connector.remoterpc.api,
-                            org.opendaylight.controller.sal.connector.remoterpc.impl</Export-Package>
-            <Import-Package>javax.xml.bind.annotation,
-                            org.opendaylight.controller.sal.core,
-                            org.opendaylight.controller.sal.utils,
-                            org.opendaylight.controller.sal.packet,
-                            org.opendaylight.controller.sal.topology,
-                            org.opendaylight.controller.clustering.services,
-                            org.opendaylight.controller.md.sal.common.api.data,
-                            org.opendaylight.yangtools.yang.binding,
-                            org.osgi.service.component,
-                            org.slf4j,
-                            org.apache.felix.dm,
-                            org.apache.commons.lang3.builder,
-                            org.apache.commons.lang3.tuple,
-                            org.eclipse.osgi.framework.console,
-                            org.osgi.framework,
-                            javax.transaction,
-                            com.google.common.base,
-                            com.google.common.collect</Import-Package>
-            <Bundle-Activator>org.opendaylight.controller.sal.connector.remoterpc.impl.Activator</Bundle-Activator>
-          </instructions>
-          <manifestLocation>${project.basedir}/META-INF</manifestLocation>
-        </configuration>
-      </plugin>
-    </plugins>
-  </build>
-  <scm>
-    <connection>scm:git:ssh://git.opendaylight.org:29418/controller.git</connection>
-    <developerConnection>scm:git:ssh://git.opendaylight.org:29418/controller.git</developerConnection>
-    <tag>HEAD</tag>
-    <url>https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main</url>
-  </scm>
-</project>
diff --git a/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/RouteChangeListener.java b/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/RouteChangeListener.java
deleted file mode 100644 (file)
index c9b47ed..0000000
+++ /dev/null
@@ -1,18 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.connector.remoterpc.api;
-
-import java.util.EventListener;
-
-public interface RouteChangeListener<I,R> extends EventListener {
-
-
-   void onRouteUpdated(I key, R new_value);
-
-   void onRouteDeleted(I key);
-}
diff --git a/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/RoutingTable.java b/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/RoutingTable.java
deleted file mode 100644 (file)
index e5e314c..0000000
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.connector.remoterpc.api;
-
-import java.util.Set;
-
-public interface RoutingTable<I,R> {
-
-  /**
-   * Adds a network address for the route. If the route already exists,
-   * it throws <code>DuplicateRouteException</code>.
-   * This method would be used when registering a global service.
-   *
-   *
-   * @param routeId route identifier
-   * @param route network address
-   * @throws DuplicateRouteException
-   * @throws RoutingTableException
-   */
-  public void addGlobalRoute(I routeId, R route) throws  RoutingTableException, SystemException;
-
-  /**
-   * Remove the route.
-   * This method would be used when registering a global service.
-   * @param routeId
-   * @throws RoutingTableException
-   * @throws SystemException
-   */
-  public void removeGlobalRoute(I routeId) throws RoutingTableException, SystemException;
-
-  /**
-   * Adds a network address for the route. If the route already exists,
-   * it throws <code>DuplicateRouteException</code>.
-   * This method would be used when registering a global service.
-   *
-   *
-   * @param routeId route identifier
-   * @param route network address
-   * @throws DuplicateRouteException
-   * @throws RoutingTableException
-   */
-  public R getGlobalRoute(I routeId) throws  RoutingTableException, SystemException;
-
-  /**
-   * Adds a network address for the route. If address for route
-   * exists, appends the address to the list
-   *
-   * @param routeId route identifier
-   * @param route network address
-   * @throws RoutingTableException for any logical exception
-   * @throws SystemException
-   */
-  public void addRoute(I routeId, R route) throws RoutingTableException,SystemException;
-
-
-  /**
-   * Removes the network address for the route from routing table. If only
-   * one network address existed, remove the route as well.
-   * @param routeId
-   * @param route
-   */
-  public void removeRoute(I routeId, R route) throws RoutingTableException,SystemException;
-
-  /**
-   * Adds address for a set of route identifiers. If address for route
-   * exists, appends the address to the set.
-   *
-   * @param routeIds a set of routeIds
-   * @param route network address
-   * @throws RoutingTableException for any logical exception
-   * @throws SystemException
-   */
-  public void addRoutes(Set<I> routeIds, R route) throws  RoutingTableException,SystemException;
-
-  /**
-   * Removes address for a set of route identifiers.
-   *
-   * @param routeIds a set of routeIds
-   * @param route network address
-   * @throws RoutingTableException for any logical exception
-   * @throws SystemException
-   */
-  public void removeRoutes(Set<I> routeIds, R route) throws  RoutingTableException,SystemException;
-
-  /**
-   * Returns a set of network addresses associated with this route
-   * @param routeId
-   * @return
-   */
-  public Set<R> getRoutes(I routeId);
-
-
-  /**
-   * Returns the last inserted address from the list of network addresses
-   * associated with the route.
-   * @param routeId
-   * @return
-   */
-  public R getLastAddedRoute(I routeId);
-
-  public class DuplicateRouteException extends RoutingTableException {
-      public DuplicateRouteException(String message) {
-          super(message);
-      }
-
-  }
-
-}
diff --git a/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/RoutingTableException.java b/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/RoutingTableException.java
deleted file mode 100644 (file)
index fc7f6f1..0000000
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.connector.remoterpc.api;
-
-/**
- * @author: syedbahm
- */
-public class RoutingTableException extends Exception {
-
-    /**
-     * Constructs a new exception with {@code null} as its detail message.
-     * The cause is not initialized, and may subsequently be initialized by a
-     * call to {@link #initCause}.
-     */
-    public RoutingTableException() {
-        super();
-    }
-
-    /**
-     * Constructs a new exception with the specified detail message.  The
-     * cause is not initialized, and may subsequently be initialized by
-     * a call to {@link #initCause}.
-     *
-     * @param message the detail message. The detail message is saved for
-     *                later retrieval by the {@link #getMessage()} method.
-     */
-    public RoutingTableException(String message) {
-        super(message);
-    }
-
-    /**
-     * Constructs a new exception with the specified detail message and
-     * cause.  <p>Note that the detail message associated with
-     * {@code cause} is <i>not</i> automatically incorporated in
-     * this exception's detail message.
-     *
-     * @param message the detail message (which is saved for later retrieval
-     *                by the {@link #getMessage()} method).
-     * @param cause   the cause (which is saved for later retrieval by the
-     *                {@link #getCause()} method).  (A <tt>null</tt> value is
-     *                permitted, and indicates that the cause is nonexistent or
-     *                unknown.)
-     */
-    public RoutingTableException(String message, Throwable cause) {
-        super(message, cause);
-    }
-}
diff --git a/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/SystemException.java b/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/api/SystemException.java
deleted file mode 100644 (file)
index 491858e..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-
-
-package org.opendaylight.controller.sal.connector.remoterpc.api;
-
-/**
- * @author: syedbahm
- *
- */
-public class SystemException extends  Exception {
-    /**
-     * Constructs a new exception with {@code null} as its detail message.
-     * The cause is not initialized, and may subsequently be initialized by a
-     * call to {@link #initCause}.
-     */
-    public SystemException() {
-        super();
-    }
-
-    /**
-     * Constructs a new exception with the specified detail message.  The
-     * cause is not initialized, and may subsequently be initialized by
-     * a call to {@link #initCause}.
-     *
-     * @param message the detail message. The detail message is saved for
-     *                later retrieval by the {@link #getMessage()} method.
-     */
-    public SystemException(String message) {
-        super(message);
-    }
-
-    /**
-     * Constructs a new exception with the specified detail message and
-     * cause.  <p>Note that the detail message associated with
-     * {@code cause} is <i>not</i> automatically incorporated in
-     * this exception's detail message.
-     *
-     * @param message the detail message (which is saved for later retrieval
-     *                by the {@link #getMessage()} method).
-     * @param cause   the cause (which is saved for later retrieval by the
-     *                {@link #getCause()} method).  (A <tt>null</tt> value is
-     *                permitted, and indicates that the cause is nonexistent or
-     *                unknown.)
-     * @since 1.4
-     */
-    public SystemException(String message, Throwable cause) {
-        super(message, cause);
-    }
-}
diff --git a/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/impl/Activator.java b/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/impl/Activator.java
deleted file mode 100644 (file)
index a826a3c..0000000
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sal.connector.remoterpc.impl;
-
-import org.apache.felix.dm.Component;
-import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
-import org.opendaylight.controller.clustering.services.IClusterGlobalServices;
-import org.opendaylight.controller.sal.connector.remoterpc.api.RouteChangeListener;
-import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable;
-import org.opendaylight.controller.sal.core.ComponentActivatorAbstractBase;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.util.Dictionary;
-import java.util.HashSet;
-import java.util.Hashtable;
-import java.util.Set;
-
-/**
- * @author: syedbahm
- */
-public class Activator extends ComponentActivatorAbstractBase {
-
-    protected static final Logger logger = LoggerFactory
-            .getLogger(Activator.class);
-    private static final String CACHE_UPDATE_AWARE_REGISTRY_KEY = "cachenames" ;
-
-
-    /**
-     * Method which tells how many Global implementations are
-     * supported by the bundle. This way we can tune the number of
-     * components created. This components will be created ONLY at the
-     * time of bundle startup and will be destroyed only at time of
-     * bundle destruction, this is the major difference with the
-     * implementation retrieved via getImplementations where all of
-     * them are assumed to be in a container!
-     *
-     *
-     * @return The list of implementations the bundle will support,
-     * in Global version
-     */
-
-    @Override
-    protected Object[] getGlobalImplementations(){
-        logger.debug("Calling getGlobalImplementations to return:", RoutingTableImpl.class);
-        return new Object[] {
-                RoutingTableImpl.class
-        };
-    }
-
-    /**
-     * Configure the dependency for a given instance Global
-     *
-     * @param c Component assigned for this instance, this will be
-     * what will be used for configuration
-     * @param imp implementation to be configured
-     *
-     */
-    @Override
-    protected void configureGlobalInstance(Component c, Object imp){
-        if (imp.equals(RoutingTableImpl.class)) {
-            Dictionary<String, Set<String>> props = new Hashtable<String, Set<String>>();
-            Set<String> propSet = new HashSet<String>();
-            propSet.add(RoutingTableImpl.GLOBALRPC_CACHE);
-            propSet.add(RoutingTableImpl.RPC_CACHE);
-            props.put(CACHE_UPDATE_AWARE_REGISTRY_KEY, propSet);
-
-            c.setInterface(new String[] { RoutingTable.class.getName(),ICacheUpdateAware.class.getName()  }, props);
-            logger.debug("configureGlobalInstance adding dependency:", IClusterGlobalServices.class);
-
-
-            // RouteChangeListener services will be none or many so the
-            // dependency is optional
-            c.add(createServiceDependency()
-                    .setService(RouteChangeListener.class)
-                    .setCallbacks("setRouteChangeListener", "unsetRouteChangeListener")
-                    .setRequired(false));
-
-            //dependency is required as it provides us the caching support
-            c.add(createServiceDependency().setService(
-                    IClusterGlobalServices.class).setCallbacks(
-                    "setClusterGlobalServices",
-                    "unsetClusterGlobalServices").setRequired(true));
-
-        }
-    }
-
-
-}
diff --git a/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/impl/RoutingTableImpl.java b/opendaylight/md-sal/remoterpc-routingtable/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/impl/RoutingTableImpl.java
deleted file mode 100644 (file)
index e242b0a..0000000
+++ /dev/null
@@ -1,464 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sal.connector.remoterpc.impl;
-
-import java.util.Collections;
-import java.util.EnumSet;
-import java.util.Iterator;
-import java.util.LinkedHashSet;
-import java.util.Map;
-import java.util.Set;
-import java.util.concurrent.ConcurrentMap;
-
-import javax.transaction.HeuristicMixedException;
-import javax.transaction.HeuristicRollbackException;
-import javax.transaction.NotSupportedException;
-import javax.transaction.RollbackException;
-
-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.CacheListenerAddException;
-import org.opendaylight.controller.clustering.services.ICacheUpdateAware;
-import org.opendaylight.controller.clustering.services.IClusterGlobalServices;
-import org.opendaylight.controller.clustering.services.IClusterServices;
-import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable;
-import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTableException;
-import org.opendaylight.controller.sal.connector.remoterpc.api.SystemException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableSet;
-
-public class RoutingTableImpl<I, R> implements RoutingTable<I, R>, ICacheUpdateAware<I, R> {
-
-    private final Logger log = LoggerFactory.getLogger(RoutingTableImpl.class);
-
-    private IClusterGlobalServices clusterGlobalServices = null;
-
-    private ConcurrentMap<I,R> globalRpcCache = null;
-    private ConcurrentMap<I, LinkedHashSet<R>> rpcCache = null;  //need routes to ordered by insert-order
-
-    public static final String GLOBALRPC_CACHE = "remoterpc_routingtable.globalrpc_cache";
-    public static final String RPC_CACHE = "remoterpc_routingtable.rpc_cache";
-
-    public RoutingTableImpl() {
-    }
-
-    @Override
-    public R getGlobalRoute(final I routeId) throws RoutingTableException, SystemException {
-        Preconditions.checkNotNull(routeId, "getGlobalRoute: routeId cannot be null!");
-        return globalRpcCache.get(routeId);
-    }
-
-    @Override
-    public void addGlobalRoute(final I routeId, final R route) throws RoutingTableException, SystemException {
-        Preconditions.checkNotNull(routeId, "addGlobalRoute: routeId cannot be null!");
-        Preconditions.checkNotNull(route, "addGlobalRoute: route cannot be null!");
-        try {
-
-            log.debug("addGlobalRoute: adding  a new route with id[{}] and value [{}]", routeId, route);
-            clusterGlobalServices.tbegin();
-            if (globalRpcCache.putIfAbsent(routeId, route) != null) {
-                throw new DuplicateRouteException(" There is already existing route " + routeId);
-            }
-            clusterGlobalServices.tcommit();
-
-        } catch (NotSupportedException | HeuristicRollbackException | RollbackException | HeuristicMixedException e) {
-            throw new RoutingTableException("Transaction error - while trying to create route id="
-                    + routeId + "with route" + route, e);
-        } catch (javax.transaction.SystemException e) {
-            throw new SystemException("System error occurred - while trying to create with value", e);
-        }
-
-    }
-
-    @Override
-    public void removeGlobalRoute(final I routeId) throws RoutingTableException, SystemException {
-        Preconditions.checkNotNull(routeId, "removeGlobalRoute: routeId cannot be null!");
-        try {
-            log.debug("removeGlobalRoute: removing  a new route with id [{}]", routeId);
-
-            clusterGlobalServices.tbegin();
-            globalRpcCache.remove(routeId);
-            clusterGlobalServices.tcommit();
-
-        } catch (NotSupportedException | HeuristicRollbackException | RollbackException | HeuristicMixedException e) {
-            throw new RoutingTableException("Transaction error - while trying to remove route id="
-                    + routeId, e);
-        } catch (javax.transaction.SystemException e) {
-            throw new SystemException("System error occurred - while trying to remove with value", e);
-        }
-    }
-
-
-    @Override
-    public Set<R> getRoutes(final I routeId) {
-        Preconditions.checkNotNull(routeId, "getRoutes: routeId cannot be null!");
-        Set<R> routes = rpcCache.get(routeId);
-
-        if (routes == null) {
-            return Collections.emptySet();
-        }
-
-        return ImmutableSet.copyOf(routes);
-    }
-
-
-
-    @Override
-    public R getLastAddedRoute(final I routeId) {
-
-        Set<R> routes = getRoutes(routeId);
-
-        if (routes.isEmpty()) {
-            return null;
-        }
-
-        R route = null;
-        Iterator<R> iter = routes.iterator();
-        while (iter.hasNext()) {
-            route = iter.next();
-        }
-
-        return route;
-    }
-
-    @Override
-    public void addRoute(final I routeId, final R route)  throws RoutingTableException, SystemException {
-        Preconditions.checkNotNull(routeId, "addRoute: routeId cannot be null");
-        Preconditions.checkNotNull(route, "addRoute: route cannot be null");
-
-        try{
-            clusterGlobalServices.tbegin();
-            log.debug("addRoute: adding a route with k/v [{}/{}]", routeId, route);
-            threadSafeAdd(routeId, route);
-            clusterGlobalServices.tcommit();
-
-        } catch (NotSupportedException | HeuristicRollbackException | RollbackException | HeuristicMixedException e) {
-            throw new RoutingTableException("Transaction error - while trying to remove route id="
-                    + routeId, e);
-        } catch (javax.transaction.SystemException e) {
-            throw new SystemException("System error occurred - while trying to remove with value", e);
-        }
-    }
-
-    @Override
-    public void addRoutes(final Set<I> routeIds, final R route) throws RoutingTableException, SystemException {
-        Preconditions.checkNotNull(routeIds, "addRoutes: routeIds must not be null");
-        for (I routeId : routeIds){
-            addRoute(routeId, route);
-        }
-    }
-
-    @Override
-    public void removeRoute(final I routeId, final R route) throws RoutingTableException, SystemException {
-        Preconditions.checkNotNull(routeId, "removeRoute: routeId cannot be null!");
-        Preconditions.checkNotNull(route, "removeRoute: route cannot be null!");
-
-        LinkedHashSet<R> routes = rpcCache.get(routeId);
-        if (routes == null) {
-            return;
-        }
-
-        try {
-            log.debug("removeRoute: removing  a new route with k/v [{}/{}]", routeId, route);
-
-            clusterGlobalServices.tbegin();
-            threadSafeRemove(routeId, route);
-            clusterGlobalServices.tcommit();
-
-        } catch (NotSupportedException | HeuristicRollbackException | RollbackException | HeuristicMixedException e) {
-            throw new RoutingTableException("Transaction error - while trying to remove route id="
-                    + routeId, e);
-        } catch (javax.transaction.SystemException e) {
-            throw new SystemException("System error occurred - while trying to remove with value", e);
-        }
-    }
-
-    @Override
-    public void removeRoutes(final Set<I> routeIds, final R route) throws RoutingTableException, SystemException {
-        Preconditions.checkNotNull(routeIds, "removeRoutes: routeIds must not be null");
-        for (I routeId : routeIds){
-            removeRoute(routeId, route);
-        }
-    }
-
-    /**
-     * This method guarantees that no 2 thread over write each other's changes.
-     * Just so that we dont end up in infinite loop, it tries for 100 times then throw
-     */
-    private void threadSafeAdd(final I routeId, final R route) {
-
-        for (int i=0;i<100;i++){
-
-            LinkedHashSet<R> updatedRoutes = new LinkedHashSet<>();
-            updatedRoutes.add(route);
-            LinkedHashSet<R> oldRoutes = rpcCache.putIfAbsent(routeId, updatedRoutes);
-            if (oldRoutes == null) {
-                return;
-            }
-
-            updatedRoutes = new LinkedHashSet<>(oldRoutes);
-            updatedRoutes.add(route);
-
-            if (rpcCache.replace(routeId, oldRoutes, updatedRoutes)) {
-                return;
-            }
-        }
-        //the method did not already return means it failed to add route in 10 attempts
-        throw new IllegalStateException("Failed to add route [" + routeId + "]");
-    }
-
-    /**
-     * This method guarantees that no 2 thread over write each other's changes.
-     * Just so that we dont end up in infinite loop, it tries for 10 times then throw
-     */
-    private void threadSafeRemove(final I routeId, final R route) {
-        LinkedHashSet<R> updatedRoutes = null;
-        for (int i=0;i<10;i++){
-            LinkedHashSet<R> oldRoutes = rpcCache.get(routeId);
-
-            // if route to be deleted is the only entry in the set then remove routeId from the cache
-            if ((oldRoutes.size() == 1) && oldRoutes.contains(route)){
-                rpcCache.remove(routeId);
-                return;
-            }
-
-            // if there are multiple routes for this routeId, remove the route to be deleted only from the set.
-            updatedRoutes = new LinkedHashSet<>(oldRoutes);
-            updatedRoutes.remove(route);
-            if (rpcCache.replace(routeId, oldRoutes, updatedRoutes)) {
-                return;
-            }
-
-        }
-        //the method did not already return means it failed to remove route in 10 attempts
-        throw new IllegalStateException("Failed to remove route [" + routeId + "]");
-    }
-
-
-    //    /**
-    //     * @deprecated doesn't do anything will be removed once listeners used
-    //     *             whiteboard pattern Registers listener for sending any change
-    //     *             notification
-    //     * @param listener
-    //     */
-    //    @Override
-    //    public void registerRouteChangeListener(RouteChangeListener listener) {
-    //
-    //    }
-
-    //    public void setRouteChangeListener(RouteChangeListener rcl) {
-    //        if(rcl != null){
-    //            routeChangeListeners.add(rcl);
-    //        }else{
-    //            log.warn("setRouteChangeListener called with null listener");
-    //        }
-    //    }
-    //
-    //    public void unSetRouteChangeListener(RouteChangeListener rcl) {
-    //        if(rcl != null){
-    //         routeChangeListeners.remove(rcl);
-    //        }else{
-    //            log.warn("unSetRouteChangeListener called with null listener");
-    //        }
-    //    }
-
-    /**
-     * Returning the set of route change listeners for Unit testing Note: the
-     * package scope is default
-     *
-     * @return List of registered RouteChangeListener<I,R> listeners
-     */
-    //    Set<RouteChangeListener> getRegisteredRouteChangeListeners() {
-    //        return routeChangeListeners;
-    //    }
-    public void setClusterGlobalServices(final IClusterGlobalServices clusterGlobalServices) {
-        this.clusterGlobalServices = clusterGlobalServices;
-    }
-
-    public void unsetClusterGlobalServices(final IClusterGlobalServices clusterGlobalServices) {
-        if ((clusterGlobalServices != null) && (this.clusterGlobalServices.equals(clusterGlobalServices))) {
-            this.clusterGlobalServices = null;
-        }
-    }
-
-    /**
-     * Finds OR Creates clustered cache for Global RPCs
-     *
-     * @throws CacheExistException       -- cluster global services exception when cache exist
-     * @throws CacheConfigException      -- cluster global services exception during cache config
-     * @throws CacheListenerAddException -- cluster global services exception during adding of listener
-     */
-
-    @SuppressWarnings("unchecked")
-    void findOrCreateGlobalRpcCache() throws CacheExistException, CacheConfigException,
-    CacheListenerAddException {
-        // TBD: HOW DO WE DECIDE ON PROPERTIES OF THE CACHE i.e. what duration it
-        // should be caching?
-
-        // let us check here if the cache already exists -- if so don't create
-        if (!clusterGlobalServices.existCache(GLOBALRPC_CACHE)) {
-
-            globalRpcCache = (ConcurrentMap<I,R>) clusterGlobalServices.createCache(GLOBALRPC_CACHE,
-                    EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
-            log.debug("Cache created [{}] ", GLOBALRPC_CACHE);
-
-        } else {
-            globalRpcCache = (ConcurrentMap<I,R>) clusterGlobalServices.getCache(GLOBALRPC_CACHE);
-            log.debug("Cache exists [{}] ", GLOBALRPC_CACHE);
-        }
-    }
-
-    /**
-     * Finds OR Creates clustered cache for Routed RPCs
-     *
-     * @throws CacheExistException       -- cluster global services exception when cache exist
-     * @throws CacheConfigException      -- cluster global services exception during cache config
-     * @throws CacheListenerAddException -- cluster global services exception during adding of listener
-     */
-
-    @SuppressWarnings("unchecked")
-    void findOrCreateRpcCache() throws CacheExistException, CacheConfigException,
-    CacheListenerAddException {
-        // TBD: HOW DO WE DECIDE ON PROPERTIES OF THE CACHE i.e. what duration it
-        // should be caching?
-
-        if (clusterGlobalServices.existCache(RPC_CACHE)){
-            rpcCache = (ConcurrentMap<I,LinkedHashSet<R>>) clusterGlobalServices.getCache(RPC_CACHE);
-            log.debug("Cache exists [{}] ", RPC_CACHE);
-            return;
-        }
-
-        //cache doesnt exist, create one
-        rpcCache = (ConcurrentMap<I,LinkedHashSet<R>>) clusterGlobalServices.createCache(RPC_CACHE,
-                EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL));
-        log.debug("Cache created [{}] ", RPC_CACHE);
-    }
-
-
-    /**
-     * Function called by the dependency manager when all the required
-     * dependencies are satisfied
-     */
-    void init(final Component c) {
-        try {
-
-            findOrCreateGlobalRpcCache();
-            findOrCreateRpcCache();
-
-        } catch (CacheExistException|CacheConfigException|CacheListenerAddException e) {
-            throw new IllegalStateException("could not construct routing table cache");
-        }
-    }
-
-    /**
-     * Useful for unit testing <note>It has package
-     * scope</note>
-     */
-    ConcurrentMap<I, R> getGlobalRpcCache() {
-        return this.globalRpcCache;
-    }
-
-    /**
-     * Useful for unit testing <note>It has package
-     * scope</note>
-     */
-    ConcurrentMap<I, LinkedHashSet<R>> getRpcCache() {
-        return this.rpcCache;
-    }
-
-    /**
-     * This is used from integration test NP rest API to check out the result of the
-     * cache population
-     * <Note> For testing purpose only-- use it wisely</Note>
-     *
-     * @return
-     */
-    public String dumpGlobalRpcCache() {
-        Set<Map.Entry<I, R>> cacheEntrySet = this.globalRpcCache.entrySet();
-        StringBuilder sb = new StringBuilder();
-        for (Map.Entry<I, R> entry : cacheEntrySet) {
-            sb.append("Key:").append(entry.getKey()).append("---->Value:")
-            .append((entry.getValue() != null) ? entry.getValue() : "null")
-            .append("\n");
-        }
-        return sb.toString();
-    }
-
-    public String dumpRpcCache() {
-        Set<Map.Entry<I, LinkedHashSet<R>>> cacheEntrySet = this.rpcCache.entrySet();
-        StringBuilder sb = new StringBuilder();
-        for (Map.Entry<I, LinkedHashSet<R>> entry : cacheEntrySet) {
-            sb.append("Key:").append(entry.getKey()).append("---->Value:")
-            .append((entry.getValue() != null) ? entry.getValue() : "null")
-            .append("\n");
-        }
-        return sb.toString();
-    }
-    /**
-     * Invoked when a new entry is available in the cache, the key is only
-     * provided, the value will come as an entryUpdate invocation
-     *
-     * @param key         Key for the entry just created
-     * @param cacheName   name of the cache for which update has been received
-     * @param originLocal true if the event is generated from this node
-     */
-    @Override
-    public void entryCreated(final I key, final String cacheName, final boolean originLocal) {
-        // TBD: do we require this.
-        if (log.isDebugEnabled()) {
-            log.debug("RoutingTableUpdates: entryCreated  routeId = " + key + " cacheName=" + cacheName);
-        }
-    }
-
-    /**
-     * Called anytime a given entry is updated
-     *
-     * @param key         Key for the entry modified
-     * @param new_value   the new value the key will have
-     * @param cacheName   name of the cache for which update has been received
-     * @param originLocal true if the event is generated from this node
-     */
-    @Override
-    public void entryUpdated(final I key, final R new_value, final String cacheName, final boolean originLocal) {
-        if (log.isDebugEnabled()) {
-            log.debug("RoutingTableUpdates: entryUpdated  routeId = " + key + ",value = " + new_value
-                    + " ,cacheName=" + cacheName + " originLocal=" + originLocal);
-        }
-        //        if (!originLocal) {
-        //            for (RouteChangeListener rcl : routeChangeListeners) {
-        //                rcl.onRouteUpdated(key, new_value);
-        //            }
-        //        }
-    }
-
-    /**
-     * Called anytime a given key is removed from the ConcurrentHashMap we are
-     * listening to.
-     *
-     * @param key         Key of the entry removed
-     * @param cacheName   name of the cache for which update has been received
-     * @param originLocal true if the event is generated from this node
-     */
-    @Override
-    public void entryDeleted(final I key, final String cacheName, final boolean originLocal) {
-        if (log.isDebugEnabled()) {
-            log.debug("RoutingTableUpdates: entryUpdated  routeId = " + key + " local = " + originLocal
-                    + " cacheName=" + cacheName + " originLocal=" + originLocal);
-        }
-        //        if (!originLocal) {
-        //            for (RouteChangeListener rcl : routeChangeListeners) {
-        //                rcl.onRouteDeleted(key);
-        //            }
-        //        }
-    }
-}
diff --git a/opendaylight/md-sal/remoterpc-routingtable/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/impl/RoutingTableImplTest.java b/opendaylight/md-sal/remoterpc-routingtable/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/impl/RoutingTableImplTest.java
deleted file mode 100644 (file)
index 1ff49c1..0000000
+++ /dev/null
@@ -1,334 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sal.connector.remoterpc.impl;
-
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.reset;
-import static org.mockito.Mockito.when;
-
-import java.net.URI;
-import java.util.EnumSet;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.TimeUnit;
-
-import junit.framework.Assert;
-
-import org.apache.felix.dm.Component;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.clustering.services.IClusterGlobalServices;
-import org.opendaylight.controller.clustering.services.IClusterServices;
-import org.opendaylight.controller.sal.connector.api.RpcRouter;
-import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
-
-public class RoutingTableImplTest {
-
-    private final URI namespace = URI.create("http://cisco.com/example");
-    private final QName QNAME = new QName(namespace, "global");
-
-    private IClusterGlobalServices clusterService;
-    private RoutingTableImpl<RpcRouter.RouteIdentifier<QName, QName, InstanceIdentifier>, String> routingTable;
-    ConcurrentMap mockGlobalRpcCache;
-    ConcurrentMap mockRpcCache;
-
-    @Before
-    public void setUp() throws Exception{
-        clusterService = mock(IClusterGlobalServices.class);
-        routingTable = new RoutingTableImpl<RpcRouter.RouteIdentifier<QName, QName, InstanceIdentifier>, String>();
-        mockGlobalRpcCache = new ConcurrentHashMap<>();
-        mockRpcCache = new ConcurrentHashMap<>();
-        createRoutingTableCache();
-    }
-
-    @After
-    public void tearDown(){
-        reset(clusterService);
-        mockGlobalRpcCache = null;
-        mockRpcCache = null;
-    }
-
-    @Test
-    public void addGlobalRoute_ValidArguments_ShouldAdd() throws Exception {
-
-        Assert.assertNotNull(mockGlobalRpcCache);
-        RpcRouter.RouteIdentifier<QName, QName, InstanceIdentifier> routeIdentifier = getRouteIdentifier();
-
-        final String expectedRoute = "172.27.12.1:5000";
-        routingTable.addGlobalRoute(routeIdentifier, expectedRoute);
-
-        ConcurrentMap latestCache = routingTable.getGlobalRpcCache();
-        Assert.assertEquals(mockGlobalRpcCache, latestCache);
-        Assert.assertEquals(expectedRoute, latestCache.get(routeIdentifier));
-    }
-
-    @Test (expected = RoutingTable.DuplicateRouteException.class)
-    public void addGlobalRoute_DuplicateRoute_ShouldThrow() throws Exception{
-
-        Assert.assertNotNull(mockGlobalRpcCache);
-
-        RpcRouter.RouteIdentifier<QName, QName, InstanceIdentifier> routeIdentifier = getRouteIdentifier();
-        routingTable.addGlobalRoute(routeIdentifier, new String());
-        routingTable.addGlobalRoute(routeIdentifier, new String());
-    }
-
-    @Test
-    public void getGlobalRoute_ExistingRouteId_ShouldReturnRoute() throws Exception {
-
-        Assert.assertNotNull(mockGlobalRpcCache);
-        RpcRouter.RouteIdentifier<QName, QName, InstanceIdentifier> routeIdentifier = getRouteIdentifier();
-        String expectedRoute = "172.27.12.1:5000";
-
-        routingTable.addGlobalRoute(routeIdentifier, expectedRoute);
-
-        String actualRoute = routingTable.getGlobalRoute(routeIdentifier);
-        Assert.assertEquals(expectedRoute, actualRoute);
-    }
-
-    @Test
-    public void getGlobalRoute_NonExistentRouteId_ShouldReturnNull() throws Exception {
-
-        Assert.assertNotNull(mockGlobalRpcCache);
-        RpcRouter.RouteIdentifier<QName, QName, InstanceIdentifier> routeIdentifier = getRouteIdentifier();
-
-        String actualRoute = routingTable.getGlobalRoute(routeIdentifier);
-        Assert.assertNull(actualRoute);
-    }
-
-    @Test
-    public void removeGlobalRoute_ExistingRouteId_ShouldRemove() throws Exception {
-
-        Assert.assertNotNull(mockGlobalRpcCache);
-        RpcRouter.RouteIdentifier<QName, QName, InstanceIdentifier> routeIdentifier = getRouteIdentifier();
-
-        ConcurrentMap cache = routingTable.getGlobalRpcCache();
-        Assert.assertTrue(cache.size() == 0);
-        routingTable.addGlobalRoute(routeIdentifier, "172.27.12.1:5000");
-        Assert.assertTrue(cache.size() == 1);
-
-        routingTable.removeGlobalRoute(routeIdentifier);
-        Assert.assertTrue(cache.size() == 0);
-
-    }
-
-    @Test
-    public void removeGlobalRoute_NonExistentRouteId_ShouldDoNothing() throws Exception {
-
-        Assert.assertNotNull(mockGlobalRpcCache);
-        RpcRouter.RouteIdentifier<QName, QName, InstanceIdentifier> routeIdentifier = getRouteIdentifier();
-
-        ConcurrentMap cache = routingTable.getGlobalRpcCache();
-        Assert.assertTrue(cache.size() == 0);
-
-        routingTable.removeGlobalRoute(routeIdentifier);
-        Assert.assertTrue(cache.size() == 0);
-
-    }
-
-    @Test
-    public void addRoute_ForNewRouteId_ShouldAddRoute() throws Exception {
-        Assert.assertTrue(mockRpcCache.size() == 0);
-
-        RpcRouter.RouteIdentifier<QName, QName, InstanceIdentifier> routeId = getRouteIdentifier();
-
-        routingTable.addRoute(routeId, new String());
-        Assert.assertTrue(mockRpcCache.size() == 1);
-
-        Set<String> routes = routingTable.getRoutes(routeId);
-        Assert.assertEquals(1, routes.size());
-    }
-
-    @Test
-    public void addRoute_ForExistingRouteId_ShouldAppendRoute() throws Exception {
-
-        Assert.assertTrue(mockRpcCache.size() == 0);
-
-        RpcRouter.RouteIdentifier<QName, QName, InstanceIdentifier> routeId = getRouteIdentifier();
-
-        String route_1 = "10.0.0.1:5955";
-        String route_2 = "10.0.0.2:5955";
-
-        routingTable.addRoute(routeId, route_1);
-        routingTable.addRoute(routeId, route_2);
-
-        Assert.assertTrue(mockRpcCache.size() == 1);
-
-        Set<String> routes = routingTable.getRoutes(routeId);
-        Assert.assertEquals(2, routes.size());
-        Assert.assertTrue(routes.contains(route_1));
-        Assert.assertTrue(routes.contains(route_2));
-    }
-
-    @Test
-    public void addRoute_UsingMultipleThreads_ShouldNotOverwrite(){
-        ExecutorService threadPool = Executors.newCachedThreadPool();
-
-        int numOfRoutesToAdd = 100;
-        String routePrefix_1   = "10.0.0.1:555";
-        RpcRouter.RouteIdentifier routeId = getRouteIdentifier();
-        threadPool.submit(addRoutes(numOfRoutesToAdd, routePrefix_1, routeId));
-        String routePrefix_2   = "10.0.0.1:556";
-        threadPool.submit(addRoutes(numOfRoutesToAdd, routePrefix_2, routeId));
-
-        // wait for all tasks to complete; timeout in 10 sec
-        threadPool.shutdown();
-        try {
-            threadPool.awaitTermination(10, TimeUnit.SECONDS); //
-        } catch (InterruptedException e) {
-            e.printStackTrace();
-        }
-
-        Assert.assertEquals(2*numOfRoutesToAdd, routingTable.getRoutes(routeId).size());
-    }
-
-    @Test(expected = NullPointerException.class)
-    public void addRoute_NullRouteId_shouldThrowNpe() throws Exception {
-
-        routingTable.addRoute(null, new String());
-    }
-
-    @Test(expected = NullPointerException.class)
-    public void addRoute_NullRoute_shouldThrowNpe() throws Exception{
-
-        routingTable.addRoute(getRouteIdentifier(), null);
-    }
-
-    @Test (expected = UnsupportedOperationException.class)
-    public void getRoutes_Call_ShouldReturnImmutableCopy() throws Exception{
-        Assert.assertNotNull(routingTable);
-        RpcRouter.RouteIdentifier routeId = getRouteIdentifier();
-        routingTable.addRoute(routeId, new String());
-
-        Set<String> routes = routingTable.getRoutes(routeId); //returns Immutable Set
-
-        routes.add(new String()); //can not be modified; should throw
-    }
-
-    @Test
-    public void getRoutes_With2RoutesFor1RouteId_ShouldReturnASetWithSize2() throws Exception{
-        Assert.assertNotNull(routingTable);
-        RpcRouter.RouteIdentifier routeId = getRouteIdentifier();
-        routingTable.addRoute(routeId, "10.0.0.1:5555");
-        routingTable.addRoute(routeId, "10.0.0.2:5555");
-
-        Set<String> routes = routingTable.getRoutes(routeId); //returns Immutable Set
-
-        Assert.assertEquals(2, routes.size());
-    }
-
-    @Test
-    public void getLastAddedRoute_WhenMultipleRoutesExists_ShouldReturnLatestRoute()
-            throws Exception {
-
-        Assert.assertNotNull(routingTable);
-        RpcRouter.RouteIdentifier routeId = getRouteIdentifier();
-        String route_1 = "10.0.0.1:5555";
-        String route_2 = "10.0.0.2:5555";
-        routingTable.addRoute(routeId, route_1);
-        routingTable.addRoute(routeId, route_2);
-
-        Assert.assertEquals(route_2, routingTable.getLastAddedRoute(routeId));
-    }
-
-    @Test
-    public void removeRoute_WhenMultipleRoutesExist_RemovesGivenRoute() throws Exception{
-        Assert.assertNotNull(routingTable);
-        RpcRouter.RouteIdentifier routeId = getRouteIdentifier();
-        String route_1 = "10.0.0.1:5555";
-        String route_2 = "10.0.0.2:5555";
-
-        routingTable.addRoute(routeId, route_1);
-        routingTable.addRoute(routeId, route_2);
-
-        Assert.assertEquals(2, routingTable.getRoutes(routeId).size());
-
-        routingTable.removeRoute(routeId, route_1);
-        Assert.assertEquals(1, routingTable.getRoutes(routeId).size());
-
-    }
-
-    @Test
-    public void removeRoute_WhenOnlyOneRouteExists_RemovesRouteId() throws Exception{
-        Assert.assertNotNull(routingTable);
-        RpcRouter.RouteIdentifier routeId = getRouteIdentifier();
-        String route_1 = "10.0.0.1:5555";
-
-        routingTable.addRoute(routeId, route_1);
-        Assert.assertEquals(1, routingTable.getRoutes(routeId).size());
-
-        routingTable.removeRoute(routeId, route_1);
-        ConcurrentMap cache = routingTable.getRpcCache();
-        Assert.assertFalse(cache.containsKey(routeId));
-
-    }
-
-    /*
-     * Private helper methods
-     */
-    private void createRoutingTableCache() throws Exception {
-
-        //here init
-        Component c = mock(Component.class);
-
-        when(clusterService.existCache(
-                RoutingTableImpl.GLOBALRPC_CACHE)).thenReturn(false);
-
-        when(clusterService.createCache(RoutingTableImpl.GLOBALRPC_CACHE,
-                EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL))).
-                thenReturn(mockGlobalRpcCache);
-
-        when(clusterService.existCache(
-                RoutingTableImpl.RPC_CACHE)).thenReturn(false);
-
-        when(clusterService.createCache(RoutingTableImpl.RPC_CACHE,
-                EnumSet.of(IClusterServices.cacheMode.TRANSACTIONAL))).
-                thenReturn(mockRpcCache);
-
-        doNothing().when(clusterService).tbegin();
-        doNothing().when(clusterService).tcommit();
-
-        routingTable.setClusterGlobalServices(this.clusterService);
-        routingTable.init(c);
-
-        Assert.assertEquals(mockGlobalRpcCache, routingTable.getGlobalRpcCache());
-        Assert.assertEquals(mockRpcCache, routingTable.getRpcCache());
-    }
-
-    private RpcRouter.RouteIdentifier<QName, QName, InstanceIdentifier> getRouteIdentifier(){
-        RpcRouter.RouteIdentifier<QName, QName, InstanceIdentifier> routeIdentifier = mock(RpcRouter.RouteIdentifier.class);
-        InstanceIdentifier identifier = mock(InstanceIdentifier.class);
-        when(routeIdentifier.getType()).thenReturn(QNAME);
-        when(routeIdentifier.getRoute()).thenReturn(identifier);
-
-        return routeIdentifier;
-    }
-
-    private Runnable addRoutes(final int numRoutes, final String routePrefix, final RpcRouter.RouteIdentifier routeId){
-        return new Runnable() {
-            @Override
-            public void run() {
-                for (int i=0;i<numRoutes;i++){
-                    String route = routePrefix + i;
-                    try {
-                        routingTable.addRoute(routeId, route);
-                    } catch (Exception e) {
-                        e.printStackTrace();
-                    }
-                }
-            }
-        };
-    }
-}
diff --git a/opendaylight/md-sal/remoterpc-routingtable/integrationtest/pom.xml b/opendaylight/md-sal/remoterpc-routingtable/integrationtest/pom.xml
deleted file mode 100644 (file)
index ce11be1..0000000
+++ /dev/null
@@ -1,230 +0,0 @@
-<?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.integrationtest</artifactId>
-    <version>0.5.1-SNAPSHOT</version>
-    <relativePath>../../../commons/integrationtest</relativePath>
-  </parent>
-  <scm>
-    <connection>scm:git:ssh://git.opendaylight.org:29418/controller.git</connection>
-    <developerConnection>scm:git:ssh://git.opendaylight.org:29418/controller.git</developerConnection>
-    <url>https://wiki.opendaylight.org/view/OpenDaylight_Controller:Main</url>
-    <tag>HEAD</tag>
-  </scm>
-
-  <artifactId>remoterpc-routingtable.integrationtest</artifactId>
-  <version>0.4.1-SNAPSHOT</version>
-
-  <dependencies>
-    <dependency>
-        <groupId>org.opendaylight.controller</groupId>
-        <artifactId>remoterpc-routingtable.implementation</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>clustering.services</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>sal</artifactId>
-    </dependency>
-      <dependency>
-          <groupId>org.opendaylight.controller</groupId>
-          <artifactId>sal.implementation</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>org.opendaylight.controller</groupId>
-          <artifactId>containermanager</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>org.opendaylight.controller</groupId>
-          <artifactId>containermanager.it.implementation</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>org.opendaylight.controller</groupId>
-          <artifactId>clustering.stub</artifactId>
-      </dependency>
-        <dependency>
-      <groupId>junit</groupId>
-      <artifactId>junit</artifactId>
-    </dependency>
-    <dependency>
-       <groupId>org.ops4j.pax.exam</groupId>
-       <artifactId>pax-exam-container-native</artifactId>
-       <scope>test</scope>
-     </dependency>
-     <dependency>
-        <groupId>org.ops4j.pax.exam</groupId>
-        <artifactId>pax-exam-link-mvn</artifactId>
-        <scope>test</scope>
-      </dependency>
-      <dependency>
-        <groupId>org.ops4j.pax.url</groupId>
-        <artifactId>pax-url-aether</artifactId>
-        <scope>test</scope>
-      </dependency>
-      <dependency>
-        <groupId>org.slf4j</groupId>
-        <artifactId>log4j-over-slf4j</artifactId>
-      </dependency>
-      <dependency>
-        <groupId>ch.qos.logback</groupId>
-        <artifactId>logback-core</artifactId>
-      </dependency>
-      <dependency>
-        <groupId>ch.qos.logback</groupId>
-        <artifactId>logback-classic</artifactId>
-      </dependency>
-      <dependency>
-        <groupId>org.apache.felix</groupId>
-        <artifactId>org.apache.felix.dependencymanager.shell</artifactId>
-      </dependency>
-      <dependency>
-        <groupId>eclipselink</groupId>
-        <artifactId>javax.resource</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>com.google.guava</groupId>
-          <artifactId>guava</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>org.opendaylight.controller</groupId>
-          <artifactId>sal</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>org.opendaylight.yangtools</groupId>
-          <artifactId>yang-binding</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>org.opendaylight.yangtools</groupId>
-          <artifactId>yang-common</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>org.opendaylight.controller</groupId>
-          <artifactId>sal-connector-api</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>org.opendaylight.controller</groupId>
-          <artifactId>sal-common-util</artifactId>
-      </dependency>
-
-      <dependency>
-          <groupId>junit</groupId>
-          <artifactId>junit</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>org.opendaylight.controller</groupId>
-          <artifactId>sal-common-api</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>org.opendaylight.controller</groupId>
-          <artifactId>sal-binding-broker-impl</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>org.ops4j.pax.exam</groupId>
-          <artifactId>pax-exam-container-native</artifactId>
-          <version>${exam.version}</version>
-          <scope>test</scope>
-      </dependency>
-      <dependency>
-          <groupId>org.ops4j.pax.exam</groupId>
-          <artifactId>pax-exam-junit4</artifactId>
-          <version>${exam.version}</version>
-          <scope>test</scope>
-      </dependency>
-      <dependency>
-          <groupId>org.ops4j.pax.exam</groupId>
-          <artifactId>pax-exam-link-mvn</artifactId>
-          <version>${exam.version}</version>
-          <scope>test</scope>
-      </dependency>
-
-      <dependency>
-          <groupId>org.opendaylight.controller</groupId>
-          <artifactId>config-manager</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>equinoxSDK381</groupId>
-          <artifactId>org.eclipse.osgi</artifactId>
-          <scope>test</scope>
-      </dependency>
-      <dependency>
-          <groupId>org.slf4j</groupId>
-          <artifactId>log4j-over-slf4j</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>ch.qos.logback</groupId>
-          <artifactId>logback-core</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>ch.qos.logback</groupId>
-          <artifactId>logback-classic</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>org.opendaylight.yangtools.thirdparty</groupId>
-          <artifactId>antlr4-runtime-osgi-nohead</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>org.opendaylight.yangtools.thirdparty</groupId>
-          <artifactId>xtend-lib-osgi</artifactId>
-      </dependency>
-
-      <dependency>
-          <groupId>org.opendaylight.controller</groupId>
-          <artifactId>clustering.services</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>junit</groupId>
-          <artifactId>junit</artifactId>
-          <scope>test</scope>
-      </dependency>
-
-      <dependency>
-          <groupId>equinoxSDK381</groupId>
-          <artifactId>org.eclipse.osgi</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>org.ops4j.pax.exam</groupId>
-          <artifactId>pax-exam-junit4</artifactId>
-          <version>${exam.version}</version>
-      </dependency>
-      <dependency>
-          <groupId>org.ops4j.pax.exam</groupId>
-          <artifactId>pax-exam</artifactId>
-          <version>${exam.version}</version>
-      </dependency>
-  </dependencies>
-  <properties>
-    <!-- Sonar jacoco plugin to get integration test coverage info -->
-    <sonar.jacoco.reportPath>../implementation/target/jacoco.exec</sonar.jacoco.reportPath>
-    <sonar.jacoco.itReportPath>../implementation/target/jacoco-it.exec</sonar.jacoco.itReportPath>
-  </properties>
-  <build>
-    <plugins>
-      <plugin>
-        <groupId>org.jacoco</groupId>
-        <artifactId>jacoco-maven-plugin</artifactId>
-        <configuration>
-          <destFile>../implementation/target/jacoco-it.exec</destFile>
-          <includes><include>org.opendaylight.controller.*</include></includes>
-        </configuration>
-        <executions>
-          <execution>
-            <id>pre-test</id>
-            <goals>
-              <goal>prepare-agent</goal>
-            </goals>
-          </execution>
-          <execution>
-            <id>post-test</id>
-            <configuration>
-              <skip>true</skip>
-            </configuration>
-          </execution>
-        </executions>
-      </plugin>
-    </plugins>
-  </build>
-</project>
diff --git a/opendaylight/md-sal/remoterpc-routingtable/integrationtest/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/impl/ZeroMQRoutingTableTestIT.java b/opendaylight/md-sal/remoterpc-routingtable/integrationtest/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/impl/ZeroMQRoutingTableTestIT.java
deleted file mode 100644 (file)
index 9249212..0000000
+++ /dev/null
@@ -1,330 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.connector.remoterpc.impl;
-
-import junit.framework.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.opendaylight.controller.sal.connector.api.RpcRouter;
-import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
-import org.ops4j.pax.exam.Configuration;
-import org.ops4j.pax.exam.Option;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.ops4j.pax.exam.util.PathUtils;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.inject.Inject;
-import java.io.Serializable;
-import java.net.URI;
-import java.util.Set;
-
-import static org.ops4j.pax.exam.CoreOptions.junitBundles;
-import static org.ops4j.pax.exam.CoreOptions.mavenBundle;
-import static org.ops4j.pax.exam.CoreOptions.options;
-import static org.ops4j.pax.exam.CoreOptions.systemPackages;
-import static org.ops4j.pax.exam.CoreOptions.systemProperty;
-
-
-
-
-@RunWith(PaxExam.class)
-public class
-        ZeroMQRoutingTableTestIT {
-    private Logger log = LoggerFactory
-            .getLogger(ZeroMQRoutingTableTestIT.class);
-
-    public static final String ODL = "org.opendaylight.controller";
-    public static final String YANG = "org.opendaylight.yangtools";
-    public static final String CONTROLLER = "org.opendaylight.controller";
-    public static final String YANGTOOLS = "org.opendaylight.yangtools";
-    RoutingIdentifierImpl rii  = new RoutingIdentifierImpl();
-    // get the OSGI bundle context
-    @Inject
-    private BundleContext bc;
-    @Inject
-    private RoutingTable routingTable = null;
-
-    // Configure the OSGi container
-    @Configuration
-    public Option[] config() {
-        return options(
-                //
-                systemProperty("logback.configurationFile").value(
-                        "file:" + PathUtils.getBaseDir()
-                                + "/src/test/resources/logback.xml"),
-                // To start OSGi console for inspection remotely
-                systemProperty("osgi.console").value("2401"),
-                // Set the systemPackages (used by clustering)
-                systemPackages("sun.reflect", "sun.reflect.misc", "sun.misc"),
-                // List framework bundles
-
-                mavenBundle("equinoxSDK381",
-                        "org.eclipse.equinox.console").versionAsInProject(),
-                mavenBundle("equinoxSDK381",
-                        "org.eclipse.equinox.util").versionAsInProject(),
-                mavenBundle("equinoxSDK381",
-                        "org.eclipse.osgi.services").versionAsInProject(),
-                mavenBundle("equinoxSDK381",
-                        "org.eclipse.equinox.ds").versionAsInProject(),
-                mavenBundle("equinoxSDK381",
-                        "org.apache.felix.gogo.command").versionAsInProject(),
-                mavenBundle("equinoxSDK381",
-                        "org.apache.felix.gogo.runtime").versionAsInProject(),
-                mavenBundle("equinoxSDK381",
-                        "org.apache.felix.gogo.shell").versionAsInProject(),
-                // List logger bundles
-                mavenBundle("org.slf4j", "slf4j-api").versionAsInProject(),
-                mavenBundle("org.slf4j", "log4j-over-slf4j").versionAsInProject(),
-                mavenBundle("ch.qos.logback", "logback-core").versionAsInProject(),
-                mavenBundle("ch.qos.logback", "logback-classic").versionAsInProject(),
-                // List all the bundles on which the test case depends
-                mavenBundle(ODL,
-                        "clustering.services").versionAsInProject(),
-
-                mavenBundle(ODL, "sal").versionAsInProject(),
-                mavenBundle(ODL,
-                        "sal.implementation").versionAsInProject(),
-                mavenBundle(ODL, "containermanager").versionAsInProject(),
-                mavenBundle(ODL,
-                        "containermanager.it.implementation").versionAsInProject(),
-                mavenBundle("org.jboss.spec.javax.transaction",
-                        "jboss-transaction-api_1.1_spec").versionAsInProject(),
-                mavenBundle("org.apache.commons", "commons-lang3").versionAsInProject(),
-                mavenBundle("org.apache.felix",
-                        "org.apache.felix.dependencymanager").versionAsInProject(),
-                mavenBundle("org.apache.felix",
-                        "org.apache.felix.dependencymanager.shell").versionAsInProject(),
-                mavenBundle("eclipselink", "javax.resource").versionAsInProject(),
-
-                mavenBundle("com.google.guava","guava").versionAsInProject(),
-                // List logger bundles
-                mavenBundle("org.slf4j", "slf4j-api").versionAsInProject(),
-                mavenBundle("org.slf4j", "log4j-over-slf4j")
-                        .versionAsInProject(),
-                mavenBundle("ch.qos.logback", "logback-core")
-                        .versionAsInProject(),
-                mavenBundle("ch.qos.logback", "logback-classic")
-                        .versionAsInProject(),
-
-                mavenBundle(ODL, "clustering.services")
-                        .versionAsInProject(),
-                mavenBundle(ODL, "clustering.stub")
-                        .versionAsInProject(),
-
-
-                // List all the bundles on which the test case depends
-                mavenBundle(ODL, "sal")
-                        .versionAsInProject(),
-                mavenBundle(ODL, "sal-connector-api")
-                        .versionAsInProject(),
-                mavenBundle(ODL, "remoterpc-routingtable.implementation")
-                        .versionAsInProject(),
-
-                mavenBundle("org.jboss.spec.javax.transaction",
-                        "jboss-transaction-api_1.1_spec").versionAsInProject(),
-                mavenBundle("org.apache.commons", "commons-lang3")
-                        .versionAsInProject(),
-                mavenBundle("org.apache.felix",
-                        "org.apache.felix.dependencymanager")
-                        .versionAsInProject(),
-
-                mavenBundle(ODL,
-                        "sal-core-api")
-                        .versionAsInProject(),
-                mavenBundle("org.opendaylight.yangtools","yang-data-api")
-                        .versionAsInProject(),
-                mavenBundle("org.opendaylight.yangtools","yang-model-api")
-                        .versionAsInProject(),
-                mavenBundle("org.opendaylight.yangtools","yang-binding")
-                        .versionAsInProject(),
-
-                mavenBundle(CONTROLLER, "sal-binding-api").versionAsInProject(), //
-                mavenBundle(CONTROLLER, "sal-binding-config").versionAsInProject(),
-                mavenBundle(CONTROLLER, "sal-binding-broker-impl").versionAsInProject(), //
-                mavenBundle("org.javassist", "javassist").versionAsInProject(), //
-                mavenBundle(CONTROLLER, "sal-common-util").versionAsInProject(), //
-
-                mavenBundle(YANGTOOLS, "yang-data-api").versionAsInProject(), //
-                mavenBundle(YANGTOOLS, "yang-data-impl").versionAsInProject(), //
-                mavenBundle(YANGTOOLS, "yang-model-api").versionAsInProject(), //
-                mavenBundle(YANGTOOLS, "yang-model-util").versionAsInProject(), //
-                mavenBundle(YANGTOOLS, "yang-parser-api").versionAsInProject(),
-                mavenBundle(YANGTOOLS, "yang-parser-impl").versionAsInProject(),
-
-
-                mavenBundle(YANGTOOLS, "binding-generator-spi").versionAsInProject(), //
-                mavenBundle(YANGTOOLS, "binding-model-api").versionAsInProject(), //
-                mavenBundle(YANGTOOLS, "binding-generator-util").versionAsInProject(),
-                mavenBundle(YANGTOOLS, "yang-parser-impl").versionAsInProject(),
-                mavenBundle(YANGTOOLS, "binding-type-provider").versionAsInProject(),
-                mavenBundle(YANGTOOLS, "binding-generator-api").versionAsInProject(),
-                mavenBundle(YANGTOOLS, "binding-generator-spi").versionAsInProject(),
-                mavenBundle(YANGTOOLS, "binding-generator-impl").versionAsInProject(),
-
-
-                mavenBundle(CONTROLLER, "sal-core-api").versionAsInProject().update(), //
-                mavenBundle(CONTROLLER, "sal-broker-impl").versionAsInProject(), //
-                mavenBundle(CONTROLLER, "sal-core-spi").versionAsInProject().update(), //
-
-                mavenBundle(YANGTOOLS + ".thirdparty", "antlr4-runtime-osgi-nohead").versionAsInProject(), //
-
-                mavenBundle(YANG+".thirdparty", "xtend-lib-osgi").versionAsInProject(),
-                mavenBundle("com.google.guava", "guava").versionAsInProject(), //
-                mavenBundle("org.javassist", "javassist").versionAsInProject(),
-                mavenBundle("org.slf4j", "slf4j-api").versionAsInProject(), //
-                mavenBundle("org.slf4j", "log4j-over-slf4j").versionAsInProject(), //
-                mavenBundle("ch.qos.logback", "logback-core").versionAsInProject(), //
-                mavenBundle("ch.qos.logback", "logback-classic").versionAsInProject(), //
-
-                mavenBundle(ODL, "sal-common").versionAsInProject(), //
-                mavenBundle(ODL, "sal-common-api").versionAsInProject(),//
-                mavenBundle(ODL, "sal-common-impl").versionAsInProject(), //
-                mavenBundle(ODL, "sal-common-util").versionAsInProject(), //
-
-                mavenBundle(ODL, "config-api").versionAsInProject(), //
-                mavenBundle(ODL, "config-manager").versionAsInProject(), //
-                mavenBundle("commons-io", "commons-io").versionAsInProject(),
-                mavenBundle("org.apache.commons", "commons-lang3").versionAsInProject(),
-
-                mavenBundle(ODL, "sal-binding-api").versionAsInProject(), //
-                mavenBundle(ODL, "sal-binding-config").versionAsInProject(),
-                mavenBundle("org.javassist", "javassist").versionAsInProject(), //
-                mavenBundle(ODL, "sal-common-util").versionAsInProject(), //
-
-                mavenBundle(YANG, "yang-data-api").versionAsInProject(), //
-                mavenBundle(YANG, "yang-data-impl").versionAsInProject(), //
-                mavenBundle(YANG, "yang-model-api").versionAsInProject(), //
-                mavenBundle(YANG, "yang-model-util").versionAsInProject(), //
-                mavenBundle(YANG, "yang-parser-api").versionAsInProject(),
-                mavenBundle(YANG, "yang-parser-impl").versionAsInProject(),
-
-
-                mavenBundle(YANG, "binding-generator-spi").versionAsInProject(), //
-                mavenBundle(YANG, "binding-model-api").versionAsInProject(), //
-                mavenBundle(YANG, "binding-generator-util").versionAsInProject(),
-                mavenBundle(YANG, "yang-parser-impl").versionAsInProject(),
-                mavenBundle(YANG, "binding-type-provider").versionAsInProject(),
-                mavenBundle(YANG, "binding-generator-api").versionAsInProject(),
-                mavenBundle(YANG, "binding-generator-spi").versionAsInProject(),
-                mavenBundle(YANG, "binding-generator-impl").versionAsInProject(),
-
-
-                mavenBundle(ODL, "sal-core-api").versionAsInProject().update(), //
-                mavenBundle(ODL, "sal-broker-impl").versionAsInProject(), //
-                mavenBundle(ODL, "sal-core-spi").versionAsInProject().update(), //
-
-                mavenBundle(YANG + ".thirdparty", "antlr4-runtime-osgi-nohead").versionAsInProject(), //
-
-                mavenBundle(YANG, "concepts").versionAsInProject(),
-                mavenBundle(YANG, "yang-binding").versionAsInProject(), //
-                mavenBundle(YANG, "yang-common").versionAsInProject(), //
-                mavenBundle(YANG+".thirdparty", "xtend-lib-osgi").versionAsInProject(),
-                mavenBundle("com.google.guava", "guava").versionAsInProject(), //
-                mavenBundle("org.javassist", "javassist").versionAsInProject(),
-
-                junitBundles());
-    }
-
-    private String stateToString(int state) {
-        switch (state) {
-            case Bundle.ACTIVE:
-                return "ACTIVE";
-            case Bundle.INSTALLED:
-                return "INSTALLED";
-            case Bundle.RESOLVED:
-                return "RESOLVED";
-            case Bundle.UNINSTALLED:
-                return "UNINSTALLED";
-            default:
-                return "Not CONVERTED";
-        }
-    }
-
-    @Test
-  public  void testAddGlobalRoute () throws Exception{
-
-       routingTable.addGlobalRoute(rii,"172.27.12.1:5000");
-
-       Set<String> routes = routingTable.getRoutes(rii);
-
-       for(String route:routes){
-           Assert.assertEquals(route,"172.27.12.1:5000");
-       }
-
-
-    }
-
-
-    @Test
-    public  void testDeleteGlobalRoute () throws Exception{
-
-        routingTable.removeGlobalRoute(rii);
-
-        Set<String> routes = routingTable.getRoutes(rii);
-
-        Assert.assertNull(routes);
-
-
-    }
-
-
-
-   class RoutingIdentifierImpl implements RpcRouter.RouteIdentifier,Serializable {
-
-       private final URI namespace = URI.create("http://cisco.com/example");
-       private final QName QNAME = new QName(namespace,"global");
-       private final QName instance = new QName(URI.create("127.0.0.1"),"local");
-
-       @Override
-       public QName getContext() {
-           return QNAME;
-       }
-
-       @Override
-       public QName getType() {
-           return QNAME;
-       }
-
-       @Override
-       public org.opendaylight.yangtools.yang.data.api.InstanceIdentifier getRoute() {
-           return InstanceIdentifier.of(instance);
-       }
-
-       @Override
-       public boolean equals(Object o) {
-           if (this == o) return true;
-           if (o == null || getClass() != o.getClass()) return false;
-
-           RoutingIdentifierImpl that = (RoutingIdentifierImpl) o;
-
-           if (QNAME != null ? !QNAME.equals(that.QNAME) : that.QNAME != null) return false;
-           if (instance != null ? !instance.equals(that.instance) : that.instance != null) return false;
-           if (namespace != null ? !namespace.equals(that.namespace) : that.namespace != null) return false;
-
-           return true;
-       }
-
-       @Override
-       public int hashCode() {
-           int result = namespace != null ? namespace.hashCode() : 0;
-           result = 31 * result + (QNAME != null ? QNAME.hashCode() : 0);
-           result = 31 * result + (instance != null ? instance.hashCode() : 0);
-           return result;
-       }
-   }
-
-
-
-
-
-}
diff --git a/opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/pom.xml b/opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/pom.xml
deleted file mode 100644 (file)
index d74e713..0000000
+++ /dev/null
@@ -1,87 +0,0 @@
-<?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>
-    <artifactId>sal-remoterpc-connector-test-parent</artifactId>
-    <groupId>org.opendaylight.controller.tests</groupId>
-    <version>1.1-SNAPSHOT</version>
-  </parent>
-
-  <artifactId>remoterpc-routingtable-nb-it</artifactId>
-  <packaging>bundle</packaging>
-
-  <build>
-    <plugins>
-      <plugin>
-        <groupId>org.apache.felix</groupId>
-        <artifactId>maven-bundle-plugin</artifactId>
-        <version>${bundle.plugin.version}</version>
-        <extensions>true</extensions>
-        <configuration>
-          <instructions>
-            <Export-Package>
-             org.opendaylight.controller.tests.zmqroutingtable.rest
-            </Export-Package>
-            <Import-Package>
-              com.sun.jersey.spi.container.servlet,
-              com.fasterxml.jackson.annotation,
-              javax.ws.rs,
-              javax.ws.rs.core,
-              javax.xml.bind,
-              javax.xml.bind.annotation,
-              org.slf4j,
-              org.apache.catalina.filters,
-              org.codehaus.jackson.jaxrs,
-              org.opendaylight.controller.sal.utils,
-              org.opendaylight.yangtools.yang.common,
-              org.opendaylight.controller.sal.connector.api,
-              org.opendaylight.controller.sal.connector.remoterpc.api,
-              org.opendaylight.controller.sal.connector.remoterpc.impl,
-              org.osgi.framework,
-              com.google.common.base,
-              org.opendaylight.yangtools.yang.data.api,
-              !org.codehaus.enunciate.jaxrs
-
-            </Import-Package>
-            <Web-ContextPath>/controller/nb/v2/zmqnbrt</Web-ContextPath>
-            <Jaxrs-Resources>,${classes;ANNOTATION;javax.ws.rs.Path}</Jaxrs-Resources>
-          </instructions>
-          <manifestLocation>${project.basedir}/src/main/resources/META-INF</manifestLocation>
-        </configuration>
-      </plugin>
-    </plugins>
-  </build>
-  <dependencies>
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>containermanager</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>commons.northbound</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>sal</artifactId>
-    </dependency>
-
-    <dependency>
-      <groupId>org.osgi</groupId>
-      <artifactId>org.osgi.core</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>junit</groupId>
-      <artifactId>junit</artifactId>
-    </dependency>
-      <dependency>
-          <groupId>org.opendaylight.controller</groupId>
-          <artifactId>remoterpc-routingtable.implementation</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>com.google.guava</groupId>
-          <artifactId>guava</artifactId>
-      </dependency>
-  </dependencies>
-
- </project>
diff --git a/opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/src/main/java/org/opendaylight/controller/tests/zmqroutingtable/rest/RouteIdentifierImpl.java b/opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/src/main/java/org/opendaylight/controller/tests/zmqroutingtable/rest/RouteIdentifierImpl.java
deleted file mode 100644 (file)
index eb5ecd7..0000000
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.tests.zmqroutingtable.rest;
-
-import org.opendaylight.controller.sal.connector.api.RpcRouter;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
-
-import java.io.Serializable;
-import java.net.URI;
-
-/**
- * @author: syedbahm
- * Date: 12/10/13
- */
-public class RouteIdentifierImpl implements RpcRouter.RouteIdentifier, Serializable {
-
-    private final URI namespace;
-    private final QName QNAME;
-    private final QName instance;
-
-    public RouteIdentifierImpl() {
-        namespace = URI.create("http://cisco.com/example");
-        QNAME = new QName(namespace, "global");
-        instance = new QName(URI.create("127.0.0.1"), "local");
-    }
-
-    public RouteIdentifierImpl(String url,String instanceIP){
-        namespace = URI.create(url);
-        QNAME = new QName(namespace,"global");
-        instance =  new QName(URI.create(instanceIP), "local");
-    }
-
-
-    @Override
-    public QName getContext() {
-        return QNAME;
-    }
-
-    @Override
-    public QName getType() {
-        return QNAME;
-    }
-
-    @Override
-    public org.opendaylight.yangtools.yang.data.api.InstanceIdentifier getRoute() {
-        return InstanceIdentifier.of(instance);
-    }
-
-    @Override
-    public boolean equals(Object o) {
-        if (this == o) return true;
-        if (o == null || getClass() != o.getClass()) return false;
-
-        RouteIdentifierImpl that = (RouteIdentifierImpl) o;
-
-        if (!QNAME.equals(that.QNAME)) return false;
-        if (!instance.equals(that.instance)) return false;
-        if (!namespace.equals(that.namespace)) return false;
-
-        return true;
-    }
-
-    @Override
-    public int hashCode() {
-        int result = namespace.hashCode();
-        result = 31 * result + QNAME.hashCode();
-        result = 31 * result + instance.hashCode();
-        return result;
-    }
-}
diff --git a/opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/src/main/java/org/opendaylight/controller/tests/zmqroutingtable/rest/Router.java b/opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/src/main/java/org/opendaylight/controller/tests/zmqroutingtable/rest/Router.java
deleted file mode 100644 (file)
index 9bf6e53..0000000
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.tests.zmqroutingtable.rest;
-
-import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable;
-import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTableException;
-import org.opendaylight.controller.sal.connector.remoterpc.api.SystemException;
-import org.opendaylight.controller.sal.connector.remoterpc.impl.RoutingTableImpl;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.BundleReference;
-import org.osgi.framework.FrameworkUtil;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.MediaType;
-import java.io.Serializable;
-import java.net.URI;
-
-@Path("router")
-public class Router implements Serializable {
-  private Logger _logger = LoggerFactory.getLogger(Router.class);
-  private final URI namespace = URI.create("http://cisco.com/example");
-  private final QName QNAME = new QName(namespace, "heartbeat");
-
-
-  @GET
-  @Path("/hello")
-  @Produces(MediaType.TEXT_PLAIN)
-  public String hello() {
-    return "Hello";
-  }
-
-
-
-
-    @GET
-    @Path("/rtadd")
-    @Produces(MediaType.TEXT_PLAIN)
-    public String addToRoutingTable(@QueryParam("nsp") String namespace,@QueryParam("inst") String instance,@QueryParam("port") String port) {
-        _logger.info("Invoking adding an entry in routing table");
-
-        BundleContext ctx = getBundleContext();
-        ServiceReference routingTableServiceReference = ctx.getServiceReference(RoutingTable.class);
-        if (routingTableServiceReference == null) {
-            _logger.debug("Could not get routing table impl reference");
-            return "Could not get routingtable referen ";
-        }
-        RoutingTableImpl routingTable = (RoutingTableImpl) ctx.getService(routingTableServiceReference);
-        if (routingTable == null) {
-            _logger.info("Could not get routing table service");
-            return "Could not get routing table service";
-        }
-
-
-        RouteIdentifierImpl rii = new RouteIdentifierImpl(namespace,instance);
-        try {
-            routingTable.addGlobalRoute(rii, instance+":"+ port);
-        } catch (RoutingTableException e) {
-            _logger.error("error in adding routing identifier" + e.getMessage());
-
-        } catch (SystemException e) {
-            _logger.error("error in adding routing identifier" + e.getMessage());
-        }
-
-        StringBuilder stringBuilder = new StringBuilder();
-        stringBuilder.append("Result of adding route:").append("\n")
-                     .append(routingTable.dumpRoutingTableCache());
-        return stringBuilder.toString();
-    }
-
-  @GET
-  @Path("/rtdelete")
-  @Produces(MediaType.TEXT_PLAIN)
-  public String invokeDeleteRoutingTable(@QueryParam("nsp") String namespace,@QueryParam("inst") String instance) {
-    _logger.info("Invoking delete an entry in routing table");
-
-    BundleContext ctx = getBundleContext();
-    ServiceReference routingTableServiceReference = ctx.getServiceReference(RoutingTable.class);
-    if (routingTableServiceReference == null) {
-      _logger.debug("Could not get routing table impl reference");
-      return "Could not get routingtable referen ";
-    }
-    RoutingTableImpl routingTable = (RoutingTableImpl) ctx.getService(routingTableServiceReference);
-    if (routingTable == null) {
-      _logger.info("Could not get routing table service");
-      return "Could not get routing table service";
-    }
-
-
-    RouteIdentifierImpl rii = new RouteIdentifierImpl(namespace,instance);
-    try {
-      routingTable.removeGlobalRoute(rii);
-    } catch (RoutingTableException e) {
-      _logger.error("error in adding routing identifier" + e.getMessage());
-
-    } catch (SystemException e) {
-      _logger.error("error in adding routing identifier" + e.getMessage());
-    }
-
-
-    StringBuilder stringBuilder = new StringBuilder();
-    stringBuilder.append("Result of deleting route:").append("\n")
-              .append(routingTable.dumpRoutingTableCache());
-
-    return stringBuilder.toString();
-  }
-
-    @GET
-    @Path("/routingtable")
-    @Produces(MediaType.TEXT_PLAIN)
-    public String invokeGetRoutingTable() {
-        _logger.info("Invoking getting of routing table");
-
-        BundleContext ctx = getBundleContext();
-        ServiceReference routingTableServiceReference = ctx.getServiceReference(RoutingTable.class);
-        if (routingTableServiceReference == null) {
-            _logger.debug("Could not get routing table impl reference");
-            return "Could not get routingtable referen ";
-        }
-        RoutingTableImpl routingTable = (RoutingTableImpl) ctx.getService(routingTableServiceReference);
-        if (routingTable == null) {
-            _logger.info("Could not get routing table service");
-            return "Could not get routing table service";
-        }
-
-
-        StringBuilder stringBuilder = new StringBuilder();
-        stringBuilder.append("Result of getting routetable:").append("\n")
-                .append(routingTable.dumpRoutingTableCache());
-
-        return stringBuilder.toString();
-    }
-
-
-
-  private BundleContext getBundleContext() {
-    ClassLoader tlcl = Thread.currentThread().getContextClassLoader();
-    Bundle bundle = null;
-
-    if (tlcl instanceof BundleReference) {
-      bundle = ((BundleReference) tlcl).getBundle();
-    } else {
-      _logger.info("Unable to determine the bundle context based on " +
-          "thread context classloader.");
-      bundle = FrameworkUtil.getBundle(this.getClass());
-    }
-    return (bundle == null ? null : bundle.getBundleContext());
-  }
-
-
-
-}
diff --git a/opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/src/main/resources/WEB-INF/web.xml b/opendaylight/md-sal/remoterpc-routingtable/integrationtest/test-nb/src/main/resources/WEB-INF/web.xml
deleted file mode 100644 (file)
index 2a0f3f3..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
-        version="3.0">
-  <servlet>
-    <servlet-name>JAXRSZmqRT</servlet-name>
-    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
-    <init-param>
-      <param-name>javax.ws.rs.Application</param-name>
-      <param-value>org.opendaylight.controller.northbound.commons.NorthboundApplication</param-value>
-    </init-param>
-    <load-on-startup>1</load-on-startup>
-  </servlet>
-
-  <servlet-mapping>
-    <servlet-name>JAXRSZmqRT</servlet-name>
-    <url-pattern>/*</url-pattern>
-  </servlet-mapping>
-
-
-
-        <security-constraint>
-          <web-resource-collection>
-            <web-resource-name>NB api</web-resource-name>
-            <url-pattern>/*</url-pattern>
-            <http-method>POST</http-method>
-            <http-method>GET</http-method>
-            <http-method>PUT</http-method>
-            <http-method>PATCH</http-method>
-            <http-method>DELETE</http-method>
-            <http-method>HEAD</http-method>
-          </web-resource-collection>
-          <auth-constraint>
-            <role-name>System-Admin</role-name>
-            <role-name>Network-Admin</role-name>
-            <role-name>Network-Operator</role-name>
-            <role-name>Container-User</role-name>
-          </auth-constraint>
-        </security-constraint>
-
-        <security-role>
-                <role-name>System-Admin</role-name>
-        </security-role>
-        <security-role>
-                <role-name>Network-Admin</role-name>
-        </security-role>
-        <security-role>
-                <role-name>Network-Operator</role-name>
-        </security-role>
-        <security-role>
-                <role-name>Container-User</role-name>
-        </security-role>
-
-        <login-config>
-                <auth-method>BASIC</auth-method>
-                <realm-name>opendaylight</realm-name>
-        </login-config>
-</web-app>
diff --git a/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataBroker.java b/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingDataBroker.java
deleted file mode 100644 (file)
index 7eee5c8..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.md.sal.binding.api;
-
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-public interface BindingDataBroker extends AsyncDataBroker<InstanceIdentifier<?>, DataObject, BindingDataChangeListener>, BindingService {
-    @Override
-    BindingDataReadTransaction newReadOnlyTransaction();
-
-    @Override
-    BindingDataReadWriteTransaction newReadWriteTransaction();
-
-    @Override
-    BindingDataWriteTransaction newWriteOnlyTransaction();
-
-    @Override
-    ListenerRegistration<BindingDataChangeListener> registerDataChangeListener(LogicalDatastoreType store,
-            InstanceIdentifier<?> path, BindingDataChangeListener listener, DataChangeScope triggeringScope);
-}
diff --git a/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingTransactionChain.java b/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/BindingTransactionChain.java
new file mode 100644 (file)
index 0000000..eac65ad
--- /dev/null
@@ -0,0 +1,18 @@
+package org.opendaylight.controller.md.sal.binding.api;
+
+import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+public interface BindingTransactionChain extends TransactionChain<InstanceIdentifier<?>, DataObject> {
+
+    @Override
+    ReadOnlyTransaction newReadOnlyTransaction();
+
+    @Override
+    ReadWriteTransaction newReadWriteTransaction();
+
+    @Override
+    WriteTransaction newWriteOnlyTransaction();
+
+}
diff --git a/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/DataBroker.java b/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/DataBroker.java
new file mode 100644 (file)
index 0000000..b60d8ff
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * 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.api;
+
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionChainFactory;
+import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+/**
+ * Provides access to a conceptual data tree store and also provides the ability to
+ * subscribe for changes to data under a given branch of the tree.
+ * <p>
+ * For more information on usage, please see the documentation in {@link AsyncDataBroker}.
+ */
+public interface DataBroker extends AsyncDataBroker<InstanceIdentifier<?>, DataObject, DataChangeListener>, BindingService, TransactionChainFactory<InstanceIdentifier<?>, DataObject> {
+    @Override
+    ReadOnlyTransaction newReadOnlyTransaction();
+
+    @Override
+    ReadWriteTransaction newReadWriteTransaction();
+
+    @Override
+    WriteTransaction newWriteOnlyTransaction();
+
+    @Override
+    ListenerRegistration<DataChangeListener> registerDataChangeListener(LogicalDatastoreType store,
+            InstanceIdentifier<?> path, DataChangeListener listener, DataChangeScope triggeringScope);
+}
@@ -12,7 +12,7 @@ import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListene
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 
-public interface BindingDataChangeListener extends AsyncDataChangeListener<InstanceIdentifier<?>, DataObject> {
+public interface DataChangeListener extends AsyncDataChangeListener<InstanceIdentifier<?>, DataObject> {
     @Override
     void onDataChanged(AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change);
 }
@@ -7,15 +7,16 @@
  */
 package org.opendaylight.controller.md.sal.binding.api;
 
-import org.opendaylight.controller.md.sal.common.api.data.AsyncReadTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncReadOnlyTransaction;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.ListenableFuture;
+/**
+ * A transaction that provides a stateful read-only view of the data tree.
+ * <p>
+ * For more information on usage and examples, please see the documentation in
+ *  {@link org.opendaylight.controller.md.sal.common.api.data.AsyncReadTransaction}.
+ */
+public interface ReadOnlyTransaction extends ReadTransaction, AsyncReadOnlyTransaction<InstanceIdentifier<?>, DataObject> {
 
-public interface BindingDataReadTransaction extends AsyncReadTransaction<InstanceIdentifier<?>, DataObject> {
-    @Override
-    ListenableFuture<Optional<DataObject>> read(LogicalDatastoreType store, InstanceIdentifier<?> path);
 }
diff --git a/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/ReadTransaction.java b/opendaylight/md-sal/sal-binding-api/src/main/java/org/opendaylight/controller/md/sal/binding/api/ReadTransaction.java
new file mode 100644 (file)
index 0000000..cc85d43
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * 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.api;
+
+import org.opendaylight.controller.md.sal.common.api.data.AsyncReadTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.ListenableFuture;
+
+/**
+ * A transaction that provides read access to a logical data store.
+ * <p>
+ * For more information on usage and examples, please see the documentation in {@link AsyncReadTransaction}.
+ */
+public interface ReadTransaction extends AsyncReadTransaction<InstanceIdentifier<?>, DataObject> {
+
+    /**
+     * Reads data from the provided logical data store located at the provided path.
+     *<p>
+     * If the target is a subtree, then the whole subtree is read (and will be
+     * accessible from the returned data object).
+     *
+     * @param store
+     *            Logical data store from which read should occur.
+     * @param path
+     *            Path which uniquely identifies subtree which client want to
+     *            read
+     * @return Listenable Future which contains read result
+     *         <ul>
+     *         <li>If data at supplied path exists the
+     *         {@link ListeblaFuture#get()} returns Optional object containing
+     *         data once read is done.
+     *         <li>If data at supplied path does not exists the
+     *         {@link ListenbleFuture#get()} returns {@link Optional#absent()}.
+     *         </ul>
+     */
+    <T extends DataObject> ListenableFuture<Optional<T>> read(LogicalDatastoreType store, InstanceIdentifier<T> path);
+}
@@ -12,9 +12,10 @@ import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 
 /**
- * Logical capture of a combination of both {@link BindingDataReadTransaction} and
- * {@link BindingDataWriteTransaction}.
+ * A transaction that enables combined read/write capabilities.
+ * <p>
+ * For more information on usage and examples, please see the documentation in {@link AsyncReadWriteTransaction}.
  */
-public interface BindingDataReadWriteTransaction extends BindingDataReadTransaction, BindingDataWriteTransaction, AsyncReadWriteTransaction<InstanceIdentifier<?>, DataObject> {
+public interface ReadWriteTransaction extends ReadTransaction, WriteTransaction, AsyncReadWriteTransaction<InstanceIdentifier<?>, DataObject> {
 
 }
@@ -12,7 +12,12 @@ import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 
-public interface BindingDataWriteTransaction extends AsyncWriteTransaction<InstanceIdentifier<?>, DataObject> {
+/**
+ * A transaction that provides mutation capabilities on a data tree.
+ * <p>
+ * For more information on usage and examples, please see the documentation in {@link AsyncWriteTransaction}.
+ */
+public interface WriteTransaction extends AsyncWriteTransaction<InstanceIdentifier<?>, DataObject> {
     @Override
     void put(LogicalDatastoreType store, InstanceIdentifier<?> path, DataObject data);
 
index 453ff449118ffab0898f429cb02c8ec0ca8ed5ff..a41186dae11eda694687e7698663dffbc3364c26 100644 (file)
@@ -156,11 +156,26 @@ public interface BindingAwareBroker {
         void unregisterFunctionality(ProviderFunctionality functionality);
     }
 
+    /**
+     * Represents an RPC implementation registration. Users should call the
+     * {@link ObjectRegistration#close close} method when the registration is no longer needed.
+     *
+     * @param <T> the implemented RPC service interface
+     */
     public interface RpcRegistration<T extends RpcService> extends ObjectRegistration<T> {
 
+        /**
+         * Returns the implemented RPC service interface.
+         */
         Class<T> getServiceType();
     }
 
+    /**
+     * Represents a routed RPC implementation registration. Users should call the
+     * {@link RoutedRegistration#close close} method when the registration is no longer needed.
+     *
+     * @param <T> the implemented RPC service interface
+     */
     public interface RoutedRpcRegistration<T extends RpcService> extends RpcRegistration<T>,
             RoutedRegistration<Class<? extends BaseIdentity>, InstanceIdentifier<?>, T> {
 
index 4327451d2126fa51b6a3a7767e0c2fbd0781703c..bcbd6879d037d12a27c2781ab46f02887c571dff 100644 (file)
@@ -10,17 +10,64 @@ package org.opendaylight.controller.sal.binding.api;
 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.ConsumerContext;
 
 /**
- *
- * Defines the component of controller and supplies additional metadata. A
- * component of the controller or application supplies a concrete implementation
- * of this interface.
- *
- * A user-implemented component (application) which facilitates the SAL and SAL
- * services to access infrastructure services or providers' functionality.
- *
- *
- *
- */
+*
+* A developer implemented component that gets registered with the Broker.
+*
+* Semantically, a consumer may:
+*
+* <ol>
+*   <li>Subscribe for Notifications </li>
+*   <li>Invoke RPCs</li>
+*   <li>Read from either the operational or config data tree</li>
+*   <li>Write to the config data tree</li>
+* </ol>
+* If you need to:
+* <ol>
+*   <li> Emit Notifications</li>
+*   <li> Provide the implementation of RPCs </li>
+*   <li> Write to the operational data tree </li>
+* </ol>
+*
+* Consider using a BindingAwareProvider
+*
+* Examples:
+*
+* To get a NotificationService:
+*
+* {code
+* public void onSessionInitiated(ProviderContext session) {
+*      NotificationProviderService notificationService = session.getSALService(NotificationProviderService.class);
+*      notificationService.publish(notification)
+* }
+* where notification is an instance of a modeled Notification.
+* For more information on sending notifications via the NotificationProviderService
+* @see org.opendaylight.controller.sal.binding.api.NotificationProviderService
+*
+*
+* A consumer can *invoke* and RPC ( ie, call foo(fooArgs)) but it cannot register an RPC
+* implementation with the MD-SAL that others can invoke(call).
+* To get an invokable RPC:
+*
+* {code
+* public void onSessionInitiated(ProviderContext session) {
+*    MyService rpcFlowSalService = session.getRpcService(MyService.class);
+* }
+*
+* Where MyService.class is a Service interface generated from a yang model with RPCs modeled in it.  The returned
+* rpcFlowSalService can be used like any other object by invoking its methods.  Note, nothing special needs to be done
+* for RoutedRPCs.  They just work.
+*
+* To get a DataBroker to allow access to the data tree:
+*
+* {code
+* public void onSessionInitiated(final ProviderContext session) {
+*      DataBroker databroker = session.getSALService(BindingDataBroker.class);
+* }
+* }
+* @see org.opendaylight.controller.md.sal.common.api.data.BindingDataBroker
+* for more info on using the DataBroker.
+*
+*/
 public interface BindingAwareConsumer {
 
     /**
index 0812e5f53c3d9193cbafaae8acabaaa06be3b880..cb26cad2f392cacc01757cd6c8bdff1b29920cad 100644 (file)
@@ -15,37 +15,131 @@ import org.opendaylight.yangtools.yang.binding.RpcService;
 
 /**
  *
- * Defines the component of controller and supplies additional metadata. A
- * component of the controller or application supplies a concrete implementation
- * of this interface.
+ * A developer implemented component that gets registered with the Broker.
  *
+ * Semantically, a provider may:
+ *
+ * <ol>
+ *   <li> Emit Notifications</li>
+ *   <li> Provide the implementation of RPCs </li>
+ *   <li> Write to the operational data tree </li>
+ * </ol>
+ *
+ * If a class is not doing at least one of those three, consider using
+ * a BindingAwareConsumer instead:
+ * @see org.opendaylight.controller.sal.binding.api.BindingAwareConsumer
+ *
+ * <p>
+ *
+ *In addition, a BindingAwareProvider can in pursuit of its goals:
+ *
+ * <ol>
+ *   <li>Subscribe for Notifications </li>
+ *   <li>Invoke RPCs</li>
+ *   <li>Read from either the operational or config data tree</li>
+ *   <li>Write to the config data tree</li>
+ * </ol>
+ * (All of the above are things a Consumer can also do).
+ *
+ *<p>
+ *
+ * Examples:
+ *
+ *<p>
+ *
+ * To get a NotificationService:
+ *
+ * {code
+ * public void onSessionInitiated(ProviderContext session) {
+ *      NotificationProviderService notificationService = session.getSALService(NotificationProviderService.class);
+ * }
+ * For more information on sending notifications via the NotificationProviderService
+ * @see org.opendaylight.controller.sal.binding.api.NotificationProviderService
+ *
+ * To register an RPC implementation:
+ *
+ * {code
+ * public void onSessionInitiated(ProviderContext session) {
+ *    RpcRegistration<MyService> registration = session.addRpcImplementation(MyService.class, myImplementationInstance);
+ * }
+ *
+ * <p>
+ *
+ * Where MyService.class is a Service interface generated from a yang model with RPCs modeled in it and myImplementationInstance
+ * is an instance of a class that implements MyService.
+ *
+ * To register a Routed RPC Implementation:
+ * {code
+ * public void onSessionInitiated(ProviderContext session) {
+ *   RoutedRpcRegistration<SalFlowService> flowRegistration = session.addRoutedRpcImplementation(SalFlowService.class, salFlowServiceImplementationInstance);
+     flowRegistration.registerPath(NodeContext.class, nodeInstanceId);
+ * }
+ * }
+ *
+ * Where SalFlowService.class is a Service interface generated from a yang model with RPCs modeled in it and salFlowServiceImplementationInstance is an instance
+ * of a class that implements SalFlowService.
  * <p>
- * A user-implemented component (application) which facilitates the SAL and SAL
- * services to access infrastructure services and to provide functionality to
- * {@link Consumer}s and other providers.
+ * The line:
+ * {code
+ * flowRegistration.registerPath(NodeContext.class, nodeInstanceId);
+ * }
+ * Is indicating that the RPC implementation is registered to handle RPC invocations that have their NodeContext pointing to the node with instance id nodeInstanceId.
+ * This bears a bit of further explanation.  RoutedRPCs can be 'routed' to an implementation based upon 'context'.  'context' is a pointer (instanceId) to some place
+ * in the data tree.  In this example, the 'context' is a pointer to a Node.  In this way, a provider can register its ability to provide a service for a particular
+ * Node, but not *all* Nodes.  The Broker routes the RPC by 'context' to the correct implementation, without the caller having to do extra work.  Because of this when
+ * a RoutedRPC is registered, it needs to also be able to indicate for which 'contexts' it is providing an implementation.
+ *
+ * An example of a Routed RPC would be an updateFlow(node, flow) that would be routed based on node to the provider which had registered to provide
+ * it *for that node*.
+ *
+ *<p>
  *
+ * To get a DataBroker to allow access to the data tree:
+ *
+ * {code
+ * public void onSessionInitiated(final ProviderContext session) {
+ *      DataBroker databroker = session.getSALService(BindingDataBroker.class);
+ * }
+ * }
+ * @see org.opendaylight.controller.md.sal.common.api.data.BindingDataBroker
+ * for more info on using the DataBroker.
  *
  */
 public interface BindingAwareProvider {
 
     /**
-     * Returns a set of provided implementations of YANG modules and their rpcs.
+     * @deprecated
      *
+     * This interface was originally intended to solve problems of how to get Implementations
+     * of functionality from a provider, but that is no longer necessary because the Provider
+     * Registers RPCs in onSessionInitiated.
      *
-     * @return Set of provided implementation of YANG modules and their Rpcs
+     * Recommend:
+     * {code
+     * public Collection<? extends RpcService> getImplementations() {
+     *   return Collections.emptySet();
+     * }
+     * }
      */
+    @Deprecated
     Collection<? extends RpcService> getImplementations();
 
     /**
-     * Gets a set of implementations of provider functionality to be registered
-     * into system during the provider registration to the SAL.
+     * @deprecated
      *
-     * <p>
-     * This method is invoked by {@link Broker#registerProvider(Provider)} to
-     * learn the initial provided functionality
+     * This interface was originally intended to solve problems of how to get Functionality
+     *  a provider could provide, but that is no longer necessary because the Provider
+     * Registers RPCs in onSessionInitiated.
+     *
+     * Recommend:
+     * {code
+     * public Collection<? extends ProviderFunctionality> getFunctionality() {
+     *   return Collections.emptySet();
+     * }
+     * }
      *
-     * @return Set of provider's functionality.
      */
+    @Deprecated
     Collection<? extends ProviderFunctionality> getFunctionality();
 
     /**
@@ -58,12 +152,38 @@ public interface BindingAwareProvider {
      *
      *
      */
+    @Deprecated
     public interface ProviderFunctionality {
 
     }
-
+    /**
+     * Callback signaling initialization of the consumer session to the SAL.
+     *
+     * The consumer MUST use the session for all communication with SAL or
+     * retrieving SAL infrastructure services.
+     *
+     * This method is invoked by
+     * {@link BindingAwareBroker#registerProvider(BindingAwareProvider)}
+     *
+     * @param session Unique session between consumer and SAL.
+     */
     void onSessionInitiated(ProviderContext session);
 
+    /*
+     * @deprecated
+     *
+     * A provider was at one point considered an extension of a consumer, thus this
+     * call.  It is deprecated and the @see org.opendaylight.controller.sal.binding.api.BindingAwareConsumer#onSessionInitiated
+     * used, or you should simply use {@link #onSessionInitiated(ProviderContext)}
+     *
+     * Recommend:
+     * {code
+     * public final void onSessionInitialized(ConsumerContext session) {
+     *   // NOOP - as method is deprecated
+     * }
+     * }
+     */
+    @Deprecated
     void onSessionInitialized(ConsumerContext session);
 
 }
index 9429d3f8fa33372dedbbc8b0a00201db695d99a9..be8e0cefc1a3115329ed3391d99bbc8a38810dcd 100644 (file)
@@ -12,20 +12,20 @@ import java.util.EventListener;
 import org.opendaylight.yangtools.yang.binding.Notification;
 
 /**
- * Interface implemented by objects interested in some sort of Notification. This
- * class acts as a base interface for specific listeners which usually are a type
+ * Interface for a generic listener that is interested in receiving YANG modeled notifications.
+ * This interface acts as a base interface for specific listeners which usually are a type
  * capture of this interface.
  *
- * @param <T> Notification type
+ * @param <T> the interested notification type
  */
 public interface NotificationListener<T extends Notification> extends EventListener {
     /**
-     * Invoked to deliver the notification. Note that this method may be invoked
-     * from a shared thread pool, so implementations SHOULD NOT perform CPU-intensive
-     * operations and they definitely MUST NOT invoke any potentially blocking
-     * operations.
+     * Invoked to deliver a notification.
+     * <p>
+     * Note that this method may be invoked from a shared thread pool, so implementations SHOULD NOT
+     * perform CPU-intensive operations and MUST NOT invoke any potentially blocking operations.
      *
-     * @param notification Notification being delivered.
+     * @param notification the notification.
      */
     void onNotification(T notification);
 }
index b94695b83d437e31194e1e862da479b787ba8d80..00db80c19f7fd3fc9399dd303df74f7987eb2ce7 100644 (file)
@@ -14,29 +14,62 @@ import org.opendaylight.controller.md.sal.common.api.notify.NotificationPublishS
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.yang.binding.Notification;
 
+/**
+ * Interface for a notification service that provides publish/subscribe capabilities for YANG
+ * modeled notifications. This interface is a combination of the {@link NotificationService} and
+ * {@link NotificationPublishService} interfaces.
+ */
 public interface NotificationProviderService extends NotificationService, NotificationPublishService<Notification> {
+
     /**
-     * Publishes a notification.
-     *
-     * @param Notification
-     *            notification to publish.
-     *
+     * {@inheritDoc}
      */
     @Override
-    void publish(Notification notification);
+    public void publish(Notification notification);
 
     /**
-     * Publishes a notification, listener calls are done in provided executor.
-     *
+     * {@inheritDoc}
      */
     @Override
-    void publish(Notification notification, ExecutorService service);
+    void publish(Notification notification, ExecutorService executor);
 
+    /**
+     * Registers a listener to be notified about notification subscriptions. This
+     * enables a component to know when there is a notification listener subscribed
+     * for a particular notification type.
+     * <p>
+     * On registration of this listener, the
+     * {@link NotificationInterestListener#onNotificationSubscribtion(Class)} method
+     * will be invoked for every notification type that currently has a notification listener
+     * subscribed.
+     *
+     * @param interestListener the listener that will be notified when subscriptions
+     *                         for new notification types occur.
+     * @return a {@link ListenerRegistration} instance that should be used to unregister the listener
+     *         by invoking the {@link ListenerRegistration#close()} method when no longer needed.
+     */
     ListenerRegistration<NotificationInterestListener> registerInterestListener(
             NotificationInterestListener interestListener);
 
+    /**
+     * Interface for a listener interested in being notified about notification subscriptions.
+     */
     public interface NotificationInterestListener extends EventListener {
 
+        /**
+         * Callback that is invoked when a notification listener subscribes for a
+         * particular notification type.
+         * <p>
+         * This method is only called for the first subscription that occurs for a
+         * particular notification type. Subsequent subscriptions for the same
+         * notification type do not trigger invocation of this method.
+         * <p>
+         * <b>Note:</b>This callback is delivered from thread not owned by this listener,
+         * all processing should be as fast as possible and implementations should
+         * not do any blocking calls or block this thread.
+         *
+         * @param notificationType the notification type for the subscription that occurred.
+         */
         void onNotificationSubscribtion(Class<? extends Notification> notificationType);
     }
 }
index 46e372aea652e29439408da9b6d1ccc963e86acc..335f55bcbbade9ce84898eafee05ff146ef2d382 100644 (file)
@@ -10,24 +10,108 @@ package org.opendaylight.controller.sal.binding.api;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.yang.binding.Notification;
 
+/**
+ * Notification broker which allows clients to subscribe for and publish YANG-modeled notifications.
+ *
+ *<p>
+ * Two styles of listeners are supported:
+ * <ul>
+ * <li>Generic listener</li>
+ * <li>Dispatch listener - listener, which implements <code>{ModelName}Listener</code> interface,
+ * which has dispatch methods for each defined notification. Methods are invoked based on notification type (class).
+ * </li>
+ *
+ * <h3>Generic Listener</h3>
+ * <p>
+ * A generic listener implements the {@link NotificationListener} interface which has one callback method
+ * <code>onNotification</code> that is invoked for any notification type the listener is subscribed to.
+ * <p>
+ * A generic listener is subscribed using the {@link #registerNotificationListener(Class, NotificationListener)}
+ * method by which you specify the type of notification to receive. A generic listener may be registered for
+ * multiple notification types via multiple subscriptions.
+ * <p>
+ * Generic listeners allow for a more flexible approach, allowing you to subscribe for just
+ * one type of notification from a YANG model. You could also have a general subscription
+ * for all notification in the system via
+ * <pre>
+ *   service.registerNotificationListener(Notification.class, listener);
+ * </pre>
+ *
+ * <h3>Dispatch Listener</h3>
+ * <p>
+ * A dispatch listener implements a YANG-generated module interface <code>{ModuleName}Listener</code>
+ * which handles all the notifications defined in the YANG model. Each notification type translates to
+ * a specific method of the form <code>on{NotificationType}</code> on the generated interface.
+ * The generated interface also extends the
+ * {@link org.opendaylight.yangtools.yang.binding.NotificationListener} interface and implementations
+ * are registered using {@link #registerNotificationListener(org.opendaylight.yangtools.yang.binding.NotificationListener)}
+ * method.
+ *
+ * <h5>Dispatch Listener Example</h5>
+ * <p>
+ * Lets assume we have following YANG model:
+ *
+ * <pre>
+ * module example {
+ *      ...
+ *
+ *      notification start {
+ *          ...
+ *      }
+ *
+ *      notification stop {
+ *           ...
+ *      }
+ * }
+ * </pre>
+ *
+ * The generated interface will be:
+ * <pre>
+ *  public interface ExampleListener extends NotificationListener {
+ *      void onStart(Start notification);
+ *      void onStop(Stop notification);
+ *  }
+ * </pre>
+ * The following defines an implementation of the generated interface:
+ * <pre>
+ *  public class MyExampleListener implements ExampleListener {
+ *      public void onStart(Start notification) {
+ *          // do something
+ *      }
+ *
+ *      public void onStop(Stop notification) {
+ *          // do something
+ *      }
+ *  }
+ * </pre>
+ * The implementation is registered as follows:
+ * <pre>
+ *  MyExampleListener listener = new MyExampleListener();
+ *  ListenerRegistration<NotificationListener> reg = service.registerNotificationListener( listener );
+ * </pre>
+ * The <code>onStart</code> method will be invoked when someone publishes a <code>Start</code> notification and
+ * the <code>onStop</code> method will be invoked when someone publishes a <code>Stop</code> notification.
+ */
 public interface NotificationService extends BindingAwareService {
     /**
-     * Register a generic listener for specified notification type only.
+     * Registers a generic listener implementation for a specified notification type.
      *
-     * @param notificationType
-     * @param listener
-     * @return Registration for listener. To unregister listener invoke {@link ListenerRegistration#close()} method.
+     * @param notificationType the YANG-generated interface of the notification type.
+     * @param listener the listener implementation that will receive notifications.
+     * @return a {@link ListenerRegistration} instance that should be used to unregister the listener
+     *         by invoking the {@link ListenerRegistration#close()} method when no longer needed.
      */
     <T extends Notification> ListenerRegistration<NotificationListener<T>> registerNotificationListener(
             Class<T> notificationType, NotificationListener<T> listener);
 
     /**
-     * Register a listener which implements generated notification interfaces derived from
+     * Registers a listener which implements a YANG-generated notification interface derived from
      * {@link org.opendaylight.yangtools.yang.binding.NotificationListener}.
-     * Listener is registered for all notifications present in implemented interfaces.
+     * The listener is registered for all notifications present in the implemented interface.
      *
-     * @param listener
-     * @return Registration for listener. To unregister listener invoke {@link ListenerRegistration#close()} method.
+     * @param listener the listener implementation that will receive notifications.
+     * @return a {@link ListenerRegistration} instance that should be used to unregister the listener
+     *         by invoking the {@link ListenerRegistration#close()} method when no longer needed.
      */
     ListenerRegistration<org.opendaylight.yangtools.yang.binding.NotificationListener> registerNotificationListener(
             org.opendaylight.yangtools.yang.binding.NotificationListener listener);
index 7da0a48517fddf715db5f55ced1d431680f0a755..615acd3195c8a99ed5b5f372f53dee46d5faac7b 100644 (file)
@@ -10,16 +10,60 @@ package org.opendaylight.controller.sal.binding.api;
 import org.opendaylight.yangtools.yang.binding.RpcService;
 
 /**
- * Base interface defining contract for retrieving MD-SAL
- * version of RpcServices
+ * Provides access to registered Remote Procedure Call (RPC) service implementations. The RPCs are
+ * defined in YANG models.
+ * <p>
+ * RPC implementations are registered using the {@link RpcProviderRegistry}.
  *
  */
 public interface RpcConsumerRegistry extends BindingAwareService {
     /**
-     * Returns a session specific instance (implementation) of requested
-     * YANG module implementation / service provided by consumer.
+     * Returns an implementation of a requested RPC service.
      *
-     * @return Session specific implementation of service
+     * <p>
+     * The returned instance is not an actual implementation of the RPC service
+     * interface, but a proxy implementation of the interface that forwards to
+     * an actual implementation, if any.
+     * <p>
+     *
+     * The following describes the behavior of the proxy when invoking RPC methods:
+     * <ul>
+     * <li>If an actual implementation is registered with the MD-SAL, all invocations are
+     * forwarded to the registered implementation.</li>
+     * <li>If no actual implementation is registered, all invocations will fail by
+     * throwing {@link IllegalStateException}.</li>
+     * <li>Prior to invoking the actual implementation, the method arguments are are validated.
+     * If any are invalid, an {@link IllegalArgumentException} is thrown.
+     * </ul>
+     *
+     * The returned proxy is automatically updated with the most recent
+     * registered implementation.
+     * <p>
+     * The generated RPC method APIs require implementors to return a {@link java.util.concurrent.Future Future}
+     * instance that wraps the {@link org.opendaylight.yangtools.yang.common.RpcResult RpcResult}. Since
+     * RPC methods may be implemented asynchronously, callers should avoid blocking on the
+     * {@link java.util.concurrent.Future Future} result. Instead, it is recommended to use
+     * {@link com.google.common.util.concurrent.JdkFutureAdapters#listenInPoolThread(java.util.concurrent.Future)}
+     * or {@link com.google.common.util.concurrent.JdkFutureAdapters#listenInPoolThread(java.util.concurrent.Future, java.util.concurrent.Executor)}
+     * to listen for Rpc Result. This will asynchronously listen for future result in executor and
+     * will not block current thread.
+     *
+     * <pre>
+     *   final Future<RpcResult<SomeRpcOutput>> future = someRpcService.someRpc( ... );
+     *   Futures.addCallback(JdkFutureAdapters.listenInThreadPool(future), new FutureCallback<RpcResult<SomeRpcOutput>>() {
+     *
+     *       public void onSuccess(RpcResult<SomeRpcOutput> result) {
+     *          // process result ...
+     *       }
+     *
+     *       public void onFailure(Throwable t) {
+     *          // RPC failed
+     *       }
+     *   );
+     * </pre>
+     * @param serviceInterface the interface of the RPC Service. Typically this is an interface generated
+     *                         from a YANG model.
+     * @return the proxy for the requested RPC service. This method never returns null.
      */
-    <T extends RpcService> T getRpcService(Class<T> module);
+    <T extends RpcService> T getRpcService(Class<T> serviceInterface);
 }
index cdf55844b3d94d680a7a21ad052deb9a7aa73ac4..22db985ba96b82cc4245a42f28ccd3e1f9959774 100644 (file)
@@ -15,39 +15,256 @@ import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.binding.RpcService;
 
 /**
- * Interface defining provider's access to the Rpc Registry which could be used
- * to register their implementations of service to the MD-SAL.
+ * Provides a registry for Remote Procedure Call (RPC) service implementations. The RPCs are
+ * defined in YANG models.
+ * <p>
+ * There are 2 types of RPCs:
+ * <ul>
+ * <li>Global</li>
+ * <li>Routed</li>
+ * </ul>
  *
- * @author ttkacik
+ * <h2>Global RPC</h2>
+ * <p>
+ * An RPC is global if there is intended to be only 1 registered implementation. A global RPC is not
+ * explicitly declared as such, essentially any RPC that is not defined to be routed is considered global.
+ * <p>
+ * Global RPCs are registered using the
+ * {@link #addRpcImplementation(Class, RpcService)} method.
  *
+ * <h2>Routed RPC</h2>
+ * <p>
+ * MD-SAL supports routing of RPC between multiple implementations where the appropriate
+ * implementation is selected at run time based on the content of the RPC message as described in
+ * YANG model.
+ * <p>
+ * RPC routing is based on:
+ * <ul>
+ * <li><b>Route identifier</b> -
+ * An {@link org.opendaylight.yangtools.yang.binding.InstanceIdentifier InstanceIdentifier} value
+ * which is part of the RPC input. This value is used to select the correct
+ * implementation at run time.</li>
+ * <li><b>Context Type</b> - A YANG-defined construct which constrains the subset of
+ * valid route identifiers for a particular RPC.</li>
+ * </ul>
+ *
+ * <h3>Context type</h3>
+ * <p>
+ * A context type is modeled in YANG using a combination of a YANG <code>identity</code>
+ * and Opendaylight specific extensions from <code>yang-ext</code> module. These extensions are:
+ * <ul>
+ * <li><b>context-instance</b> - This is used in the data tree part of a YANG model to
+ * define a context type that associates nodes with a specified context <code>identity</code>.
+ * Instance identifiers that reference these nodes are valid route identifiers for RPCs that
+ * reference this context type.</li>
+ * <li><b>context-reference</b> - This is used in RPC input to mark a leaf of type
+ * <code>instance-identifier</code> as a reference to the particular context type defined by the
+ * specified context <code>identity</code>. The value of this
+ * leaf is used by the RPC broker at run time to route the RPC request to the correct implementation.
+ * Note that <code>context-reference</code> may only be used on leaf elements of type
+ * <code>instance-identifier</code> or a type derived from <code>instance-identifier</code>.</li>
+ * </ul>
+ *
+ *
+ * <h3>Routed RPC example</h3>
+ * <p>
+ * <h5>1. Defining a Context Type</h5>
+ * <p>
+ * The following snippet declares a simple YANG <code>identity</code> named <code>example-context</code>:
+ *
+ * <pre>
+ * module example {
+ *     ...
+ *     identity example-context {
+ *          description "Identity used to define an example-context type";
+ *     }
+ *     ...
+ * }
+ * </pre>
+ * <p>
+ * We then use the declared identity to define a context type by using it in combination
+ * with the <code>context-instance</code> YANG extension. We'll associate the context type
+ * with a list element in the data tree. This defines the set of nodes whose instance
+ * identifiers are valid for the <code>example-context</code> context type.
+ * <p>
+ * The following YANG snippet imports the <code>yang-ext</code> module and defines the list
+ * element named <code>item</code> inside a container named <code>foo</code>:
+ *
+ * <pre>
+ * module foo {
+ *     ...
+ *     import yang-ext {prefix ext;}
+ *     ...
+ *     container foo {
+ *          list item {
+ *              key "id";
+ *              leaf id {type string;}
+ *              ext:context-instance "example-context";
+ *          }
+ *     }
+ *     ...
+ * }
+ * </pre>
+ * <p>
+ * The statement <code>ext:context-instance "example-context";</code> inside the list element
+ * declares that any instance identifier referencing <code>item</code> in the data
+ * tree is valid for <code>example-context</code>. For example, the following instance
+ * identifier:
+ * <pre>
+ *     InstanceIdentifier.create(Foo.class).child(Item.class,new ItemKey("Foo"))
+ * </pre>
+ * is valid for <code>example-context</code>. However the following:
+ * <pre>
+ *     InstanceIdentifier.create(Example.class)
+ * </pre>
+ * is not valid.
+ * <p>
+ * So using an <code>identity</code> in combination with <code>context-instance</code> we
+ * have effectively defined a context type that can be referenced in a YANG RPC input.
+ *
+ * <h5>2. Defining an RPC to use the Context Type</h5>
+ * <p>
+ * To define an RPC to be routed based on the context type we need to add an input leaf element
+ * that references the context type which will hold an instance identifier value to be
+ * used to route the RPC.
+ * <p>
+ * The following snippet defines an RPC named <code>show-item</code> with 2 leaf elements
+ * as input: <code>item</code> of type <code>instance-identifier</code> and <code>description</code>:
+ *
+ * <pre>
+ * module foo {
+ *      ...
+ *      import yang-ext {prefix ext;}
+ *      ...
+ *      rpc show-item {
+ *          input {
+ *              leaf item {
+ *                  type instance-identifier;
+ *                  ext:context-reference example-context;
+ *              }
+ *              leaf description {
+ *                  type "string";
+ *              }
+ *          }
+ *      }
+ * }
+ * </pre>
+ * <p>
+ * We mark the <code>item</code> leaf with a <code>context-reference</code> statement that
+ * references the <code>example-context</code> context type. RPC calls will then be routed
+ * based on the instance identifier value contained in <code>item</code>. Only instance
+ * identifiers that point to a <code>foo/item</code> node are valid as input.
+ * <p>
+ * The generated RPC Service interface for the module is:
+ *
+ * <pre>
+ * interface FooService implements RpcService {
+ *      Future&lt;RpcResult&lt;Void&gt;&gt; showItem(ShowItemInput input);
+ * }
+ * </pre>
+ * <p>
+ * For constructing the RPC input, there are generated classes ShowItemInput and ShowItemInputBuilder.
+ *
+ * <h5>3. Registering a routed RPC implementation</h5>
+ * <p>
+ * To register a routed implementation for the <code>show-item</code> RPC, we must use the
+ * {@link #addRoutedRpcImplementation(Class, RpcService)} method. This
+ * will return a {@link RoutedRpcRegistration} instance which can then be used to register /
+ * unregister routed paths associated with the registered implementation.
+ * <p>
+ * The following snippet registers <code>myImpl</code> as the RPC implementation for an
+ * <code>item</code> with key <code>"foo"</code>:
+ * <pre>
+ * // Create the instance identifier path for item "foo"
+ * InstanceIdentifier path = InstanceIdentifier.create(Foo.class).child(Item.class, new ItemKey(&quot;foo&quot;));
+ *
+ * // Register myImpl as the implementation for the FooService RPC interface
+ * RoutedRpcRegistration reg = rpcRegistry.addRoutedRpcImplementation(FooService.class, myImpl);
+ *
+ * // Now register for the context type and specific path ID. The context type is specified by the
+ * // YANG-generated class for the example-context identity.
+ * reg.registerPath(ExampleContext.class, path);
+ * </pre>
+ * <p>
+ * It is also possible to register the same implementation for multiple paths:
+ *
+ * <pre>
+ * InstanceIdentifier one = InstanceIdentifier.create(Foo.class).child(Item.class, new ItemKey(&quot;One&quot;));
+ * InstanceIdentifier two = InstanceIdentifier.create(Foo.class).child(Item.class, new ItemKey(&quot;Two&quot;));
+ *
+ * RoutedRpcRegistration reg = rpcRegistry.addRoutedRpcImplementation(FooService.class, myImpl);
+ * reg.registerPath(ExampleContext.class, one);
+ * reg.registerPath(ExampleContext.class, two);
+ * </pre>
+ *
+ * <p>
+ * When another client invokes the <code>showItem(ShowItemInput)</code> method on the proxy instance
+ * retrieved via {@link RpcConsumerRegistry#getRpcService(Class)}, the proxy will inspect the
+ * arguments in ShowItemInput, extract the InstanceIdentifier value of the <code>item</code> leaf and select
+ * the implementation whose registered path matches the InstanceIdentifier value of the <code>item</code> leaf.
+ *
+ * <h2>Notes for RPC Implementations</h2>
+ *
+ * <h3>RpcResult</h3>
+ * <p>
+ * The generated interfaces require implementors to return
+ *  {@link java.util.concurrent.Future Future}&lt;{@link org.opendaylight.yangtools.yang.common.RpcResult RpcResult}&lt;{RpcName}Output&gt;&gt; instances.
+ *
+ * Implementations should do processing of RPC calls asynchronously and update the
+ * returned {@link java.util.concurrent.Future Future} instance when processing is complete.
+ * However using {@link com.google.common.util.concurrent.Futures#immediateFuture(Object) Futures.immediateFuture}
+ * is valid only if the result is immediately available and asynchronous processing is unnecessary and
+ * would only introduce additional complexity.
+ *
+ * <p>
+ * The {@link org.opendaylight.yangtools.yang.common.RpcResult RpcResult} is a generic
+ * wrapper for the RPC output payload, if any, and also allows for attaching error or
+ * warning information (possibly along with the payload) should the RPC processing partially
+ * or completely fail. This is intended to provide additional human readable information
+ * for users of the API and to transfer warning / error information across the system
+ * so it may be visible via other external APIs such as Restconf.
+ * <p>
+ * It is recommended to use the {@link org.opendaylight.yangtools.yang.common.RpcResult RpcResult}
+ * for conveying appropriate error information
+ * on failure rather than purposely throwing unchecked exceptions if at all possible.
+ * While unchecked exceptions will fail the returned {@link java.util.concurrent.Future Future},
+ * using the intended RpcResult to convey the error information is more user-friendly.
  */
 public interface RpcProviderRegistry extends //
         RpcConsumerRegistry, //
         RouteChangePublisher<RpcContextIdentifier, InstanceIdentifier<?>> {
     /**
-     * Registers a global RpcService implementation.
+     * Registers a global implementation of the provided RPC service interface.
+     * All methods of the interface are required to be implemented.
+     *
+     * @param serviceInterface the YANG-generated interface of the RPC Service for which to register.
+     * @param implementation "the implementation of the RPC service interface.
+     * @return an RpcRegistration instance that should be used to unregister the RPC implementation
+     *         when no longer needed by calling {@link RpcRegistration#close()}.
      *
-     * @param type
-     * @param implementation
-     * @return
+     * @throws IllegalStateException
+     *             if the supplied RPC interface is a routed RPC type.
      */
-    <T extends RpcService> RpcRegistration<T> addRpcImplementation(Class<T> type, T implementation)
+    <T extends RpcService> RpcRegistration<T> addRpcImplementation(Class<T> serviceInterface, T implementation)
             throws IllegalStateException;
 
     /**
+     * Registers an implementation of the given routed RPC service interface.
+     * <p>
+     * See the {@link RpcProviderRegistry class} documentation for information and example on
+     * how to use routed RPCs.
      *
-     * Register a Routed RpcService where routing is determined on annotated
-     * (in YANG model) context-reference and value of annotated leaf.
-     *
-     * @param type
-     *            Type of RpcService, use generated interface class, not your
-     *            implementation class
-     * @param implementation
-     *            Implementation of RpcService
-     * @return Registration object for routed Rpc which could be used to unregister
+     * @param serviceInterface the YANG-generated interface of the RPC Service for which to register.
+     * @param implementation the implementation instance to register.
+     * @return a RoutedRpcRegistration instance which can be used to register paths for the RPC
+     *         implementation via invoking {@link RoutedRpcRegistration#registerPath(....).
+     *         {@link RoutedRpcRegistration#close()} should be called to unregister the implementation
+     *         and all previously registered paths when no longer needed.
      *
      * @throws IllegalStateException
+     *            if the supplied RPC interface is not a routed RPC type.
      */
-    <T extends RpcService> RoutedRpcRegistration<T> addRoutedRpcImplementation(Class<T> type, T implementation)
+    <T extends RpcService> RoutedRpcRegistration<T> addRoutedRpcImplementation(Class<T> serviceInterface,
+                                                                               T implementation)
             throws IllegalStateException;
 }
index d0225768b4e2500acf0eccfb13e4999e0a8591e3..d30ca6beaf6fc209f600fbe09175895d4b9bdd62 100644 (file)
@@ -21,7 +21,9 @@ import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
  *
  *
  * @see DataProviderService
+ * @deprecated Replaced by newer better documented version {@link org.opendaylight.controller.md.sal.binding.api.DataBroker}
  */
+@Deprecated
 public interface DataBrokerService extends //
         BindingAwareService, //
         DataModificationTransactionFactory<InstanceIdentifier<? extends DataObject>, DataObject>, //
@@ -31,16 +33,26 @@ public interface DataBrokerService extends //
      * Creates a data modification transaction.
      *
      * @return new blank data modification transaction.
+     * @deprecated Replaced by more specific transaction types. Please use
+     *          {@link org.opendaylight.controller.md.sal.binding.api.DataBroker#newReadOnlyTransaction(),
+     *          {@link org.opendaylight.controller.md.sal.binding.api.DataBroker#newReadWriteTransaction()
+     *          or
+     *          {@link org.opendaylight.controller.md.sal.binding.api.DataBroker#newWriteOnlyTransaction().
      */
+    @Deprecated
     @Override
     DataModificationTransaction beginTransaction();
 
     /**
      * Reads data subtree from configurational store.
      * (Store which is populated by consumer, which is usually used to
-     * inject state into providers. E.g. Flow configuration)-
+     * inject state into providers. E.g. Flow configuration)
+     *
+     *
+     * @deprecated Please use {@link org.opendaylight.controller.md.sal.binding.api.DataBroker#newReadOnlyTransaction()}
      *
      */
+    @Deprecated
     @Override
     public DataObject readConfigurationData(InstanceIdentifier<? extends DataObject> path);
 
@@ -49,7 +61,9 @@ public interface DataBrokerService extends //
      * (Store which is populated by providers, which is usually used to
      * capture state of providers. E.g. Topology)
      *
+     * @deprecated Please use {@link org.opendaylight.controller.md.sal.binding.api.DataBroker#newReadOnlyTransaction()}
      */
+    @Deprecated
     @Override
     public DataObject readOperationalData(InstanceIdentifier<? extends DataObject> path);
 
@@ -58,7 +72,10 @@ public interface DataBrokerService extends //
      *
      * Callback is invoked each time data in subtree changes.
      *
+     * @deprecated Please use {@link org.opendaylight.controller.md.sal.binding.api.DataBroker#registerDataChangeListener(org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType, InstanceIdentifier, org.opendaylight.controller.md.sal.binding.api.DataChangeListener, org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope)}
+     * which provides more fine-grained registration options.
      */
+    @Deprecated
     @Override
     public ListenerRegistration<DataChangeListener> registerDataChangeListener(
             InstanceIdentifier<? extends DataObject> path, DataChangeListener listener);
index 6373cfbf4a3ec6a67f8cdd2c3b423ea1eb5b4e28..e26cbcef29b7e40a3757425216f0253d706fcda1 100644 (file)
@@ -11,6 +11,12 @@ import org.opendaylight.controller.md.sal.common.api.data.DataChangeEvent;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 
+/**
+ *
+ * @deprecated Replaced by {@link org.opendaylight.controller.md.sal.binding.api.DataChangeListener}
+ *
+ */
+@Deprecated
 public interface DataChangeListener extends
         org.opendaylight.controller.md.sal.common.api.data.DataChangeListener<InstanceIdentifier<? extends DataObject>, DataObject> {
 
index 5fafabbd1b6e9104bd72c3946acce0aa2e580871..0c250fdbee4c2454d0d9c1afa981ef71b4c05acc 100644 (file)
@@ -17,6 +17,18 @@ import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 
+/**
+ *
+ *
+ * @deprecated Replaced by more specific transaction types. Please use
+ *          {@link org.opendaylight.controller.md.sal.binding.api.DataBroker#newReadOnlyTransaction(),
+ *          {@link org.opendaylight.controller.md.sal.binding.api.DataBroker#newReadWriteTransaction()
+ *          or
+ *          {@link org.opendaylight.controller.md.sal.binding.api.DataBroker#newWriteOnlyTransaction().
+ *
+ *
+ */
+@Deprecated
 public interface DataModificationTransaction extends DataModification<InstanceIdentifier<? extends DataObject>, DataObject> {
     /**
      * Returns an unique identifier for transaction
index b496d1dfb4ba58636e2af34abcd1e7cd186f4f55..5aa3b99b3009ea850c8131eef042391b0d7c6d5a 100644 (file)
@@ -16,7 +16,10 @@ import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 /**
  * DataProviderService is common access point for {@link org.opendaylight.controller.sal.binding.api.BindingAwareProvider} providers
  * to access data trees described by the YANG model.
+ *
+ * @deprecated Replaced by {@link org.opendaylight.controller.md.sal.common.api.data.AsyncConfigurationCommitCoordinator} service.
  */
+@Deprecated
 public interface DataProviderService extends DataBrokerService, DataProvisionService<InstanceIdentifier<? extends DataObject>, DataObject> {
     /**
      * Registers a data reader for particular subtree of overal YANG data tree.
@@ -27,6 +30,8 @@ public interface DataProviderService extends DataBrokerService, DataProvisionSer
      * @param path Subpath which is handled by registered data reader
      * @param reader Instance of reader which
      * @return Registration object for reader. Invoking {@link Registration#close()} will unregister reader.
+     * @deprecated Data Reader contract is removed from capabilities of MD-SAL and is replaced by  replaced by org.opendaylight.controller.sal.core.spi.data.DOMStore contract.
      */
+    @Deprecated
     Registration<DataReader<InstanceIdentifier<? extends DataObject>,DataObject>> registerDataReader(InstanceIdentifier<? extends DataObject> path,DataReader<InstanceIdentifier<? extends DataObject>,DataObject> reader);
 }
index 3334f2a037b119711916a52ad7c9d86b6424201d..c0c8f4f2112fd0ccb7dcde3427009595c880ccc2 100644 (file)
@@ -13,8 +13,9 @@ import org.opendaylight.controller.sal.binding.api.BindingAwareProvider;
  * Trigger for refreshing of the data exposed by the {@link Provider}
  *
  *
- *
+ * @deprecated Unused, not supported. Replaced by org.opendaylight.controller.sal.core.spi.data.DOMStore.
  */
+@Deprecated
 public interface DataRefresher extends BindingAwareProvider.ProviderFunctionality {
 
     /**
index 85a2b82ee0397174966e8e584a6607eb61de3433..273f20f01da8c27562017d7f4aede2a144c6bffe 100644 (file)
@@ -15,9 +15,11 @@ import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 /**
  * Utility interface which does type capture for BindingAware DataReader.
  *
- * @author
+ *
+ * @deprecated Removed, replaced by org.opendaylight.controller.sal.core.spi.data.DOMStore.
  *
  */
+@Deprecated
 public interface RuntimeDataProvider extends ProviderFunctionality,DataReader<InstanceIdentifier<? extends DataObject>, DataObject> {
 
 
index da6d46d499317d647673cfb2b7ef5d60e43b2eae..fc0d3964ea07ff7d107d99e0278a0df7263f9772 100644 (file)
@@ -25,12 +25,19 @@ import com.google.common.base.Preconditions;
  *
  * To get instance of synchronized wrapper use {@link #from(DataModificationTransaction)}
  *
+ * @deprecated Replaced by more specific transaction types. Please use
+ *          {@link org.opendaylight.controller.md.sal.binding.api.DataBroker#newReadOnlyTransaction(),
+ *          {@link org.opendaylight.controller.md.sal.binding.api.DataBroker#newReadWriteTransaction()
+ *          or
+ *          {@link org.opendaylight.controller.md.sal.binding.api.DataBroker#newWriteOnlyTransaction().
+ *
  */
+@Deprecated
 public final class SynchronizedTransaction implements DataModificationTransaction,Delegator<DataModificationTransaction> {
 
     private final DataModificationTransaction delegate;
 
-    private SynchronizedTransaction(DataModificationTransaction delegate) {
+    private SynchronizedTransaction(final DataModificationTransaction delegate) {
         this.delegate = delegate;
     }
 
@@ -40,7 +47,7 @@ public final class SynchronizedTransaction implements DataModificationTransactio
      * @param transaction Transaction for which synchronized wrapper should be created.
      * @return Synchronized wrapper over transaction.
      */
-    public static final SynchronizedTransaction from(DataModificationTransaction transaction) {
+    public static final SynchronizedTransaction from(final DataModificationTransaction transaction) {
         Preconditions.checkArgument(transaction != null, "Transaction must not be null.");
         if (transaction instanceof SynchronizedTransaction) {
             return (SynchronizedTransaction) transaction;
@@ -59,7 +66,7 @@ public final class SynchronizedTransaction implements DataModificationTransactio
     }
 
     @Override
-    public synchronized DataObject readOperationalData(InstanceIdentifier<? extends DataObject> path) {
+    public synchronized DataObject readOperationalData(final InstanceIdentifier<? extends DataObject> path) {
         return delegate.readOperationalData(path);
     }
 
@@ -79,7 +86,7 @@ public final class SynchronizedTransaction implements DataModificationTransactio
     }
 
     @Override
-    public synchronized DataObject readConfigurationData(InstanceIdentifier<? extends DataObject> path) {
+    public synchronized DataObject readConfigurationData(final InstanceIdentifier<? extends DataObject> path) {
         return delegate.readConfigurationData(path);
     }
 
@@ -89,12 +96,12 @@ public final class SynchronizedTransaction implements DataModificationTransactio
     }
 
     @Override
-    public synchronized void putOperationalData(InstanceIdentifier<? extends DataObject> path, DataObject data) {
+    public synchronized void putOperationalData(final InstanceIdentifier<? extends DataObject> path, final DataObject data) {
         delegate.putOperationalData(path, data);
     }
 
     @Override
-    public synchronized void putConfigurationData(InstanceIdentifier<? extends DataObject> path, DataObject data) {
+    public synchronized void putConfigurationData(final InstanceIdentifier<? extends DataObject> path, final DataObject data) {
         delegate.putConfigurationData(path, data);
     }
 
@@ -104,12 +111,12 @@ public final class SynchronizedTransaction implements DataModificationTransactio
     }
 
     @Override
-    public synchronized void removeOperationalData(InstanceIdentifier<? extends DataObject> path) {
+    public synchronized void removeOperationalData(final InstanceIdentifier<? extends DataObject> path) {
         delegate.removeOperationalData(path);
     }
 
     @Override
-    public synchronized void removeConfigurationData(InstanceIdentifier<? extends DataObject> path) {
+    public synchronized void removeConfigurationData(final InstanceIdentifier<? extends DataObject> path) {
         delegate.removeConfigurationData(path);
     }
 
@@ -129,7 +136,7 @@ public final class SynchronizedTransaction implements DataModificationTransactio
     }
 
     @Override
-    public synchronized ListenerRegistration<DataTransactionListener> registerListener(DataTransactionListener listener) {
+    public synchronized ListenerRegistration<DataTransactionListener> registerListener(final DataTransactionListener listener) {
         return delegate.registerListener(listener);
     }
 
@@ -152,7 +159,7 @@ public final class SynchronizedTransaction implements DataModificationTransactio
     }
 
     @Override
-    public boolean equals(Object obj) {
+    public boolean equals(final Object obj) {
         if (this == obj) {
             return true;
         }
index 35b186db6aeeaf5ed53ee8a7e43bf5d9e4fb1b82..74cceb1cbd55fc786b78e3f111b2a82a60bd8751 100644 (file)
       <groupId>org.opendaylight.yangtools.model</groupId>
       <artifactId>ietf-inet-types</artifactId>
     </dependency>
-    <dependency>
-      <groupId>org.reflections</groupId>
-      <artifactId>reflections</artifactId>
-      <scope>compile</scope>
-    </dependency>
     <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-api</artifactId>
       <artifactId>ietf-topology-l3-unicast-igp</artifactId>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>sal-test-model</artifactId>
+      <scope>test</scope>
+    </dependency>
     <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-simple</artifactId>
-      <version>${slf4j.version}</version>
       <scope>test</scope>
     </dependency>
   </dependencies>
index 17cd67a8576018485d3f1162dab89d51be0fcf15..018e26878c9873490d6c3ed88822edb78efe0280 100644 (file)
@@ -10,12 +10,10 @@ import org.opendaylight.controller.sal.core.api.Broker.ProviderSession;
 import org.opendaylight.controller.sal.core.api.Provider;
 import org.opendaylight.controller.sal.core.api.model.SchemaService;
 import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
-import org.osgi.framework.BundleContext;
 
 public class BindingAsyncDataBrokerImplModule extends
         org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractBindingAsyncDataBrokerImplModule implements
         Provider {
-    private BundleContext bundleContext;
 
     public BindingAsyncDataBrokerImplModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
             final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
@@ -42,25 +40,15 @@ public class BindingAsyncDataBrokerImplModule extends
 
         // FIXME: Switch this to DOM Broker registration which would not require
         // BundleContext when API are updated.
-        ProviderSession session = domBroker.registerProvider(this, getBundleContext());
+        ProviderSession session = domBroker.registerProvider(this, null);
         DOMDataBroker domDataBroker = session.getService(DOMDataBroker.class);
         SchemaService schemaService = session.getService(SchemaService.class);
         return new ForwardedBindingDataBroker(domDataBroker, mappingService, schemaService);
     }
 
-    // FIXME: Remove this when DOM Broker registration would not require
-    // BundleContext
-    @Deprecated
-    private BundleContext getBundleContext() {
-        return bundleContext;
-    }
 
-    // FIXME: Remove this when DOM Broker registration would not require
-    // BundleContext
-    @Deprecated
-    void setBundleContext(final BundleContext bundleContext) {
-        this.bundleContext = bundleContext;
-    }
+
+
 
     @Override
     public Collection<ProviderFunctionality> getProviderFunctionality() {
index 763e6ad3ca92e40e02a6e3c63a1ad2e96d46d747..a7c8843fcf3c48d1aa79fd85fbcc798a7b7c3efe 100644 (file)
@@ -9,29 +9,7 @@
 */
 package org.opendaylight.controller.config.yang.md.sal.binding.impl;
 
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.osgi.framework.BundleContext;
 
 public class BindingAsyncDataBrokerImplModuleFactory extends org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractBindingAsyncDataBrokerImplModuleFactory {
 
-
-
-
-    @Override
-    public BindingAsyncDataBrokerImplModule instantiateModule(final String instanceName,
-            final DependencyResolver dependencyResolver, final BindingAsyncDataBrokerImplModule oldModule,
-            final AutoCloseable oldInstance, final BundleContext bundleContext) {
-        BindingAsyncDataBrokerImplModule module = super.instantiateModule(instanceName, dependencyResolver, oldModule, oldInstance, bundleContext);
-        module.setBundleContext(bundleContext);
-        return module;
-    }
-
-    @Override
-    public BindingAsyncDataBrokerImplModule instantiateModule(final String instanceName,
-            final DependencyResolver dependencyResolver, final BundleContext bundleContext) {
-        // TODO Auto-generated method stub
-        BindingAsyncDataBrokerImplModule module = super.instantiateModule(instanceName, dependencyResolver, bundleContext);
-        module.setBundleContext(bundleContext);
-        return module;
-    }
 }
index 188272fb60c186f07b472805776df83ee12899e0..61e7a2e6a240d9e7ab98574f7dd1bee2058ed987 100644 (file)
@@ -1,96 +1,85 @@
-/*\r
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.\r
- *\r
- * This program and the accompanying materials are made available under the\r
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,\r
- * and is available at http://www.eclipse.org/legal/epl-v10.html\r
- */\r
-/**\r
- * Generated file\r
-\r
- * Generated from: yang module name: opendaylight-sal-binding-broker-impl  yang module local name: binding-broker-impl\r
- * Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator\r
- * Generated at: Wed Nov 20 17:33:01 CET 2013\r
- *\r
- * Do not modify this file unless it is present under src/main directory\r
- */\r
-package org.opendaylight.controller.config.yang.md.sal.binding.impl;\r
-\r
-import org.opendaylight.controller.sal.binding.codegen.impl.SingletonHolder;\r
-import org.opendaylight.controller.sal.binding.impl.RootBindingAwareBroker;\r
-import org.opendaylight.controller.sal.binding.impl.RpcProviderRegistryImpl;\r
-import org.opendaylight.controller.sal.binding.impl.forward.DomForwardedBindingBrokerImpl;\r
-import org.opendaylight.controller.sal.binding.impl.forward.DomForwardingUtils;\r
-import org.osgi.framework.BundleContext;\r
-\r
-/**\r
-*\r
-*/\r
-public final class BindingBrokerImplModule extends\r
-        org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractBindingBrokerImplModule {\r
-\r
-    private BundleContext bundleContext;\r
-\r
-    public BindingBrokerImplModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,\r
-            final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {\r
-        super(identifier, dependencyResolver);\r
-    }\r
-\r
-    public BindingBrokerImplModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,\r
-            final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,\r
-            final BindingBrokerImplModule oldModule, final java.lang.AutoCloseable oldInstance) {\r
-        super(identifier, dependencyResolver, oldModule, oldInstance);\r
-    }\r
-\r
-    @Override\r
-    public void validate() {\r
-        super.validate();\r
-    }\r
-\r
-    @Override\r
-    public java.lang.AutoCloseable createInstance() {\r
-\r
-        RootBindingAwareBroker broker;\r
-        if (DomForwardingUtils.isDomForwardedBroker(getDataBrokerDependency())) {\r
-            broker = createForwardedBroker();\r
-        } else {\r
-            broker = createStandaloneBroker();\r
-        }\r
-        broker.start();\r
-        return broker;\r
-    }\r
-\r
-    private RootBindingAwareBroker createStandaloneBroker() {\r
-        RootBindingAwareBroker broker = new RootBindingAwareBroker(getIdentifier().getInstanceName());\r
-\r
-        broker.setLegacyDataBroker(getDataBrokerDependency());\r
-        broker.setNotificationBroker(getNotificationServiceDependency());\r
-        broker.setRpcBroker(new RpcProviderRegistryImpl(broker.getIdentifier()));\r
-        // FIXME: Also set Async Data Broker\r
-        return broker;\r
-    }\r
-\r
-    private RootBindingAwareBroker createForwardedBroker() {\r
-        DomForwardedBindingBrokerImpl broker = new DomForwardedBindingBrokerImpl(getIdentifier().getInstanceName());\r
-\r
-        broker.setLegacyDataBroker(getDataBrokerDependency());\r
-        broker.setNotificationBroker(getNotificationServiceDependency());\r
-        broker.setRpcBroker(new RpcProviderRegistryImpl(broker.getIdentifier()));\r
-\r
-        broker.getMountManager().setDataCommitExecutor(SingletonHolder.getDefaultCommitExecutor());\r
-        broker.getMountManager().setNotificationExecutor(SingletonHolder.getDefaultNotificationExecutor());\r
-\r
-        // FIXME: Also set Async Data Broker\r
-        DomForwardingUtils.reuseForwardingFrom(broker, broker.getDataBroker());\r
-        broker.startForwarding();\r
-        return broker;\r
-    }\r
-\r
-    public BundleContext getBundleContext() {\r
-        return bundleContext;\r
-    }\r
-\r
-    public void setBundleContext(final BundleContext bundleContext) {\r
-        this.bundleContext = bundleContext;\r
-    }\r
-}\r
+/*
+ * 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 file
+
+ * Generated from: yang module name: opendaylight-sal-binding-broker-impl  yang module local name: binding-broker-impl
+ * Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator
+ * Generated at: Wed Nov 20 17:33:01 CET 2013
+ *
+ * Do not modify this file unless it is present under src/main directory
+ */
+package org.opendaylight.controller.config.yang.md.sal.binding.impl;
+
+import org.opendaylight.controller.sal.binding.codegen.impl.SingletonHolder;
+import org.opendaylight.controller.sal.binding.impl.RootBindingAwareBroker;
+import org.opendaylight.controller.sal.binding.impl.RpcProviderRegistryImpl;
+import org.opendaylight.controller.sal.binding.impl.forward.DomForwardedBindingBrokerImpl;
+import org.opendaylight.controller.sal.binding.impl.forward.DomForwardingUtils;
+
+/**
+*
+*/
+public final class BindingBrokerImplModule extends
+        org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractBindingBrokerImplModule {
+
+    public BindingBrokerImplModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+            final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
+        super(identifier, dependencyResolver);
+    }
+
+    public BindingBrokerImplModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+            final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,
+            final BindingBrokerImplModule oldModule, final java.lang.AutoCloseable oldInstance) {
+        super(identifier, dependencyResolver, oldModule, oldInstance);
+    }
+
+    @Override
+    public void validate() {
+        super.validate();
+    }
+
+    @Override
+    public java.lang.AutoCloseable createInstance() {
+
+        RootBindingAwareBroker broker;
+        if (DomForwardingUtils.isDomForwardedBroker(getDataBrokerDependency())) {
+            broker = createForwardedBroker();
+        } else {
+            broker = createStandaloneBroker();
+        }
+        broker.start();
+        return broker;
+    }
+
+    private RootBindingAwareBroker createStandaloneBroker() {
+        RootBindingAwareBroker broker = new RootBindingAwareBroker(getIdentifier().getInstanceName());
+
+        broker.setLegacyDataBroker(getDataBrokerDependency());
+        broker.setNotificationBroker(getNotificationServiceDependency());
+        broker.setRpcBroker(new RpcProviderRegistryImpl(broker.getIdentifier()));
+        broker.setDataBroker(getRootDataBrokerDependency());
+        return broker;
+    }
+
+    private RootBindingAwareBroker createForwardedBroker() {
+        DomForwardedBindingBrokerImpl broker = new DomForwardedBindingBrokerImpl(getIdentifier().getInstanceName());
+
+        broker.setLegacyDataBroker(getDataBrokerDependency());
+        broker.setNotificationBroker(getNotificationServiceDependency());
+        broker.setRpcBroker(new RpcProviderRegistryImpl(broker.getIdentifier()));
+
+        broker.getMountManager().setDataCommitExecutor(SingletonHolder.getDefaultCommitExecutor());
+        broker.getMountManager().setNotificationExecutor(SingletonHolder.getDefaultNotificationExecutor());
+
+        broker.setDataBroker(getRootDataBrokerDependency());
+        DomForwardingUtils.reuseForwardingFrom(broker, broker.getDataBroker());
+        broker.startForwarding();
+        return broker;
+    }
+}
index a11a7d67f5d4077006676dc476cf154e1de8ade8..181b568cf51e898a807053dbe16ab353fdfab2de 100644 (file)
 */
 package org.opendaylight.controller.config.yang.md.sal.binding.impl;
 
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.spi.Module;
-import org.osgi.framework.BundleContext;
 
 /**
 *
 */
 public class BindingBrokerImplModuleFactory extends org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractBindingBrokerImplModuleFactory {
 
-
-    @Override
-    public Module createModule(String instanceName, DependencyResolver dependencyResolver, BundleContext bundleContext) {
-        BindingBrokerImplModule module = (BindingBrokerImplModule) super.createModule(instanceName, dependencyResolver, bundleContext);
-        module.setBundleContext(bundleContext);
-        return module;
-    }
-
-    @Override
-    public Module createModule(String instanceName, DependencyResolver dependencyResolver,
-            DynamicMBeanWithInstance old, BundleContext bundleContext) throws Exception {
-        BindingBrokerImplModule module = (BindingBrokerImplModule) super.createModule(instanceName, dependencyResolver, old, bundleContext);
-        module.setBundleContext(bundleContext);
-        return module;
-    }
-
 }
index 7357926b9e6226a612bd0fc453dc28b737cff5b8..4a4e8000781381f906888369a8db0ac6b683e525 100644 (file)
@@ -5,8 +5,8 @@
  * 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.config.yang.md.sal.binding.impl;\r
-\r
+package org.opendaylight.controller.config.yang.md.sal.binding.impl;
+
 import java.util.concurrent.ExecutorService;
 
 import org.opendaylight.controller.sal.binding.codegen.impl.SingletonHolder;
@@ -16,85 +16,64 @@ import org.opendaylight.controller.sal.binding.impl.connect.dom.BindingIndepende
 import org.opendaylight.controller.sal.binding.impl.forward.DomForwardedDataBrokerImpl;
 import org.opendaylight.controller.sal.core.api.Broker.ProviderSession;
 import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-\r
-/**\r
-*\r
-*/\r
-public final class DataBrokerImplModule extends\r
-        org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractDataBrokerImplModule {\r
-\r
-    private BundleContext bundleContext;\r
-\r
-    public DataBrokerImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier,\r
-            org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {\r
-        super(identifier, dependencyResolver);\r
-    }\r
-\r
-    public DataBrokerImplModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier,\r
-            org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,\r
-            DataBrokerImplModule oldModule, java.lang.AutoCloseable oldInstance) {\r
-        super(identifier, dependencyResolver, oldModule, oldInstance);\r
-    }\r
-\r
-    @Override\r
-    public void validate() {\r
-        super.validate();\r
-    }\r
-\r
-    @Override\r
-    public java.lang.AutoCloseable createInstance() {\r
-        RootDataBrokerImpl dataBindingBroker;\r
-\r
-\r
-        ExecutorService listeningExecutor = SingletonHolder.getDefaultCommitExecutor();\r
-        BindingIndependentMappingService potentialMapping = resolveMappingServiceDependency();\r
-        if (getDomBrokerDependency() != null && potentialMapping != null) {\r
-\r
-            dataBindingBroker = createDomConnectedBroker(listeningExecutor,potentialMapping);\r
-        } else {\r
-            dataBindingBroker = createStandAloneBroker(listeningExecutor);\r
-        }\r
-        dataBindingBroker.registerRuntimeBean(getRootRuntimeBeanRegistratorWrapper());\r
-        dataBindingBroker.setNotificationExecutor(SingletonHolder.getDefaultChangeEventExecutor());\r
-        return dataBindingBroker;\r
-    }\r
-    private BindingIndependentMappingService resolveMappingServiceDependency() {\r
-        if(getMappingService() != null) {\r
-            return getMappingServiceDependency();\r
-        }\r
-\r
-        ServiceReference<BindingIndependentMappingService> potentialMappingService = bundleContext.getServiceReference(BindingIndependentMappingService.class);\r
-        if(potentialMappingService != null) {\r
-            return bundleContext.getService(potentialMappingService);\r
-        }\r
-        return null;\r
-    }\r
-\r
-    private RootDataBrokerImpl createStandAloneBroker(ExecutorService listeningExecutor) {\r
-        RootDataBrokerImpl broker = new RootDataBrokerImpl();\r
-        broker.setExecutor(listeningExecutor);\r
-        return broker;\r
-    }\r
-\r
-    private RootDataBrokerImpl createDomConnectedBroker(ExecutorService listeningExecutor, BindingIndependentMappingService mappingService) {\r
-        DomForwardedDataBrokerImpl forwardedBroker = new DomForwardedDataBrokerImpl();\r
-        forwardedBroker.setExecutor(listeningExecutor);\r
-        BindingIndependentConnector connector = BindingDomConnectorDeployer.createConnector(mappingService);\r
-        getDomBrokerDependency().registerProvider(forwardedBroker, getBundleContext());\r
-        ProviderSession domContext = forwardedBroker.getDomProviderContext();\r
-        forwardedBroker.setConnector(connector);\r
-        forwardedBroker.setDomProviderContext(domContext);\r
-        forwardedBroker.startForwarding();\r
-        return forwardedBroker;\r
-    }\r
-\r
-    public BundleContext getBundleContext() {\r
-        return bundleContext;\r
-    }\r
-\r
-    public void setBundleContext(BundleContext bundleContext2) {\r
-        this.bundleContext = bundleContext2;\r
-    }\r
-}\r
+
+/**
+*
+*/
+public final class DataBrokerImplModule extends
+        org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractDataBrokerImplModule {
+
+    public DataBrokerImplModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+            final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
+        super(identifier, dependencyResolver);
+    }
+
+    public DataBrokerImplModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+            final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,
+            final DataBrokerImplModule oldModule, final java.lang.AutoCloseable oldInstance) {
+        super(identifier, dependencyResolver, oldModule, oldInstance);
+    }
+
+    @Override
+    public void validate() {
+        super.validate();
+    }
+
+    @Override
+    public java.lang.AutoCloseable createInstance() {
+        RootDataBrokerImpl dataBindingBroker;
+
+
+        ExecutorService listeningExecutor = SingletonHolder.getDefaultCommitExecutor();
+        BindingIndependentMappingService potentialMapping = getMappingServiceDependency();
+        if (getDomBrokerDependency() != null && potentialMapping != null) {
+
+            dataBindingBroker = createDomConnectedBroker(listeningExecutor,potentialMapping);
+        } else {
+            dataBindingBroker = createStandAloneBroker(listeningExecutor);
+        }
+        dataBindingBroker.registerRuntimeBean(getRootRuntimeBeanRegistratorWrapper());
+        dataBindingBroker.setNotificationExecutor(SingletonHolder.getDefaultChangeEventExecutor());
+        return dataBindingBroker;
+    }
+
+
+    private RootDataBrokerImpl createStandAloneBroker(final ExecutorService listeningExecutor) {
+        RootDataBrokerImpl broker = new RootDataBrokerImpl();
+        broker.setExecutor(listeningExecutor);
+        return broker;
+    }
+
+    private RootDataBrokerImpl createDomConnectedBroker(final ExecutorService listeningExecutor, final BindingIndependentMappingService mappingService) {
+        DomForwardedDataBrokerImpl forwardedBroker = new DomForwardedDataBrokerImpl();
+        forwardedBroker.setExecutor(listeningExecutor);
+        BindingIndependentConnector connector = BindingDomConnectorDeployer.createConnector(mappingService);
+        getDomBrokerDependency().registerProvider(forwardedBroker, null);
+        ProviderSession domContext = forwardedBroker.getDomProviderContext();
+        forwardedBroker.setConnector(connector);
+        forwardedBroker.setDomProviderContext(domContext);
+        forwardedBroker.startForwarding();
+        return forwardedBroker;
+    }
+
+}
index 9ce3ebf73f26793089c171126e33db8c6d3d956d..d3fc5ac215d7c201e66e9dfdf6022cc12d1fe3eb 100644 (file)
@@ -7,10 +7,6 @@
  */
 package org.opendaylight.controller.config.yang.md.sal.binding.impl;
 
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.spi.Module;
-import org.osgi.framework.BundleContext;
 
 /**
 *
@@ -18,21 +14,4 @@ import org.osgi.framework.BundleContext;
 public class DataBrokerImplModuleFactory extends
         org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractDataBrokerImplModuleFactory {
 
-    @Override
-    public Module createModule(String instanceName, DependencyResolver dependencyResolver, BundleContext bundleContext) {
-        DataBrokerImplModule module = (DataBrokerImplModule) super.createModule(instanceName, dependencyResolver,
-                bundleContext);
-        module.setBundleContext(bundleContext);
-        return module;
-    }
-
-    @Override
-    public Module createModule(String instanceName, DependencyResolver dependencyResolver,
-            DynamicMBeanWithInstance old, BundleContext bundleContext) throws Exception {
-        DataBrokerImplModule module = (DataBrokerImplModule) super.createModule(instanceName, dependencyResolver, old,
-                bundleContext);
-        module.setBundleContext(bundleContext);
-        return module;
-    }
-
 }
index 7467e544fdc8e2577447da8c62fca6319b7e3d0c..0ea30f7e66a817f63c63cc81e20f3890170ea7b5 100644 (file)
@@ -19,7 +19,6 @@ import org.opendaylight.controller.sal.core.api.Broker.ProviderSession;
 import org.opendaylight.controller.sal.core.api.Provider;
 import org.opendaylight.controller.sal.core.api.model.SchemaService;
 import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
-import org.osgi.framework.BundleContext;
 
 import com.google.common.util.concurrent.ListeningExecutorService;
 
@@ -30,8 +29,6 @@ public final class ForwardedCompatibleDataBrokerImplModule extends
         org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractForwardedCompatibleDataBrokerImplModule
         implements Provider {
 
-    private BundleContext bundleContext;
-
     public ForwardedCompatibleDataBrokerImplModule(
             final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
             final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
@@ -57,7 +54,7 @@ public final class ForwardedCompatibleDataBrokerImplModule extends
         BindingIndependentMappingService mappingService = getBindingMappingServiceDependency();
 
         Broker domBroker = getDomAsyncBrokerDependency();
-        ProviderSession session = domBroker.registerProvider(this, getBundleContext());
+        ProviderSession session = domBroker.registerProvider(this, null);
         DOMDataBroker domDataBroker = session.getService(DOMDataBroker.class);
         SchemaService schemaService = session.getService(SchemaService.class);
         ForwardedBackwardsCompatibleDataBroker dataBroker = new ForwardedBackwardsCompatibleDataBroker(domDataBroker,
@@ -68,14 +65,6 @@ public final class ForwardedCompatibleDataBrokerImplModule extends
         return dataBroker;
     }
 
-    public BundleContext getBundleContext() {
-        return bundleContext;
-    }
-
-    public void setBundleContext(final BundleContext bundleContext2) {
-        this.bundleContext = bundleContext2;
-    }
-
     @Override
     public void onSessionInitiated(final ProviderSession session) {
 
index f01977503e8239128ac5b3bb022d6c4278bc863b..5b5fb45fd9904eb80ece3e9de0faa56351f6f796 100644 (file)
@@ -7,10 +7,6 @@
  */
 package org.opendaylight.controller.config.yang.md.sal.binding.impl;
 
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.spi.Module;
-import org.osgi.framework.BundleContext;
 
 
 /**
@@ -19,20 +15,4 @@ import org.osgi.framework.BundleContext;
 public class ForwardedCompatibleDataBrokerImplModuleFactory extends org.opendaylight.controller.config.yang.md.sal.binding.impl.AbstractForwardedCompatibleDataBrokerImplModuleFactory
 {
 
-
-    @Override
-    public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, final BundleContext bundleContext) {
-        ForwardedCompatibleDataBrokerImplModule module = (ForwardedCompatibleDataBrokerImplModule) super.createModule(instanceName, dependencyResolver, bundleContext);
-        module.setBundleContext(bundleContext);
-        return module;
-    }
-
-    @Override
-    public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
-            final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception {
-        ForwardedCompatibleDataBrokerImplModule module = (ForwardedCompatibleDataBrokerImplModule)  super.createModule(instanceName, dependencyResolver, old, bundleContext);
-        module.setBundleContext(bundleContext);
-        return module;
-    }
-
 }
index b09cd1c80a142e629493180a47640fb0a5d894a4..58d78a85dcee79f3eeff39640663dc82533f3aca 100644 (file)
@@ -7,14 +7,16 @@
  */
 package org.opendaylight.controller.md.sal.binding.impl;
 
+import java.util.ArrayList;
 import java.util.Collections;
+import java.util.Comparator;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;
 
-import org.opendaylight.controller.md.sal.binding.api.BindingDataChangeListener;
+import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
 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;
@@ -40,6 +42,7 @@ import org.slf4j.LoggerFactory;
 
 import com.google.common.base.Objects;
 import com.google.common.base.Optional;
+import com.google.common.collect.Iterables;
 
 public abstract class AbstractForwardedDataBroker implements Delegator<DOMDataBroker>, DomForwardedBroker,
         SchemaContextListener, AutoCloseable {
@@ -83,8 +86,8 @@ public abstract class AbstractForwardedDataBroker implements Delegator<DOMDataBr
         codec.onGlobalContextUpdated(ctx);
     }
 
-    public ListenerRegistration<BindingDataChangeListener> registerDataChangeListener(final LogicalDatastoreType store,
-            final InstanceIdentifier<?> path, final BindingDataChangeListener listener,
+    public ListenerRegistration<DataChangeListener> registerDataChangeListener(final LogicalDatastoreType store,
+            final InstanceIdentifier<?> path, final DataChangeListener listener,
             final DataChangeScope triggeringScope) {
         DOMDataChangeListener domDataChangeListener = new TranslatingDataChangeInvoker(store, path, listener,
                 triggeringScope);
@@ -97,8 +100,8 @@ public abstract class AbstractForwardedDataBroker implements Delegator<DOMDataBr
     protected Map<InstanceIdentifier<?>, DataObject> toBinding(
             final Map<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, ? extends NormalizedNode<?, ?>> normalized) {
         Map<InstanceIdentifier<?>, DataObject> newMap = new HashMap<>();
-        for (Map.Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, ? extends NormalizedNode<?, ?>> entry : normalized
-                .entrySet()) {
+
+        for (Map.Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, ? extends NormalizedNode<?, ?>> entry : sortedEntries(normalized)) {
             try {
                 Optional<Entry<InstanceIdentifier<? extends DataObject>, DataObject>> potential = getCodec().toBinding(
                         entry);
@@ -113,6 +116,21 @@ public abstract class AbstractForwardedDataBroker implements Delegator<DOMDataBr
         return newMap;
     }
 
+    private static <T> Iterable<Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier,T>> sortedEntries(final Map<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, T> map) {
+        ArrayList<Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, T>> entries = new ArrayList<>(map.entrySet());
+        Collections.sort(entries, new Comparator<Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, T>>() {
+
+            @Override
+            public int compare(final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, T> left,
+                    final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, T> right) {
+                int leftSize = Iterables.size(left.getKey().getPathArguments());
+                int rightSize = Iterables.size(right.getKey().getPathArguments());
+                return Integer.compare(leftSize, rightSize);
+            }
+        });
+        return entries;
+    }
+
     protected Set<InstanceIdentifier<?>> toBinding(
             final Set<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier> normalized) {
         Set<InstanceIdentifier<?>> hashSet = new HashSet<>();
@@ -143,13 +161,13 @@ public abstract class AbstractForwardedDataBroker implements Delegator<DOMDataBr
     }
 
     private class TranslatingDataChangeInvoker implements DOMDataChangeListener {
-        private final BindingDataChangeListener bindingDataChangeListener;
+        private final DataChangeListener bindingDataChangeListener;
         private final LogicalDatastoreType store;
         private final InstanceIdentifier<?> path;
         private final DataChangeScope triggeringScope;
 
         public TranslatingDataChangeInvoker(final LogicalDatastoreType store, final InstanceIdentifier<?> path,
-                final BindingDataChangeListener bindingDataChangeListener, final DataChangeScope triggeringScope) {
+                final DataChangeListener bindingDataChangeListener, final DataChangeScope triggeringScope) {
             this.store = store;
             this.path = path;
             this.bindingDataChangeListener = bindingDataChangeListener;
@@ -169,7 +187,7 @@ public abstract class AbstractForwardedDataBroker implements Delegator<DOMDataBr
 
         private Map<InstanceIdentifier<?>, DataObject> createdCache;
         private Map<InstanceIdentifier<?>, DataObject> updatedCache;
-        private Map<InstanceIdentifier<?>, ? extends DataObject> originalCache;
+        private Map<InstanceIdentifier<?>, DataObject> originalCache;
         private Set<InstanceIdentifier<?>> removedCache;
         private Optional<DataObject> originalDataCache;
         private Optional<DataObject> updatedDataCache;
@@ -207,7 +225,7 @@ public abstract class AbstractForwardedDataBroker implements Delegator<DOMDataBr
         }
 
         @Override
-        public Map<InstanceIdentifier<?>, ? extends DataObject> getOriginalData() {
+        public Map<InstanceIdentifier<?>, DataObject> getOriginalData() {
             if (originalCache == null) {
                 originalCache = Collections.unmodifiableMap(toBinding(domEvent.getOriginalData()));
             }
@@ -250,10 +268,10 @@ public abstract class AbstractForwardedDataBroker implements Delegator<DOMDataBr
         }
     }
 
-    private static class ListenerRegistrationImpl extends AbstractListenerRegistration<BindingDataChangeListener> {
+    private static class ListenerRegistrationImpl extends AbstractListenerRegistration<DataChangeListener> {
         private final ListenerRegistration<DOMDataChangeListener> registration;
 
-        public ListenerRegistrationImpl(final BindingDataChangeListener listener,
+        public ListenerRegistrationImpl(final DataChangeListener listener,
                 final ListenerRegistration<DOMDataChangeListener> registration) {
             super(listener);
             this.registration = registration;
index a935a33a5eb26ee13371554165db996f390469b8..a6d20c5c34cb06457ccaf8727c40980164fdefe4 100644 (file)
  */
 package org.opendaylight.controller.md.sal.binding.impl;
 
-import java.util.ArrayList;
-import java.util.EnumMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map.Entry;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeUnit;
-
-import javax.annotation.Nullable;
-
-import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
 import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationException;
-import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction;
-import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
-import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
 import org.opendaylight.yangtools.concepts.Delegator;
+import org.opendaylight.yangtools.concepts.Identifiable;
 import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Function;
 import com.google.common.base.Optional;
-import com.google.common.cache.Cache;
-import com.google.common.cache.CacheBuilder;
+import com.google.common.base.Preconditions;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
 
-public class AbstractForwardedTransaction<T extends AsyncTransaction<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>>>
-        implements Delegator<T> {
 
-    private static final Logger LOG = LoggerFactory.getLogger(AbstractForwardedTransaction.class);
+abstract class AbstractForwardedTransaction<T extends AsyncTransaction<InstanceIdentifier, NormalizedNode<?, ?>>>
+        implements Delegator<T>, Identifiable<Object> {
+
     private final T delegate;
-    private final static CacheBuilder<Object, Object> CACHE_BUILDER = CacheBuilder.newBuilder()
-            .expireAfterWrite(10, TimeUnit.MILLISECONDS).maximumSize(100);
     private final BindingToNormalizedNodeCodec codec;
-    private final EnumMap<LogicalDatastoreType, Cache<InstanceIdentifier<?>, DataObject>> cacheMap;
 
-    protected AbstractForwardedTransaction(final T delegate, final BindingToNormalizedNodeCodec codec) {
-        super();
-        this.delegate = delegate;
-        this.codec = codec;
+    public AbstractForwardedTransaction(final T delegateTx, final BindingToNormalizedNodeCodec codec) {
+        this.delegate = Preconditions.checkNotNull(delegateTx, "Delegate must not be null");
+        this.codec = Preconditions.checkNotNull(codec, "Codec must not be null");
+    }
 
-        this.cacheMap = new EnumMap<>(LogicalDatastoreType.class);
-        cacheMap.put(LogicalDatastoreType.OPERATIONAL, CACHE_BUILDER.<InstanceIdentifier<?>, DataObject> build());
-        cacheMap.put(LogicalDatastoreType.CONFIGURATION, CACHE_BUILDER.<InstanceIdentifier<?>, DataObject> build());
 
+    @Override
+    public final  Object getIdentifier() {
+        return delegate.getIdentifier();
     }
 
     @Override
-    public T getDelegate() {
+    public final  T getDelegate() {
         return delegate;
     }
 
-    protected final BindingToNormalizedNodeCodec getCodec() {
-        return codec;
-    }
-
-    protected ListenableFuture<Optional<DataObject>> transformFuture(final LogicalDatastoreType store,
-            final InstanceIdentifier<?> path, final ListenableFuture<Optional<NormalizedNode<?, ?>>> future) {
-        return Futures.transform(future, new Function<Optional<NormalizedNode<?, ?>>, Optional<DataObject>>() {
-            @Nullable
-            @Override
-            public Optional<DataObject> apply(@Nullable final Optional<NormalizedNode<?, ?>> normalizedNode) {
-                if (normalizedNode.isPresent()) {
-                    final DataObject dataObject;
-                    try {
-                        dataObject = codec.toBinding(path, normalizedNode.get());
-                    } catch (DeserializationException e) {
-                        LOG.warn("Failed to create dataobject from node {}", normalizedNode.get(), e);
-                        throw new IllegalStateException("Failed to create dataobject", e);
-                    }
-
-                    if (dataObject != null) {
-                        updateCache(store, path, dataObject);
-                        return Optional.of(dataObject);
-                    }
-                }
-                return Optional.absent();
-            }
-        });
-    }
-
-    protected void doPut(final DOMDataWriteTransaction writeTransaction, final LogicalDatastoreType store,
-            final InstanceIdentifier<?> path, final DataObject data) {
-        invalidateCache(store, path);
-        final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>> normalized = codec
-                .toNormalizedNode(path, data);
-        writeTransaction.put(store, normalized.getKey(), normalized.getValue());
-    }
-
-    protected void doPutWithEnsureParents(final DOMDataReadWriteTransaction writeTransaction,
-            final LogicalDatastoreType store, final InstanceIdentifier<?> path, final DataObject data) {
-        invalidateCache(store, path);
-        final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>> normalized = codec
-                .toNormalizedNode(path, data);
-
-        final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalizedPath = normalized.getKey();
-        ensureParentsByMerge(writeTransaction, store, normalizedPath, path);
-        LOG.debug("Tx: {} : Putting data {}", getDelegate().getIdentifier(), normalizedPath);
-        writeTransaction.put(store, normalizedPath, normalized.getValue());
-    }
-
-    protected void doMergeWithEnsureParents(final DOMDataReadWriteTransaction writeTransaction,
-            final LogicalDatastoreType store, final InstanceIdentifier<?> path, final DataObject data) {
-        invalidateCache(store, path);
-        final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>> normalized = codec
-                .toNormalizedNode(path, data);
-
-        final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalizedPath = normalized.getKey();
-        ensureParentsByMerge(writeTransaction, store, normalizedPath, path);
-        LOG.debug("Tx: {} : Merge data {}",getDelegate().getIdentifier(),normalizedPath);
-        writeTransaction.merge(store, normalizedPath, normalized.getValue());
+    @SuppressWarnings("unchecked")
+    protected final <S extends AsyncTransaction<InstanceIdentifier, NormalizedNode<?, ?>>> S getDelegateChecked(final Class<S> txType) {
+        Preconditions.checkState(txType.isInstance(delegate));
+        return (S) delegate;
     }
 
-    private void ensureParentsByMerge(final DOMDataReadWriteTransaction writeTransaction,
-            final LogicalDatastoreType store,
-            final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalizedPath,
-            final InstanceIdentifier<?> path) {
-        List<PathArgument> currentArguments = new ArrayList<>();
-        DataNormalizationOperation<?> currentOp = codec.getDataNormalizer().getRootOperation();
-        Iterator<PathArgument> iterator = normalizedPath.getPath().iterator();
-        while (iterator.hasNext()) {
-            PathArgument currentArg = iterator.next();
-            try {
-                currentOp = currentOp.getChild(currentArg);
-            } catch (DataNormalizationException e) {
-                throw new IllegalArgumentException(String.format("Invalid child encountered in path %s", path), e);
-            }
-            currentArguments.add(currentArg);
-            org.opendaylight.yangtools.yang.data.api.InstanceIdentifier currentPath = new org.opendaylight.yangtools.yang.data.api.InstanceIdentifier(
-                    currentArguments);
-
-            final Optional<NormalizedNode<?, ?>> d;
-            try {
-                d = writeTransaction.read(store, currentPath).get();
-            } catch (InterruptedException | ExecutionException e) {
-                LOG.error("Failed to read pre-existing data from store {} path {}", store, currentPath, e);
-                throw new IllegalStateException("Failed to read pre-existing data", e);
-            }
-
-            if (!d.isPresent() && iterator.hasNext()) {
-                writeTransaction.merge(store, currentPath, currentOp.createDefault(currentArg));
-            }
-        }
-    }
-
-    protected void doMerge(final DOMDataWriteTransaction writeTransaction, final LogicalDatastoreType store,
-            final InstanceIdentifier<?> path, final DataObject data) {
-        invalidateCache(store, path);
-        final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>> normalized = codec
-                .toNormalizedNode(path, data);
-        writeTransaction.merge(store, normalized.getKey(), normalized.getValue());
-    }
-
-    protected void doDelete(final DOMDataWriteTransaction writeTransaction, final LogicalDatastoreType store,
-            final InstanceIdentifier<?> path) {
-        invalidateCache(store, path);
-        final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized = codec.toNormalized(path);
-        writeTransaction.delete(store, normalized);
-    }
-
-    protected ListenableFuture<RpcResult<TransactionStatus>> doCommit(final DOMDataWriteTransaction writeTransaction) {
-        return writeTransaction.commit();
-    }
-
-    protected void doCancel(final DOMDataWriteTransaction writeTransaction) {
-        writeTransaction.cancel();
-    }
-
-    protected ListenableFuture<Optional<DataObject>> doRead(final DOMDataReadTransaction readTransaction,
-            final LogicalDatastoreType store, final InstanceIdentifier<?> path) {
-        final DataObject dataObject = getFromCache(store, path);
-        if (dataObject == null) {
-            final ListenableFuture<Optional<NormalizedNode<?, ?>>> future = readTransaction.read(store,
-                    codec.toNormalized(path));
-            return transformFuture(store, path, future);
-        } else {
-            return Futures.immediateFuture(Optional.of(dataObject));
-        }
-    }
-
-    private DataObject getFromCache(final LogicalDatastoreType store, final InstanceIdentifier<?> path) {
-        Cache<InstanceIdentifier<?>, DataObject> cache = cacheMap.get(store);
-        if (cache != null) {
-            return cache.getIfPresent(path);
-        }
-        return null;
-    }
-
-    private void updateCache(final LogicalDatastoreType store, final InstanceIdentifier<?> path,
-            final DataObject dataObject) {
-        // Check if cache exists. If not create one.
-        Cache<InstanceIdentifier<?>, DataObject> cache = cacheMap.get(store);
-        if (cache == null) {
-            cache = CacheBuilder.newBuilder().maximumSize(1000).expireAfterWrite(1, TimeUnit.MINUTES).build();
-
-        }
-
-        cache.put(path, dataObject);
+    protected final BindingToNormalizedNodeCodec getCodec() {
+        return codec;
     }
 
-    private void invalidateCache(final LogicalDatastoreType store, final InstanceIdentifier<?> path) {
-        // FIXME: Optimization: invalidate only parents and children of path
-        Cache<InstanceIdentifier<?>, DataObject> cache = cacheMap.get(store);
-        cache.invalidateAll();
-        LOG.trace("Cache invalidated");
+    protected final <T extends DataObject> ListenableFuture<Optional<T>> doRead(final DOMDataReadTransaction readTx,
+            final LogicalDatastoreType store, final org.opendaylight.yangtools.yang.binding.InstanceIdentifier<T> path) {
+        return Futures.transform(readTx.read(store, codec.toNormalized(path)), codec.deserializeFunction(path));
     }
-
 }
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractReadWriteTransaction.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractReadWriteTransaction.java
new file mode 100644 (file)
index 0000000..3988bc6
--- /dev/null
@@ -0,0 +1,89 @@
+/*
+ * 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;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.concurrent.ExecutionException;
+
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationException;
+import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Optional;
+
+public class AbstractReadWriteTransaction extends AbstractWriteTransaction<DOMDataReadWriteTransaction> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(AbstractReadWriteTransaction.class);
+
+    public AbstractReadWriteTransaction(final DOMDataReadWriteTransaction delegate, final BindingToNormalizedNodeCodec codec) {
+        super(delegate, codec);
+    }
+
+    protected final void doPutWithEnsureParents(final LogicalDatastoreType store, final InstanceIdentifier<?> path, final DataObject data) {
+        final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>> normalized = getCodec()
+                .toNormalizedNode(path, data);
+
+        final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalizedPath = normalized.getKey();
+        ensureParentsByMerge(store, normalizedPath, path);
+        LOG.debug("Tx: {} : Putting data {}", getDelegate().getIdentifier(), normalizedPath);
+        doPut(store, path, data);
+    }
+
+    protected final void doMergeWithEnsureParents(final LogicalDatastoreType store, final InstanceIdentifier<?> path, final DataObject data) {
+        final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>> normalized = getCodec()
+                .toNormalizedNode(path, data);
+
+        final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalizedPath = normalized.getKey();
+        ensureParentsByMerge(store, normalizedPath, path);
+        LOG.debug("Tx: {} : Merge data {}", getDelegate().getIdentifier(), normalizedPath);
+        doMerge(store, path, data);
+    }
+
+    private final void ensureParentsByMerge(final LogicalDatastoreType store,
+            final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalizedPath,
+            final InstanceIdentifier<?> path) {
+        List<PathArgument> currentArguments = new ArrayList<>();
+        DataNormalizationOperation<?> currentOp = getCodec().getDataNormalizer().getRootOperation();
+        Iterator<PathArgument> iterator = normalizedPath.getPathArguments().iterator();
+        while (iterator.hasNext()) {
+            PathArgument currentArg = iterator.next();
+            try {
+                currentOp = currentOp.getChild(currentArg);
+            } catch (DataNormalizationException e) {
+                throw new IllegalArgumentException(String.format("Invalid child encountered in path %s", path), e);
+            }
+            currentArguments.add(currentArg);
+            org.opendaylight.yangtools.yang.data.api.InstanceIdentifier currentPath = org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.create(
+                    currentArguments);
+
+            final Optional<NormalizedNode<?, ?>> d;
+            try {
+                d = getDelegate().read(store, currentPath).get();
+            } catch (InterruptedException | ExecutionException e) {
+                LOG.error("Failed to read pre-existing data from store {} path {}", store, currentPath, e);
+                throw new IllegalStateException("Failed to read pre-existing data", e);
+            }
+
+            if (!d.isPresent() && iterator.hasNext()) {
+                getDelegate().merge(store, currentPath, currentOp.createDefault(currentArg));
+            }
+        }
+    }
+
+
+}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractWriteTransaction.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/AbstractWriteTransaction.java
new file mode 100644 (file)
index 0000000..9eceeb1
--- /dev/null
@@ -0,0 +1,133 @@
+/*
+ * 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;
+
+import java.util.Collections;
+import java.util.Map.Entry;
+
+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.dom.api.DOMDataWriteTransaction;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.Identifiable;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Optional;
+import com.google.common.collect.Iterables;
+import com.google.common.util.concurrent.ListenableFuture;
+
+/**
+ *
+ * Abstract Base Transaction for transactions which are backed by
+ * {@link DOMDataWriteTransaction}
+ */
+public class AbstractWriteTransaction<T extends DOMDataWriteTransaction> extends
+        AbstractForwardedTransaction<T> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(AbstractWriteTransaction.class);
+
+    protected AbstractWriteTransaction(final T delegate,
+            final BindingToNormalizedNodeCodec codec) {
+        super(delegate, codec);
+    }
+
+    protected final void doPut(final LogicalDatastoreType store,
+            final InstanceIdentifier<?> path, final DataObject data) {
+       final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>> normalized = getCodec()
+                .toNormalizedNode(path, data);
+        ensureListParentIfNeeded(store,path,normalized);
+        getDelegate().put(store, normalized.getKey(), normalized.getValue());
+    }
+
+
+    /**
+     *
+     * Ensures list parent if item is list, otherwise noop.
+     *
+     * <p>
+     * One of properties of binding specification is that it is imposible
+     * to represent list as a whole and thus it is impossible to write
+     * empty variation of MapNode without creating parent node, with
+     * empty list.
+     *
+     * <p>
+     * This actually makes writes such as
+     * <pre>
+     * put("Nodes", new NodesBuilder().build());
+     * put("Nodes/Node[key]", new NodeBuilder().setKey("key").build());
+     * </pre>
+     * To result in three DOM operations:
+     * <pre>
+     * put("/nodes",domNodes);
+     * merge("/nodes/node",domNodeList);
+     * put("/nodes/node/node[key]",domNode);
+     * </pre>
+     *
+     *
+     * In order to allow that to be inserted if necessary, if we know
+     * item is list item, we will try to merge empty MapNode or OrderedNodeMap
+     * to ensure list exists.
+     *
+     * @param store Data Store type
+     * @param path Path to data (Binding Aware)
+     * @param normalized Normalized version of data to be written
+     */
+    private void ensureListParentIfNeeded(final LogicalDatastoreType store, final InstanceIdentifier<?> path,
+            final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>> normalized) {
+        if(Identifiable.class.isAssignableFrom(path.getTargetType())) {
+            org.opendaylight.yangtools.yang.data.api.InstanceIdentifier parentMapPath = getParent(normalized.getKey()).get();
+            NormalizedNode<?, ?> emptyParent = getCodec().getDefaultNodeFor(parentMapPath);
+            getDelegate().merge(store, parentMapPath, emptyParent);
+        }
+
+    }
+
+    // FIXME (should be probaly part of InstanceIdentifier)
+    protected static Optional<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier> getParent(
+            final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier child) {
+
+        Iterable<PathArgument> mapEntryItemPath = child.getPathArguments();
+        int parentPathSize = Iterables.size(mapEntryItemPath) - 1;
+        if(parentPathSize > 1) {
+            return Optional.of(org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.create(Iterables.limit(mapEntryItemPath,  parentPathSize)));
+        } else if(parentPathSize == 0) {
+            return Optional.of(org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.create(Collections.<PathArgument>emptyList()));
+        } else {
+            return Optional.absent();
+        }
+    }
+
+    protected final void doMerge(final LogicalDatastoreType store,
+            final InstanceIdentifier<?> path, final DataObject data) {
+
+        final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>> normalized = getCodec()
+                .toNormalizedNode(path, data);
+        ensureListParentIfNeeded(store,path,normalized);
+        getDelegate().merge(store, normalized.getKey(), normalized.getValue());
+    }
+
+    protected final void doDelete(final LogicalDatastoreType store,
+            final InstanceIdentifier<?> path) {
+        final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized = getCodec().toNormalized(path);
+        getDelegate().delete(store, normalized);
+    }
+
+    protected final ListenableFuture<RpcResult<TransactionStatus>> doCommit() {
+        return getDelegate().commit();
+    }
+
+    protected final boolean doCancel() {
+        return getDelegate().cancel();
+    }
+
+}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/BindingDataReadTransactionImpl.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/BindingDataReadTransactionImpl.java
new file mode 100644 (file)
index 0000000..bb94204
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * 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;
+
+import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.ListenableFuture;
+
+class BindingDataReadTransactionImpl extends AbstractForwardedTransaction<DOMDataReadOnlyTransaction> implements
+        ReadOnlyTransaction {
+
+    protected BindingDataReadTransactionImpl(final DOMDataReadOnlyTransaction delegate,
+            final BindingToNormalizedNodeCodec codec) {
+        super(delegate, codec);
+    }
+
+    @Override
+    public <T extends DataObject> ListenableFuture<Optional<T>> read(final LogicalDatastoreType store,
+            final InstanceIdentifier<T> path) {
+        return doRead(getDelegate(),store, path);
+    }
+
+    @Override
+    public void close() {
+        getDelegate().close();
+    }
+
+}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/BindingDataReadWriteTransactionImpl.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/BindingDataReadWriteTransactionImpl.java
new file mode 100644 (file)
index 0000000..c8b9d93
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * 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;
+
+import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.ListenableFuture;
+
+class BindingDataReadWriteTransactionImpl extends
+        BindingDataWriteTransactionImpl<DOMDataReadWriteTransaction> implements ReadWriteTransaction {
+
+    protected BindingDataReadWriteTransactionImpl(final DOMDataReadWriteTransaction delegate,
+            final BindingToNormalizedNodeCodec codec) {
+        super(delegate, codec);
+    }
+
+    @Override
+    public <T extends DataObject> ListenableFuture<Optional<T>> read(final LogicalDatastoreType store,
+            final InstanceIdentifier<T> path) {
+        return doRead(getDelegate(), store, path);
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/BindingDataWriteTransactionImpl.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/BindingDataWriteTransactionImpl.java
new file mode 100644 (file)
index 0000000..a62319b
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * 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;
+
+import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
+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.dom.api.DOMDataWriteTransaction;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+
+import com.google.common.util.concurrent.ListenableFuture;
+
+class BindingDataWriteTransactionImpl<T extends DOMDataWriteTransaction> extends
+        AbstractWriteTransaction<T> implements WriteTransaction {
+
+    protected BindingDataWriteTransactionImpl(final T delegateTx, final BindingToNormalizedNodeCodec codec) {
+        super(delegateTx, codec);
+    }
+
+
+
+    @Override
+    public void put(final LogicalDatastoreType store, final InstanceIdentifier<?> path, final DataObject data) {
+        doPut(store, path, data);
+    }
+
+    @Override
+    public void merge(final LogicalDatastoreType store, final InstanceIdentifier<?> path, final DataObject data) {
+        doMerge(store, path, data);
+    }
+
+    @Override
+    public void delete(final LogicalDatastoreType store, final InstanceIdentifier<?> path) {
+        doDelete( store, path);
+    }
+
+    @Override
+    public ListenableFuture<RpcResult<TransactionStatus>> commit() {
+        return doCommit();
+    }
+
+    @Override
+    public boolean cancel() {
+        return doCancel();
+    }
+}
\ No newline at end of file
index f1be5c6922ecda45cc75f343b3f6355e402e013d..f8c1cf6b99f4dfd7664251db168b0f59eddce557 100644 (file)
@@ -8,23 +8,25 @@
 package org.opendaylight.controller.md.sal.binding.impl;
 
 import java.lang.reflect.Method;
-import java.lang.reflect.Type;
 import java.util.AbstractMap.SimpleEntry;
-import java.util.LinkedList;
-import java.util.List;
+import java.util.HashSet;
+import java.util.Iterator;
 import java.util.Map.Entry;
+import java.util.Set;
+
+import javax.annotation.Nullable;
 
 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationException;
 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation;
 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
 import org.opendaylight.yangtools.yang.binding.Augmentation;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
+import org.opendaylight.yangtools.yang.binding.BindingMapping;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
+import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
-import org.opendaylight.yangtools.yang.binding.util.ClassLoaderUtils;
 import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.QNameModule;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.AugmentationIdentifier;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
@@ -37,13 +39,18 @@ import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
 import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.base.Function;
 import com.google.common.base.Optional;
-import com.google.common.base.Supplier;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 
@@ -75,7 +82,7 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
 
     public Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>> toNormalizedNode(
             final InstanceIdentifier<? extends DataObject> bindingPath, final DataObject bindingObject) {
-        return toNormalizedNode(toEntry(bindingPath, bindingObject));
+        return toNormalizedNode(toBindingEntry(bindingPath, bindingObject));
 
     }
 
@@ -87,17 +94,16 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
                 .toNormalized(legacyEntry);
         LOG.trace("Serialization of {}, Legacy Representation: {}, Normalized Representation: {}", binding,
                 legacyEntry, normalizedEntry);
-        if (Augmentation.class.isAssignableFrom(binding.getKey().getTargetType())) {
+        if (isAugmentation(binding.getKey().getTargetType())) {
 
             for (DataContainerChild<? extends PathArgument, ?> child : ((DataContainerNode<?>) normalizedEntry
                     .getValue()).getValue()) {
                 if (child instanceof AugmentationNode) {
                     ImmutableList<PathArgument> childArgs = ImmutableList.<PathArgument> builder()
-                            .addAll(normalizedEntry.getKey().getPath()).add(child.getIdentifier()).build();
-                    org.opendaylight.yangtools.yang.data.api.InstanceIdentifier childPath = new org.opendaylight.yangtools.yang.data.api.InstanceIdentifier(
-                            childArgs);
-                    return new SimpleEntry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>>(
-                            childPath, child);
+                            .addAll(normalizedEntry.getKey().getPathArguments()).add(child.getIdentifier()).build();
+                    org.opendaylight.yangtools.yang.data.api.InstanceIdentifier childPath = org.opendaylight.yangtools.yang.data.api.InstanceIdentifier
+                            .create(childArgs);
+                    return toDOMEntry(childPath, child);
                 }
             }
 
@@ -117,9 +123,9 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
      */
     public Optional<InstanceIdentifier<? extends DataObject>> toBinding(
             final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized)
-            throws DeserializationException {
+                    throws DeserializationException {
 
-        PathArgument lastArgument = Iterables.getLast(normalized.getPath());
+        PathArgument lastArgument = Iterables.getLast(normalized.getPathArguments());
         // Used instance-identifier codec do not support serialization of last
         // path
         // argument if it is AugmentationIdentifier (behaviour expected by old
@@ -134,7 +140,7 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
 
     private Optional<InstanceIdentifier<? extends DataObject>> toBindingAugmented(
             final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized)
-            throws DeserializationException {
+                    throws DeserializationException {
         Optional<InstanceIdentifier<? extends DataObject>> potential = toBindingImpl(normalized);
         // Shorthand check, if codec already supports deserialization
         // of AugmentationIdentifier we will return
@@ -143,7 +149,7 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
         }
 
         int normalizedCount = getAugmentationCount(normalized);
-        AugmentationIdentifier lastArgument = (AugmentationIdentifier) Iterables.getLast(normalized.getPath());
+        AugmentationIdentifier lastArgument = (AugmentationIdentifier) Iterables.getLast(normalized.getPathArguments());
 
         // Here we employ small trick - Binding-aware Codec injects an pointer
         // to augmentation class
@@ -151,9 +157,7 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
         // path.
         LOG.trace("Looking for candidates to match {}", normalized);
         for (QName child : lastArgument.getPossibleChildNames()) {
-            org.opendaylight.yangtools.yang.data.api.InstanceIdentifier childPath = new org.opendaylight.yangtools.yang.data.api.InstanceIdentifier(
-                    ImmutableList.<PathArgument> builder().addAll(normalized.getPath()).add(new NodeIdentifier(child))
-                            .build());
+            org.opendaylight.yangtools.yang.data.api.InstanceIdentifier childPath = normalized.node(child);
             try {
                 if (isNotRepresentable(childPath)) {
                     LOG.trace("Path {} is not BI-representable, skipping it", childPath);
@@ -186,7 +190,7 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
 
     private Optional<InstanceIdentifier<? extends DataObject>> toBindingImpl(
             final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized)
-            throws DeserializationException {
+                    throws DeserializationException {
         org.opendaylight.yangtools.yang.data.api.InstanceIdentifier legacyPath;
 
         try {
@@ -205,10 +209,10 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
     private boolean isNotRepresentable(final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized)
             throws DataNormalizationException {
         DataNormalizationOperation<?> op = findNormalizationOperation(normalized);
-        ifop.isMixin() && op.getIdentifier() instanceof NodeIdentifier) {
+        if (op.isMixin() && op.getIdentifier() instanceof NodeIdentifier) {
             return true;
         }
-        if(op.isLeaf()) {
+        if (op.isLeaf()) {
             return true;
         }
         return false;
@@ -216,21 +220,27 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
 
     private DataNormalizationOperation<?> findNormalizationOperation(
             final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized)
-            throws DataNormalizationException {
+                    throws DataNormalizationException {
         DataNormalizationOperation<?> current = legacyToNormalized.getRootOperation();
-        for (PathArgument arg : normalized.getPath()) {
+        for (PathArgument arg : normalized.getPathArguments()) {
             current = current.getChild(arg);
         }
         return current;
     }
 
-    private static final Entry<org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject>, DataObject> toEntry(
+    private static final Entry<org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject>, DataObject> toBindingEntry(
             final org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject> key,
             final DataObject value) {
         return new SimpleEntry<org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject>, DataObject>(
                 key, value);
     }
 
+    private static final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>> toDOMEntry(
+            final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier key, final NormalizedNode<?, ?> value) {
+        return new SimpleEntry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>>(key,
+                value);
+    }
+
     public DataObject toBinding(final InstanceIdentifier<?> path, final NormalizedNode<?, ?> normalizedNode)
             throws DeserializationException {
         CompositeNode legacy = null;
@@ -254,7 +264,7 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
 
     public Optional<Entry<org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject>, DataObject>> toBinding(
             final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, ? extends NormalizedNode<?, ?>> normalized)
-            throws DeserializationException {
+                    throws DeserializationException {
         Optional<InstanceIdentifier<? extends DataObject>> potentialPath = toBinding(normalized.getKey());
         if (potentialPath.isPresent()) {
             InstanceIdentifier<? extends DataObject> bindingPath = potentialPath.get();
@@ -262,7 +272,7 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
             if (bindingData == null) {
                 LOG.warn("Failed to deserialize {} to Binding format. Binding path is: {}", normalized, bindingPath);
             }
-            return Optional.of(toEntry(bindingPath, bindingData));
+            return Optional.of(toBindingEntry(bindingPath, bindingData));
         } else {
             return Optional.absent();
         }
@@ -281,38 +291,166 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
         if (isAugmentationIdentifier(processed)) {
             return processed;
         }
-        // Here we employ small trick - DataNormalizer injects augmentation
-        // identifier if child is
-        // also part of the path (since using a child we can safely identify
-        // augmentation)
-        // so, we scan augmentation for children add it to path
-        // and use original algorithm, then shorten it to last augmentation
-        for (@SuppressWarnings("rawtypes")
-        Class augChild : getAugmentationChildren(augPath.getTargetType())) {
+        Optional<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier> additionalSerialized;
+        additionalSerialized = toNormalizedAugmentedUsingChildContainers(augPath, processed);
+
+        if (additionalSerialized.isPresent()) {
+            return additionalSerialized.get();
+        }
+        additionalSerialized = toNormalizedAugmentedUsingChildLeafs(augPath, processed);
+        if (additionalSerialized.isPresent()) {
+            return additionalSerialized.get();
+        }
+        throw new IllegalStateException("Unabled to construct augmentation identfier for " + augPath);
+    }
+
+    /**
+     * Tries to find correct augmentation identifier using children leafs
+     *
+     * This method uses normalized Instance Identifier of parent node to fetch
+     * schema and {@link BindingReflections#getModuleInfo(Class)} to learn about
+     * augmentation namespace, specificly, in which module it was defined.
+     *
+     * Then it uses it to filter all available augmentations for parent by
+     * module. After that it walks augmentations in particular module and
+     * pick-up first which at least one leaf name matches supplied augmentation.
+     * We could do this safely since YANG explicitly states that no any existing
+     * augmentations must differ in leaf fully qualified names.
+     *
+     *
+     * @param augPath
+     *            Binding Aware Path which ends with augment
+     * @param parentPath
+     *            Processed path
+     * @return
+     */
+    private Optional<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier> toNormalizedAugmentedUsingChildLeafs(
+            final InstanceIdentifier<?> augPath,
+            final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier parentPath) {
+        try {
+            DataNormalizationOperation<?> parentOp = legacyToNormalized.getOperation(parentPath);
+            if(!parentOp.getDataSchemaNode().isPresent()) {
+                return Optional.absent();
+            }
+            DataSchemaNode parentSchema = parentOp.getDataSchemaNode().get();
+            if (parentSchema instanceof AugmentationTarget) {
+                Set<AugmentationSchema> augmentations = ((AugmentationTarget) parentSchema).getAvailableAugmentations();
+                LOG.info("Augmentations for {}, {}", augPath, augmentations);
+                Optional<AugmentationSchema> schema = findAugmentation(augPath.getTargetType(), augmentations);
+                if (schema.isPresent()) {
+                    AugmentationIdentifier augmentationIdentifier = DataNormalizationOperation
+                            .augmentationIdentifierFrom(schema.get());
+                    return Optional.of(parentPath.node(augmentationIdentifier));
+                }
+            }
+        } catch (DataNormalizationException e) {
+            throw new IllegalArgumentException(e);
+        }
+        return Optional.absent();
+    }
+
+    /**
+     * Creates instance identifier for augmentation child, tries to serialize it
+     * Instance Identifier is then shortened to last augmentation.
+     *
+     * This is for situations, where underlying codec is implementing hydrogen
+     * style DOM APIs (which did not supported {@link AugmentationIdentifier}.)
+     *
+     * @param augPath
+     * @param parentPath
+     *            Path to parent node
+     * @return
+     */
+    @SuppressWarnings("rawtypes")
+    private Optional<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier> toNormalizedAugmentedUsingChildContainers(
+            final InstanceIdentifier<?> augPath,
+            final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier parentPath) {
+        for (Class augChild : BindingReflections.getChildrenClasses(augPath.getTargetType())) {
             @SuppressWarnings("unchecked")
             InstanceIdentifier<?> childPath = augPath.child(augChild);
             org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized = toNormalizedImpl(childPath);
-            org.opendaylight.yangtools.yang.data.api.InstanceIdentifier potentialDiscovered = shortenToLastAugmentation(normalized);
+            org.opendaylight.yangtools.yang.data.api.InstanceIdentifier potentialDiscovered = shortenToLastAugmentation(
+                    normalized, parentPath);
             if (potentialDiscovered != null) {
-                return potentialDiscovered;
+                return Optional.of(potentialDiscovered);
             }
         }
-        return processed;
+        return Optional.absent();
+    }
+
+    private Optional<AugmentationSchema> findAugmentation(final Class<?> targetType,
+            final Set<AugmentationSchema> augmentations) {
+        YangModuleInfo moduleInfo;
+        try {
+            moduleInfo = BindingReflections.getModuleInfo(targetType);
+        } catch (Exception e) {
+            throw new IllegalStateException(e);
+        }
+        Iterable<AugmentationSchema> filtered = filteredByModuleInfo(augmentations,
+                BindingReflections.getModuleQName(moduleInfo).getModule());
+        filtered.toString();
+        Set<String> targetTypeGetters = getYangModeledGetters(targetType);
+        for (AugmentationSchema schema : filtered) {
+            for (DataSchemaNode child : schema.getChildNodes()) {
+                String getterName = "get" + BindingMapping.getClassName(child.getQName());
+                if (targetTypeGetters.contains(getterName)) {
+                    return Optional.of(schema);
+                }
+            }
+        }
+        return Optional.absent();
+    }
+
+    private static Iterable<AugmentationSchema> filteredByModuleInfo(final Iterable<AugmentationSchema> augmentations,
+            final QNameModule module) {
+        return Iterables.filter(augmentations, new Predicate<AugmentationSchema>() {
+            @Override
+            public boolean apply(final AugmentationSchema schema) {
+                final Set<DataSchemaNode> childNodes = schema.getChildNodes();
+                return !schema.getChildNodes().isEmpty()
+                        && module.equals(Iterables.get(childNodes, 0).getQName().getModule());
+            }
+        });
+    }
+
+    public static final Set<String> getYangModeledGetters(final Class<?> targetType) {
+        HashSet<String> ret = new HashSet<String>();
+        for (Method method : targetType.getMethods()) {
+            if (isYangModeledGetter(method)) {
+                ret.add(method.getName());
+            }
+        }
+        return ret;
+    }
+
+    /**
+     *
+     * Returns true if supplied method represent getter for YANG modeled value
+     *
+     * @param method
+     *            Method to be tested
+     * @return true if method represent getter for YANG Modeled value.
+     */
+    private static final boolean isYangModeledGetter(final Method method) {
+        return !method.getName().equals("getClass") && !method.getName().equals("getImplementedInterface")
+                && method.getName().startsWith("get") && method.getParameterTypes().length == 0;
     }
 
     private org.opendaylight.yangtools.yang.data.api.InstanceIdentifier shortenToLastAugmentation(
-            final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized) {
+            final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized,
+            final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier parentPath) {
+        int parentSize = Iterables.size(parentPath.getPathArguments());
         int position = 0;
         int foundPosition = -1;
-        for (PathArgument arg : normalized.getPath()) {
+        for (PathArgument arg : normalized.getPathArguments()) {
             position++;
             if (arg instanceof AugmentationIdentifier) {
                 foundPosition = position;
             }
         }
-        if (foundPosition > 0) {
-            return new org.opendaylight.yangtools.yang.data.api.InstanceIdentifier(normalized.getPath().subList(0,
-                    foundPosition));
+        if (foundPosition > 0 && foundPosition > parentSize) {
+            Iterable<PathArgument> shortened = Iterables.limit(normalized.getPathArguments(), foundPosition);
+            return org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.create(shortened);
         }
         return null;
     }
@@ -339,62 +477,6 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
         return normalized;
     }
 
-    @SuppressWarnings("unchecked")
-    private Iterable<Class<? extends DataObject>> getAugmentationChildren(final Class<?> targetType) {
-        List<Class<? extends DataObject>> ret = new LinkedList<>();
-        for (Method method : targetType.getMethods()) {
-            Class<?> entity = getYangModeledType(method);
-            if (entity != null) {
-                ret.add((Class<? extends DataObject>) entity);
-            }
-        }
-        return ret;
-    }
-
-    @SuppressWarnings({ "rawtypes", "unchecked" })
-    private Class<? extends DataObject> getYangModeledType(final Method method) {
-        if (method.getName().equals("getClass") || !method.getName().startsWith("get")
-                || method.getParameterTypes().length > 0) {
-            return null;
-        }
-
-        Class<?> returnType = method.getReturnType();
-        if (DataContainer.class.isAssignableFrom(returnType)) {
-            return (Class) returnType;
-        } else if (List.class.isAssignableFrom(returnType)) {
-            try {
-                return ClassLoaderUtils.withClassLoader(method.getDeclaringClass().getClassLoader(),
-                        new Supplier<Class>() {
-                            @Override
-                            public Class get() {
-                                Type listResult = ClassLoaderUtils.getFirstGenericParameter(method
-                                        .getGenericReturnType());
-                                if (listResult instanceof Class
-                                        && DataObject.class.isAssignableFrom((Class) listResult)) {
-                                    return (Class<?>) listResult;
-                                }
-                                return null;
-                            }
-
-                        });
-            } catch (Exception e) {
-                LOG.debug("Could not get YANG modeled entity for {}", method, e);
-                return null;
-            }
-
-        }
-        return null;
-    }
-
-    @SuppressWarnings({ "unchecked", "rawtypes" })
-    private static InstanceIdentifier<?> toWildcarded(final InstanceIdentifier<?> orig) {
-        List<org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument> wildArgs = new LinkedList<>();
-        for (org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument arg : orig.getPathArguments()) {
-            wildArgs.add(new Item(arg.getType()));
-        }
-        return InstanceIdentifier.create(wildArgs);
-    }
-
     private static boolean isAugmentation(final Class<? extends DataObject> type) {
         return Augmentation.class.isAssignableFrom(type);
     }
@@ -404,13 +486,13 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
     }
 
     private boolean isAugmentationIdentifier(final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier processed) {
-        return Iterables.getLast(processed.getPath()) instanceof AugmentationIdentifier;
+        return Iterables.getLast(processed.getPathArguments()) instanceof AugmentationIdentifier;
     }
 
     private static int getAugmentationCount(final InstanceIdentifier<?> potential) {
         int count = 0;
-        for(org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument arg : potential.getPathArguments()) {
-            if(isAugmentation(arg.getType())) {
+        for (org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument arg : potential.getPathArguments()) {
+            if (isAugmentation(arg.getType())) {
                 count++;
             }
 
@@ -420,11 +502,68 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
 
     private static int getAugmentationCount(final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier potential) {
         int count = 0;
-        for(PathArgument arg : potential.getPath()) {
-            if(arg instanceof AugmentationIdentifier) {
+        for (PathArgument arg : potential.getPathArguments()) {
+            if (arg instanceof AugmentationIdentifier) {
                 count++;
             }
         }
         return count;
     }
+
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    public <T extends DataObject> Function<Optional<NormalizedNode<?, ?>>, Optional<T>>  deserializeFunction(final InstanceIdentifier<T> path) {
+        return new DeserializeFunction(this, path);
+    }
+
+    private static class DeserializeFunction<T extends DataObject> implements Function<Optional<NormalizedNode<?, ?>>, Optional<T>> {
+
+        private final BindingToNormalizedNodeCodec codec;
+        private final InstanceIdentifier<?> path;
+
+        public DeserializeFunction(final BindingToNormalizedNodeCodec codec, final InstanceIdentifier<?> path) {
+            super();
+            this.codec = Preconditions.checkNotNull(codec, "Codec must not be null");
+            this.path = Preconditions.checkNotNull(path, "Path must not be null");
+        }
+
+        @SuppressWarnings("rawtypes")
+        @Nullable
+        @Override
+        public Optional apply(@Nullable final Optional<NormalizedNode<?, ?>> normalizedNode) {
+            if (normalizedNode.isPresent()) {
+                final DataObject dataObject;
+                try {
+                    dataObject = codec.toBinding(path, normalizedNode.get());
+                } catch (DeserializationException e) {
+                    LOG.warn("Failed to create dataobject from node {}", normalizedNode.get(), e);
+                    throw new IllegalStateException("Failed to create dataobject", e);
+                }
+
+                if (dataObject != null) {
+                    return Optional.of(dataObject);
+                }
+            }
+            return Optional.absent();
+        }
+    }
+
+    /**
+     * Returns an default object according to YANG schema for supplied path.
+     *
+     * @param path DOM Path
+     * @return Node with defaults set on.
+     */
+    public NormalizedNode<?, ?> getDefaultNodeFor(final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier path) {
+        Iterator<PathArgument> iterator = path.getPathArguments().iterator();
+        DataNormalizationOperation<?> currentOp = legacyToNormalized.getRootOperation();
+        while (iterator.hasNext()) {
+            PathArgument currentArg = iterator.next();
+            try {
+                currentOp = currentOp.getChild(currentArg);
+            } catch (DataNormalizationException e) {
+                throw new IllegalArgumentException(String.format("Invalid child encountered in path %s", path), e);
+            }
+        }
+        return currentOp.createDefault(path.getLastPathArgument());
+    }
 }
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/BindingTranslatedTransactionChain.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/md/sal/binding/impl/BindingTranslatedTransactionChain.java
new file mode 100644 (file)
index 0000000..2d8e51c
--- /dev/null
@@ -0,0 +1,115 @@
+/*
+ * 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;
+
+import java.util.Map;
+import java.util.WeakHashMap;
+
+import javax.annotation.concurrent.GuardedBy;
+
+import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
+import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
+import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
+import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionChain;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
+import org.opendaylight.yangtools.concepts.Delegator;
+
+import com.google.common.base.Preconditions;
+
+class BindingTranslatedTransactionChain implements BindingTransactionChain, Delegator<DOMTransactionChain> {
+
+    private final DOMTransactionChain delegate;
+
+    @GuardedBy("this")
+    private final Map<AsyncTransaction<?, ?>, AsyncTransaction<?, ?>> delegateTxToBindingTx = new WeakHashMap<>();
+    private final BindingToNormalizedNodeCodec codec;
+
+    public BindingTranslatedTransactionChain(final DOMDataBroker chainFactory,
+            final BindingToNormalizedNodeCodec codec, final TransactionChainListener listener) {
+        Preconditions.checkNotNull(chainFactory, "DOM Transaction chain factory must not be null");
+        this.delegate = chainFactory.createTransactionChain(new ListenerInvoker(listener));
+        this.codec = codec;
+    }
+
+    @Override
+    public DOMTransactionChain getDelegate() {
+        return delegate;
+    }
+
+    @Override
+    public ReadOnlyTransaction newReadOnlyTransaction() {
+        DOMDataReadOnlyTransaction delegateTx = delegate.newReadOnlyTransaction();
+        ReadOnlyTransaction bindingTx = new BindingDataReadTransactionImpl(delegateTx, codec);
+        putDelegateToBinding(delegateTx, bindingTx);
+        return bindingTx;
+    }
+
+    @Override
+    public ReadWriteTransaction newReadWriteTransaction() {
+        DOMDataReadWriteTransaction delegateTx = delegate.newReadWriteTransaction();
+        ReadWriteTransaction bindingTx = new BindingDataReadWriteTransactionImpl(delegateTx, codec);
+        putDelegateToBinding(delegateTx, bindingTx);
+        return bindingTx;
+    }
+
+    @Override
+    public WriteTransaction newWriteOnlyTransaction() {
+        DOMDataWriteTransaction delegateTx = delegate.newWriteOnlyTransaction();
+        WriteTransaction bindingTx = new BindingDataWriteTransactionImpl<>(delegateTx, codec);
+        putDelegateToBinding(delegateTx, bindingTx);
+        return bindingTx;
+    }
+
+    @Override
+    public void close() {
+        delegate.close();
+    }
+
+    private synchronized void putDelegateToBinding(final AsyncTransaction<?, ?> domTx,
+            final AsyncTransaction<?, ?> bindingTx) {
+        final Object previous = delegateTxToBindingTx.put(domTx, bindingTx);
+        Preconditions.checkState(previous == null, "DOM Transaction %s has already associated binding transation %s",domTx,previous);
+    }
+
+    private synchronized AsyncTransaction<?, ?> getBindingTransaction(final AsyncTransaction<?, ?> transaction) {
+        return delegateTxToBindingTx.get(transaction);
+    }
+
+    private final class ListenerInvoker implements TransactionChainListener {
+
+        private final TransactionChainListener listener;
+
+        public ListenerInvoker(final TransactionChainListener listener) {
+            this.listener = Preconditions.checkNotNull(listener, "Listener must not be null.");
+        }
+
+        @Override
+        public void onTransactionChainFailed(final TransactionChain<?, ?> chain,
+                final AsyncTransaction<?, ?> transaction, final Throwable cause) {
+            Preconditions.checkState(delegate.equals(chain),
+                    "Illegal state - listener for %s was invoked for incorrect chain %s.", delegate, chain);
+            AsyncTransaction<?, ?> bindingTx = getBindingTransaction(transaction);
+            listener.onTransactionChainFailed(chain, bindingTx, cause);
+        }
+
+        @Override
+        public void onTransactionChainSuccessful(final TransactionChain<?, ?> chain) {
+            Preconditions.checkState(delegate.equals(chain),
+                    "Illegal state - listener for %s was invoked for incorrect chain %s.", delegate, chain);
+            listener.onTransactionChainSuccessful(BindingTranslatedTransactionChain.this);
+        }
+    }
+
+}
index bf18454f4d1c3122ad7e8c5cd651e02d24f50437..b45450ae3a54554243fe6a3c5097f362fb82779b 100644 (file)
@@ -18,7 +18,6 @@ import java.util.concurrent.Callable;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ExecutionException;
 
-import org.opendaylight.controller.md.sal.binding.api.BindingDataChangeListener;
 import org.opendaylight.controller.md.sal.common.api.RegistrationListener;
 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
@@ -34,7 +33,6 @@ import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
 import org.opendaylight.controller.sal.binding.api.data.DataChangeListener;
 import org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction;
 import org.opendaylight.controller.sal.binding.api.data.DataProviderService;
-import org.opendaylight.controller.sal.common.util.Rpcs;
 import org.opendaylight.controller.sal.core.api.model.SchemaService;
 import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
 import org.opendaylight.yangtools.concepts.Delegator;
@@ -43,8 +41,8 @@ import org.opendaylight.yangtools.concepts.Registration;
 import org.opendaylight.yangtools.concepts.util.ListenerRegistry;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.RpcError;
 import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -113,11 +111,11 @@ public class ForwardedBackwardsCompatibleDataBroker extends AbstractForwardedDat
             final InstanceIdentifier<? extends DataObject> path, final DataChangeListener listener) {
 
 
-        BindingDataChangeListener asyncOperListener = new BackwardsCompatibleOperationalDataChangeInvoker(listener);
-        BindingDataChangeListener asyncCfgListener = new BackwardsCompatibleConfigurationDataChangeInvoker(listener);
+        org.opendaylight.controller.md.sal.binding.api.DataChangeListener asyncOperListener = new BackwardsCompatibleOperationalDataChangeInvoker(listener);
+        org.opendaylight.controller.md.sal.binding.api.DataChangeListener asyncCfgListener = new BackwardsCompatibleConfigurationDataChangeInvoker(listener);
 
-        ListenerRegistration<BindingDataChangeListener> cfgReg = registerDataChangeListener(LogicalDatastoreType.CONFIGURATION, path, asyncCfgListener, DataChangeScope.SUBTREE);
-        ListenerRegistration<BindingDataChangeListener> operReg = registerDataChangeListener(LogicalDatastoreType.OPERATIONAL, path, asyncOperListener, DataChangeScope.SUBTREE);
+        ListenerRegistration<org.opendaylight.controller.md.sal.binding.api.DataChangeListener> cfgReg = registerDataChangeListener(LogicalDatastoreType.CONFIGURATION, path, asyncCfgListener, DataChangeScope.SUBTREE);
+        ListenerRegistration<org.opendaylight.controller.md.sal.binding.api.DataChangeListener> operReg = registerDataChangeListener(LogicalDatastoreType.OPERATIONAL, path, asyncOperListener, DataChangeScope.SUBTREE);
 
         return new LegacyListenerRegistration(listener,cfgReg,operReg);
     }
@@ -164,7 +162,7 @@ public class ForwardedBackwardsCompatibleDataBroker extends AbstractForwardedDat
                 if(requestCommitSuccess) {
                     return tx.getDelegate().commit();
                 }
-                return Futures.immediateFuture(Rpcs.getRpcResult(false, TransactionStatus.FAILED, Collections.<RpcError>emptySet()));
+                return Futures.immediateFuture(RpcResultBuilder.<TransactionStatus>failed().withResult(TransactionStatus.FAILED).build());
             }
         });
 
@@ -187,7 +185,7 @@ public class ForwardedBackwardsCompatibleDataBroker extends AbstractForwardedDat
     }
 
     private class ForwardedBackwardsCompatibleTransacion extends
-            AbstractForwardedTransaction<DOMDataReadWriteTransaction> implements DataModificationTransaction {
+            AbstractReadWriteTransaction implements DataModificationTransaction {
 
         private final ListenerRegistry<DataTransactionListener> listeners = ListenerRegistry.create();
         private final Map<InstanceIdentifier<? extends DataObject>, DataObject> updated = new HashMap<>();
@@ -215,9 +213,9 @@ public class ForwardedBackwardsCompatibleDataBroker extends AbstractForwardedDat
         public void putOperationalData(final InstanceIdentifier<? extends DataObject> path, final DataObject data) {
             boolean previouslyRemoved = posponedRemovedOperational.remove(path);
             if(previouslyRemoved) {
-                doPutWithEnsureParents(getDelegate(), LogicalDatastoreType.OPERATIONAL, path, data);
+                doPutWithEnsureParents(LogicalDatastoreType.OPERATIONAL, path, data);
             } else {
-                doMergeWithEnsureParents(getDelegate(), LogicalDatastoreType.OPERATIONAL, path, data);
+                doMergeWithEnsureParents(LogicalDatastoreType.OPERATIONAL, path, data);
             }
         }
 
@@ -233,9 +231,9 @@ public class ForwardedBackwardsCompatibleDataBroker extends AbstractForwardedDat
             }
             updated.put(path, data);
             if(previouslyRemoved) {
-                doPutWithEnsureParents(getDelegate(), LogicalDatastoreType.CONFIGURATION, path, data);
+                doPutWithEnsureParents(LogicalDatastoreType.CONFIGURATION, path, data);
             } else {
-                doMergeWithEnsureParents(getDelegate(), LogicalDatastoreType.CONFIGURATION, path, data);
+                doMergeWithEnsureParents(LogicalDatastoreType.CONFIGURATION, path, data);
             }
         }
 
@@ -309,11 +307,6 @@ public class ForwardedBackwardsCompatibleDataBroker extends AbstractForwardedDat
             }
         }
 
-        @Override
-        public Object getIdentifier() {
-            return getDelegate().getIdentifier();
-        }
-
         private void changeStatus(final TransactionStatus status) {
             LOG.trace("Transaction {} changed status to {}", getIdentifier(), status);
             this.status = status;
@@ -331,11 +324,11 @@ public class ForwardedBackwardsCompatibleDataBroker extends AbstractForwardedDat
         public ListenableFuture<RpcResult<TransactionStatus>> commit() {
 
             for(InstanceIdentifier<? extends DataObject> path : posponedRemovedConfiguration) {
-                doDelete(getDelegate(), LogicalDatastoreType.CONFIGURATION, path);
+                doDelete(LogicalDatastoreType.CONFIGURATION, path);
             }
 
             for(InstanceIdentifier<? extends DataObject> path : posponedRemovedOperational) {
-                doDelete(getDelegate(), LogicalDatastoreType.OPERATIONAL, path);
+                doDelete(LogicalDatastoreType.OPERATIONAL, path);
             }
 
             changeStatus(TransactionStatus.SUBMITED);
@@ -387,12 +380,12 @@ public class ForwardedBackwardsCompatibleDataBroker extends AbstractForwardedDat
     private static final class LegacyListenerRegistration implements ListenerRegistration<DataChangeListener> {
 
         private final DataChangeListener instance;
-        private final ListenerRegistration<BindingDataChangeListener> cfgReg;
-        private final ListenerRegistration<BindingDataChangeListener> operReg;
+        private final ListenerRegistration<org.opendaylight.controller.md.sal.binding.api.DataChangeListener> cfgReg;
+        private final ListenerRegistration<org.opendaylight.controller.md.sal.binding.api.DataChangeListener> operReg;
 
         public LegacyListenerRegistration(final DataChangeListener listener,
-                final ListenerRegistration<BindingDataChangeListener> cfgReg,
-                final ListenerRegistration<BindingDataChangeListener> operReg) {
+                final ListenerRegistration<org.opendaylight.controller.md.sal.binding.api.DataChangeListener> cfgReg,
+                final ListenerRegistration<org.opendaylight.controller.md.sal.binding.api.DataChangeListener> operReg) {
             this.instance = listener;
             this.cfgReg = cfgReg;
             this.operReg = operReg;
@@ -411,7 +404,7 @@ public class ForwardedBackwardsCompatibleDataBroker extends AbstractForwardedDat
 
     }
 
-    private static class BackwardsCompatibleOperationalDataChangeInvoker implements BindingDataChangeListener, Delegator<DataChangeListener> {
+    private static class BackwardsCompatibleOperationalDataChangeInvoker implements org.opendaylight.controller.md.sal.binding.api.DataChangeListener, Delegator<DataChangeListener> {
 
         private final org.opendaylight.controller.md.sal.common.api.data.DataChangeListener<?,?> delegate;
 
@@ -436,7 +429,7 @@ public class ForwardedBackwardsCompatibleDataBroker extends AbstractForwardedDat
 
     }
 
-    private static class BackwardsCompatibleConfigurationDataChangeInvoker implements BindingDataChangeListener, Delegator<DataChangeListener> {
+    private static class BackwardsCompatibleConfigurationDataChangeInvoker implements org.opendaylight.controller.md.sal.binding.api.DataChangeListener, Delegator<DataChangeListener> {
         private final org.opendaylight.controller.md.sal.common.api.data.DataChangeListener<?,?> delegate;
 
         public BackwardsCompatibleConfigurationDataChangeInvoker(final DataChangeListener listener) {
index 5ab088e20ec20b072e08bf1e277af48a6dbda4a1..6359b60684ef45e18d2185d1231b14b165497724 100644 (file)
@@ -7,27 +7,17 @@
  */
 package org.opendaylight.controller.md.sal.binding.impl;
 
-import org.opendaylight.controller.md.sal.binding.api.BindingDataBroker;
-import org.opendaylight.controller.md.sal.binding.api.BindingDataReadTransaction;
-import org.opendaylight.controller.md.sal.binding.api.BindingDataReadWriteTransaction;
-import org.opendaylight.controller.md.sal.binding.api.BindingDataWriteTransaction;
-import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+
+import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
+import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
+import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
-import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction;
-import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
-import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
 import org.opendaylight.controller.sal.core.api.model.SchemaService;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
 
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.ListenableFuture;
-
 /**
  * The DataBrokerImpl simply defers to the DOMDataBroker for all its operations.
  * All transactions and listener registrations are wrapped by the DataBrokerImpl
@@ -36,111 +26,32 @@ import com.google.common.util.concurrent.ListenableFuture;
  * Besides this the DataBrokerImpl and it's collaborators also cache data that
  * is already transformed from the binding independent to binding aware format
  *
- * TODO : All references in this class to CompositeNode should be switched to
- * NormalizedNode once the MappingService is updated
- *
+
  */
-public class ForwardedBindingDataBroker extends AbstractForwardedDataBroker implements BindingDataBroker {
+public class ForwardedBindingDataBroker extends AbstractForwardedDataBroker implements DataBroker {
 
     public ForwardedBindingDataBroker(final DOMDataBroker domDataBroker, final BindingIndependentMappingService mappingService, final SchemaService schemaService) {
         super(domDataBroker, mappingService,schemaService);
     }
 
     @Override
-    public BindingDataReadTransaction newReadOnlyTransaction() {
+
+    public ReadOnlyTransaction newReadOnlyTransaction() {
         return new BindingDataReadTransactionImpl(getDelegate().newReadOnlyTransaction(),getCodec());
     }
 
     @Override
-    public BindingDataReadWriteTransaction newReadWriteTransaction() {
+    public ReadWriteTransaction newReadWriteTransaction() {
         return new BindingDataReadWriteTransactionImpl(getDelegate().newReadWriteTransaction(),getCodec());
     }
 
     @Override
-    public BindingDataWriteTransaction newWriteOnlyTransaction() {
-        return new BindingDataWriteTransactionImpl<DOMDataWriteTransaction>(getDelegate().newWriteOnlyTransaction(),getCodec());
-    }
-
-    private abstract class AbstractBindingTransaction<T extends AsyncTransaction<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>>>
-            extends AbstractForwardedTransaction<T> implements AsyncTransaction<InstanceIdentifier<?>, DataObject> {
-
-        protected AbstractBindingTransaction(final T delegate, final BindingToNormalizedNodeCodec codec) {
-            super(delegate, codec);
-        }
-
-        @Override
-        public Object getIdentifier() {
-            return getDelegate().getIdentifier();
-        }
-
-        @Override
-        public void close() {
-            getDelegate().close();
-        }
-
+    public WriteTransaction newWriteOnlyTransaction() {
+        return new BindingDataWriteTransactionImpl<>(getDelegate().newWriteOnlyTransaction(),getCodec());
     }
 
-    private class BindingDataReadTransactionImpl extends AbstractBindingTransaction<DOMDataReadTransaction> implements
-            BindingDataReadTransaction {
-
-        protected BindingDataReadTransactionImpl(final DOMDataReadTransaction delegate,
-                final BindingToNormalizedNodeCodec codec) {
-            super(delegate, codec);
-        }
-
-        @Override
-        public ListenableFuture<Optional<DataObject>> read(final LogicalDatastoreType store,
-                final InstanceIdentifier<?> path) {
-            return doRead(getDelegate(), store, path);
-        }
-    }
-
-    private class BindingDataWriteTransactionImpl<T extends DOMDataWriteTransaction> extends
-            AbstractBindingTransaction<T> implements BindingDataWriteTransaction {
-
-        protected BindingDataWriteTransactionImpl(final T delegate, final BindingToNormalizedNodeCodec codec) {
-            super(delegate, codec);
-
-        }
-
-        @Override
-        public void cancel() {
-            doCancel(getDelegate());
-        }
-
-        @Override
-        public void put(final LogicalDatastoreType store, final InstanceIdentifier<?> path, final DataObject data) {
-            doPut(getDelegate(), store, path, data);
-        }
-
-        @Override
-        public void merge(final LogicalDatastoreType store, final InstanceIdentifier<?> path, final DataObject data) {
-            doMerge(getDelegate(), store, path, data);
-        }
-
-        @Override
-        public void delete(final LogicalDatastoreType store, final InstanceIdentifier<?> path) {
-            doDelete(getDelegate(), store, path);
-        }
-
-        @Override
-        public ListenableFuture<RpcResult<TransactionStatus>> commit() {
-            return doCommit(getDelegate());
-        }
-    }
-
-    private class BindingDataReadWriteTransactionImpl extends
-            BindingDataWriteTransactionImpl<DOMDataReadWriteTransaction> implements BindingDataReadWriteTransaction {
-
-        protected BindingDataReadWriteTransactionImpl(final DOMDataReadWriteTransaction delegate,
-                final BindingToNormalizedNodeCodec codec) {
-            super(delegate, codec);
-        }
-
-        @Override
-        public ListenableFuture<Optional<DataObject>> read(final LogicalDatastoreType store,
-                final InstanceIdentifier<?> path) {
-            return doRead(getDelegate(), store, path);
-        }
+    @Override
+    public BindingTransactionChain createTransactionChain(final TransactionChainListener listener) {
+        return new BindingTranslatedTransactionChain(getDelegate(), getCodec(), listener);
     }
 }
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/codegen/impl/BrokerImplClassLoader.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/codegen/impl/BrokerImplClassLoader.java
deleted file mode 100644 (file)
index fdd9350..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sal.binding.codegen.impl;
-
-public class BrokerImplClassLoader extends ClassLoader {
-    private final ClassLoader spiClassLoader;
-
-    public BrokerImplClassLoader(final ClassLoader model, final ClassLoader spi) {
-        super(model);
-        this.spiClassLoader = spi;
-    }
-
-    @Override
-    public Class<? extends Object> loadClass(final String name) throws ClassNotFoundException {
-        try {
-            return super.loadClass(name);
-        } catch (ClassNotFoundException e) {
-            return this.spiClassLoader.loadClass(name);
-        }
-    }
-}
index 052fd2169a523b955a427f036e2a0ab6b7a03bc4..709b62fee25247c09ec980c188acd504693d4e3e 100644 (file)
@@ -37,8 +37,6 @@ RpcRouter<T>, RouteChangeListener<Class<? extends BaseIdentity>, InstanceIdentif
 
     private static final Logger LOG = LoggerFactory.getLogger(RpcRouterCodegenInstance.class);
 
-    private T defaultService;
-
     private final Class<T> serviceType;
 
     private final T invocationProxy;
@@ -49,11 +47,8 @@ RpcRouter<T>, RouteChangeListener<Class<? extends BaseIdentity>, InstanceIdentif
 
     private final Map<Class<? extends BaseIdentity>, RpcRoutingTableImpl<? extends BaseIdentity, T>> routingTables;
 
-    private final String name;
-
     @SuppressWarnings("unchecked")
     public RpcRouterCodegenInstance(final String name,final Class<T> type, final T routerImpl, final Iterable<Class<? extends BaseIdentity>> contexts) {
-        this.name = name;
         this.listeners = ListenerRegistry.create();
         this.serviceType = type;
         this.invocationProxy = routerImpl;
@@ -90,7 +85,7 @@ RpcRouter<T>, RouteChangeListener<Class<? extends BaseIdentity>, InstanceIdentif
 
     @Override
     public T getDefaultService() {
-        return defaultService;
+        return RuntimeCodeHelper.getDelegate(invocationProxy);
     }
 
     @Override
@@ -125,11 +120,17 @@ RpcRouter<T>, RouteChangeListener<Class<? extends BaseIdentity>, InstanceIdentif
         return new RoutedRpcRegistrationImpl(service);
     }
 
+    public void removeDefaultImplementation(final T instance) {
+        RpcService current = RuntimeCodeHelper.getDelegate(invocationProxy);
+        if(instance == current) {
+            RuntimeCodeHelper.setDelegate(invocationProxy, null);
+        }
+    }
+
     @Override
     public RpcRegistration<T> registerDefaultService(final T service) {
-        // TODO Auto-generated method stub
         RuntimeCodeHelper.setDelegate(invocationProxy, service);
-        return null;
+        return new DefaultRpcImplementationRegistration(service);
     }
 
     private class RoutedRpcRegistrationImpl extends AbstractObjectRegistration<T> implements RoutedRpcRegistration<T> {
@@ -168,4 +169,24 @@ RpcRouter<T>, RouteChangeListener<Class<? extends BaseIdentity>, InstanceIdentif
 
         }
     }
+
+    private class DefaultRpcImplementationRegistration extends AbstractObjectRegistration<T> implements RpcRegistration<T> {
+
+
+        protected DefaultRpcImplementationRegistration(final T instance) {
+            super(instance);
+        }
+
+        @Override
+        protected void removeRegistration() {
+            removeDefaultImplementation(this.getInstance());
+        }
+
+        @Override
+        public Class<T> getServiceType() {
+            return serviceType;
+        }
+    }
+
+
 }
index 00c9f1eb91a14f7f1df97a73bc871cac9e918058..834eb4f5fb357b65ae7ed90b6e986ea7c2474a0e 100644 (file)
@@ -82,6 +82,12 @@ class RuntimeCodeGenerator extends AbstractRuntimeCodeGenerator {
                         val rpcMeta = metadata.getRpcMethod(name);
                         val bodyTmp = '''
                         {
+                            if($1 == null) {
+                                throw new IllegalArgumentException("RPC input must not be null and must contain a value for field «rpcMeta.inputRouteGetter.name»");
+                            }
+                            if($1.«rpcMeta.inputRouteGetter.name»() == null) {
+                                throw new IllegalArgumentException("Field «rpcMeta.inputRouteGetter.name» must not be null");
+                            }
                             final «InstanceIdentifier.name» identifier = $1.«rpcMeta.inputRouteGetter.name»()«IF rpcMeta.
                             routeEncapsulated».getValue()«ENDIF»;
                             «supertype.name» instance = («supertype.name») «rpcMeta.context.routingTableField».get(identifier);
index 8acad1b2d737a0e440f7d55e1ab3c0a233dbba83..d810149c7077b663701d5385352f67da10ab7361 100644 (file)
@@ -9,7 +9,7 @@ package org.opendaylight.controller.sal.binding.impl;
 
 import static com.google.common.base.Preconditions.checkState;
 
-import org.opendaylight.controller.md.sal.binding.api.BindingDataBroker;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.binding.util.AbstractBindingSalProviderInstance;
 import org.opendaylight.controller.md.sal.binding.util.BindingContextUtils;
 import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
@@ -54,7 +54,7 @@ public class RootBindingAwareBroker implements //
 
     private DataProviderService legacyDataBroker;
 
-    private BindingDataBroker dataBroker;
+    private DataBroker dataBroker;
 
     private MountPointManagerImpl mountManager;
 
@@ -124,7 +124,7 @@ public class RootBindingAwareBroker implements //
         consBuilder.put(DataBrokerService.class, getRoot());
         consBuilder.put(RpcConsumerRegistry.class, getRoot());
         if(dataBroker != null) {
-            consBuilder.put(BindingDataBroker.class, dataBroker);
+            consBuilder.put(DataBroker.class, dataBroker);
         }
         consBuilder.put(MountService.class, mountManager).build();
         supportedConsumerServices = consBuilder.build();
@@ -183,7 +183,7 @@ public class RootBindingAwareBroker implements //
         }
     }
 
-    public void setDataBroker(final BindingDataBroker asyncDataBroker) {
+    public void setDataBroker(final DataBroker asyncDataBroker) {
         dataBroker = asyncDataBroker;
     }
 }
index 542dfa7e7bca61a0fc4ff33e31239c3c3872e73b..c61ec4926a65f58f31fd03657162b0af70b23c0e 100644 (file)
@@ -7,6 +7,19 @@
  */
 package org.opendaylight.controller.sal.binding.impl;
 
+import static com.google.common.base.Preconditions.checkState;
+
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+
+import java.util.EventListener;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.WeakHashMap;
+
 import org.opendaylight.controller.md.sal.common.api.routing.RouteChange;
 import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
 import org.opendaylight.controller.md.sal.common.api.routing.RouteChangePublisher;
@@ -28,23 +41,21 @@ import org.opendaylight.yangtools.yang.binding.RpcService;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import java.util.EventListener;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.WeakHashMap;
-
-import static com.google.common.base.Preconditions.checkState;
-
-public class RpcProviderRegistryImpl implements //
-        RpcProviderRegistry, //
-        RouteChangePublisher<RpcContextIdentifier, InstanceIdentifier<?>> {
+public class RpcProviderRegistryImpl implements RpcProviderRegistry, RouteChangePublisher<RpcContextIdentifier, InstanceIdentifier<?>> {
 
     private RuntimeCodeGenerator rpcFactory = SingletonHolder.RPC_GENERATOR_IMPL;
 
-    // publicProxies is a cache of proxy objects where each value in the map corresponds to a specific RpcService
-    private final Map<Class<? extends RpcService>, RpcService> publicProxies = new WeakHashMap<>();
+    // cache of proxy objects where each value in the map corresponds to a specific RpcService
+    private final LoadingCache<Class<? extends RpcService>, RpcService> publicProxies = CacheBuilder.newBuilder().weakKeys().
+            build(new CacheLoader<Class<? extends RpcService>, RpcService>() {
+                @Override
+                public RpcService load(final Class<? extends RpcService> type) {
+                    final RpcService proxy = rpcFactory.getDirectProxyFor(type);
+                    LOG.debug("Created {} as public proxy for {} in {}", proxy, type.getSimpleName(), this);
+                    return proxy;
+                }
+            });
+
     private final Map<Class<? extends RpcService>, RpcRouter<?>> rpcRouters = new WeakHashMap<>();
     private final ListenerRegistry<RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>> routeChangeListeners = ListenerRegistry
             .create();
@@ -60,19 +71,19 @@ public class RpcProviderRegistryImpl implements //
         return name;
     }
 
-    public RpcProviderRegistryImpl(String name) {
+    public RpcProviderRegistryImpl(final String name) {
         super();
         this.name = name;
     }
 
     @Override
-    public final <T extends RpcService> RoutedRpcRegistration<T> addRoutedRpcImplementation(Class<T> type,
-            T implementation) throws IllegalStateException {
+    public final <T extends RpcService> RoutedRpcRegistration<T> addRoutedRpcImplementation(final Class<T> type,
+            final T implementation) throws IllegalStateException {
         return getRpcRouter(type).addRoutedRpcImplementation(implementation);
     }
 
     @Override
-    public final <T extends RpcService> RpcRegistration<T> addRpcImplementation(Class<T> type, T implementation)
+    public final <T extends RpcService> RpcRegistration<T> addRpcImplementation(final Class<T> type, final T implementation)
             throws IllegalStateException {
         @SuppressWarnings("unchecked")
         RpcRouter<T> potentialRouter = (RpcRouter<T>) rpcRouters.get(type);
@@ -92,31 +103,12 @@ public class RpcProviderRegistryImpl implements //
 
     @SuppressWarnings("unchecked")
     @Override
-    public final <T extends RpcService> T getRpcService(Class<T> type) {
-
-        T potentialProxy = (T) publicProxies.get(type);
-        if (potentialProxy != null) {
-            return potentialProxy;
-        }
-        synchronized (this) {
-            /**
-             * Potential proxy could be instantiated by other thread while we
-             * were waiting for the lock.
-             */
-
-            potentialProxy = (T) publicProxies.get(type);
-            if (potentialProxy != null) {
-                return potentialProxy;
-            }
-            T proxy = rpcFactory.getDirectProxyFor(type);
-            LOG.debug("Created {} as public proxy for {} in {}", proxy, type.getSimpleName(), this);
-            publicProxies.put(type, proxy);
-            return proxy;
-        }
+    public final <T extends RpcService> T getRpcService(final Class<T> type) {
+        return (T) publicProxies.getUnchecked(type);
     }
 
-    @SuppressWarnings("unchecked")
-    public <T extends RpcService> RpcRouter<T> getRpcRouter(Class<T> type) {
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    public <T extends RpcService> RpcRouter<T> getRpcRouter(final Class<T> type) {
         RpcRouter<?> potentialRouter = rpcRouters.get(type);
         if (potentialRouter != null) {
             return (RpcRouter<T>) potentialRouter;
@@ -140,7 +132,7 @@ public class RpcProviderRegistryImpl implements //
         }
     }
 
-    private void notifyGlobalRpcAdded(Class<? extends RpcService> type) {
+    private void notifyGlobalRpcAdded(final Class<? extends RpcService> type) {
         for(ListenerRegistration<GlobalRpcRegistrationListener> listener : globalRpcListeners) {
             try {
                 listener.getInstance().onGlobalRpcRegistered(type);
@@ -151,7 +143,7 @@ public class RpcProviderRegistryImpl implements //
 
     }
 
-    private void notifyListenersRoutedCreated(RpcRouter<?> router) {
+    private void notifyListenersRoutedCreated(final RpcRouter<?> router) {
 
         for (ListenerRegistration<RouterInstantiationListener> listener : routerInstantiationListener) {
             try {
@@ -164,7 +156,7 @@ public class RpcProviderRegistryImpl implements //
     }
 
     public ListenerRegistration<RouterInstantiationListener> registerRouterInstantiationListener(
-            RouterInstantiationListener listener) {
+            final RouterInstantiationListener listener) {
         ListenerRegistration<RouterInstantiationListener> reg = routerInstantiationListener.register(listener);
         try {
             for (RpcRouter<?> router : rpcRouters.values()) {
@@ -176,9 +168,10 @@ public class RpcProviderRegistryImpl implements //
         return reg;
     }
 
+    @SuppressWarnings("unchecked")
     @Override
     public <L extends RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>> ListenerRegistration<L> registerRouteChangeListener(
-            L listener) {
+            final L listener) {
         return (ListenerRegistration<L>) routeChangeListeners.register(listener);
     }
 
@@ -186,7 +179,7 @@ public class RpcProviderRegistryImpl implements //
         return rpcFactory;
     }
 
-    public void setRpcFactory(RuntimeCodeGenerator rpcFactory) {
+    public void setRpcFactory(final RuntimeCodeGenerator rpcFactory) {
         this.rpcFactory = rpcFactory;
     }
 
@@ -194,7 +187,7 @@ public class RpcProviderRegistryImpl implements //
         void onRpcRouterCreated(RpcRouter<?> router);
     }
 
-    public ListenerRegistration<GlobalRpcRegistrationListener> registerGlobalRpcRegistrationListener(GlobalRpcRegistrationListener listener) {
+    public ListenerRegistration<GlobalRpcRegistrationListener> registerGlobalRpcRegistrationListener(final GlobalRpcRegistrationListener listener) {
         return globalRpcListeners.register(listener);
     }
 
@@ -204,17 +197,16 @@ public class RpcProviderRegistryImpl implements //
 
     }
 
-    private class RouteChangeForwarder<T extends RpcService> implements
-            RouteChangeListener<Class<? extends BaseIdentity>, InstanceIdentifier<?>> {
+    private class RouteChangeForwarder<T extends RpcService> implements RouteChangeListener<Class<? extends BaseIdentity>, InstanceIdentifier<?>> {
 
         private final Class<T> type;
 
-        public RouteChangeForwarder(Class<T> type) {
+        public RouteChangeForwarder(final Class<T> type) {
             this.type = type;
         }
 
         @Override
-        public void onRouteChange(RouteChange<Class<? extends BaseIdentity>, InstanceIdentifier<?>> change) {
+        public void onRouteChange(final RouteChange<Class<? extends BaseIdentity>, InstanceIdentifier<?>> change) {
             Map<RpcContextIdentifier, Set<InstanceIdentifier<?>>> announcements = new HashMap<>();
             for (Entry<Class<? extends BaseIdentity>, Set<InstanceIdentifier<?>>> entry : change.getAnnouncements()
                     .entrySet()) {
@@ -239,13 +231,12 @@ public class RpcProviderRegistryImpl implements //
         }
     }
 
-    public static class RpcProxyRegistration<T extends RpcService> extends AbstractObjectRegistration<T> implements
-            RpcRegistration<T> {
+    public static class RpcProxyRegistration<T extends RpcService> extends AbstractObjectRegistration<T> implements RpcRegistration<T> {
 
         private final Class<T> serviceType;
         private RpcProviderRegistryImpl registry;
 
-        public RpcProxyRegistration(Class<T> type, T service, RpcProviderRegistryImpl registry) {
+        public RpcProxyRegistration(final Class<T> type, final T service, final RpcProviderRegistryImpl registry) {
             super(service);
             this.serviceType = type;
             this.registry =  registry;
index d2472669fa39def5ae4862fb86be2fea5fa7b067..71253d02d66ff0230ad483dea2297afee072c8ba 100644 (file)
  */
 package org.opendaylight.controller.sal.binding.impl.connect.dom;
 
-import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkNotNull;
 import static com.google.common.base.Preconditions.checkState;
 
-import java.lang.ref.WeakReference;
-import java.lang.reflect.InvocationHandler;
-import java.lang.reflect.Method;
-import java.lang.reflect.Proxy;
 import java.util.Collection;
 import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.WeakHashMap;
-import java.util.concurrent.Callable;
+
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
-
 import org.opendaylight.controller.md.sal.binding.impl.AbstractForwardedDataBroker;
-import org.opendaylight.controller.md.sal.common.api.RegistrationListener;
-import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
 import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler;
-import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler.DataCommitTransaction;
-import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandlerRegistration;
-import org.opendaylight.controller.md.sal.common.api.data.DataModification;
-import org.opendaylight.controller.md.sal.common.api.routing.RouteChange;
-import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
 import org.opendaylight.controller.md.sal.common.api.routing.RouteChangePublisher;
 import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
-import org.opendaylight.controller.sal.binding.api.NotificationProviderService.NotificationInterestListener;
 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
 import org.opendaylight.controller.sal.binding.api.data.DataProviderService;
 import org.opendaylight.controller.sal.binding.api.data.RuntimeDataProvider;
-import org.opendaylight.controller.sal.binding.api.rpc.RpcContextIdentifier;
-import org.opendaylight.controller.sal.binding.api.rpc.RpcRouter;
 import org.opendaylight.controller.sal.binding.impl.DataBrokerImpl;
 import org.opendaylight.controller.sal.binding.impl.MountPointManagerImpl.BindingMountPointImpl;
 import org.opendaylight.controller.sal.binding.impl.RpcProviderRegistryImpl;
-import org.opendaylight.controller.sal.binding.impl.RpcProviderRegistryImpl.GlobalRpcRegistrationListener;
-import org.opendaylight.controller.sal.binding.impl.RpcProviderRegistryImpl.RouterInstantiationListener;
-import org.opendaylight.controller.sal.common.util.CommitHandlerTransactions;
-import org.opendaylight.controller.sal.common.util.Rpcs;
 import org.opendaylight.controller.sal.core.api.Broker.ProviderSession;
-import org.opendaylight.controller.sal.core.api.Broker.RoutedRpcRegistration;
 import org.opendaylight.controller.sal.core.api.Provider;
-import org.opendaylight.controller.sal.core.api.RpcImplementation;
 import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
-import org.opendaylight.controller.sal.core.api.data.DataModificationTransaction;
-import org.opendaylight.controller.sal.core.api.notify.NotificationListener;
 import org.opendaylight.controller.sal.core.api.notify.NotificationPublishService;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.concepts.Registration;
 import org.opendaylight.yangtools.yang.binding.Augmentable;
 import org.opendaylight.yangtools.yang.binding.Augmentation;
-import org.opendaylight.yangtools.yang.binding.BaseIdentity;
-import org.opendaylight.yangtools.yang.binding.BindingMapping;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.binding.Notification;
-import org.opendaylight.yangtools.yang.binding.RpcService;
-import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
-import org.opendaylight.yangtools.yang.binding.util.ClassLoaderUtils;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.RpcError;
-import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
 import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Function;
-import com.google.common.collect.FluentIterable;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.ImmutableSet.Builder;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-
 public class BindingIndependentConnector implements //
         RuntimeDataProvider, //
         Provider, //
         AutoCloseable {
 
-    private final Logger LOG = LoggerFactory.getLogger(BindingIndependentConnector.class);
-
+    private static final Logger LOG = LoggerFactory.getLogger(BindingIndependentConnector.class);
     private static final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier ROOT_BI = org.opendaylight.yangtools.yang.data.api.InstanceIdentifier
             .builder().toInstance();
 
-    private final static Method EQUALS_METHOD;
-
     private BindingIndependentMappingService mappingService;
-
     private org.opendaylight.controller.sal.core.api.data.DataProviderService biDataService;
-
     private DataProviderService baDataService;
 
-    private final ConcurrentMap<Object, BindingToDomTransaction> domOpenedTransactions = new ConcurrentHashMap<>();
-    private final ConcurrentMap<Object, DomToBindingTransaction> bindingOpenedTransactions = new ConcurrentHashMap<>();
-
-    private final BindingToDomCommitHandler bindingToDomCommitHandler = new BindingToDomCommitHandler();
-    private final DomToBindingCommitHandler domToBindingCommitHandler = new DomToBindingCommitHandler();
-
-    private Registration<DataCommitHandler<InstanceIdentifier<? extends DataObject>, DataObject>> baCommitHandlerRegistration;
+    private final ConcurrentMap<Object, BindingToDomTransaction> domOpenedTransactions;
+    private final ConcurrentMap<Object, DomToBindingTransaction> bindingOpenedTransactions;
+    private final BindingToDomCommitHandler bindingToDomCommitHandler;
+    private final DomToBindingCommitHandler domToBindingCommitHandler;
 
     private Registration<DataCommitHandler<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode>> biCommitHandlerRegistration;
-
     private RpcProvisionRegistry biRpcRegistry;
     private RpcProviderRegistry baRpcRegistry;
 
     private ListenerRegistration<DomToBindingRpcForwardingManager> domToBindingRpcManager;
-    // private ListenerRegistration<BindingToDomRpcForwardingManager>
-    // bindingToDomRpcManager;
 
-    private final Function<InstanceIdentifier<?>, org.opendaylight.yangtools.yang.data.api.InstanceIdentifier> toDOMInstanceIdentifier = new Function<InstanceIdentifier<?>, org.opendaylight.yangtools.yang.data.api.InstanceIdentifier>() {
-
-        @Override
-        public org.opendaylight.yangtools.yang.data.api.InstanceIdentifier apply(final InstanceIdentifier<?> input) {
-            return mappingService.toDataDom(input);
-        }
-
-    };
-
-    private boolean rpcForwarding = false;
-
-    private boolean dataForwarding = false;
-
-    private boolean notificationForwarding = false;
+    private boolean rpcForwarding;
+    private boolean dataForwarding;
+    private boolean notificationForwarding;
 
     private RpcProviderRegistryImpl baRpcRegistryImpl;
 
@@ -145,12 +75,15 @@ public class BindingIndependentConnector implements //
 
     private NotificationPublishService domNotificationService;
 
-    static {
-        try {
-            EQUALS_METHOD = Object.class.getMethod("equals", Object.class);
-        } catch (Exception e) {
-            throw new RuntimeException(e);
-        }
+    public BindingIndependentConnector() {
+        domOpenedTransactions = new ConcurrentHashMap<>();
+        bindingOpenedTransactions = new ConcurrentHashMap<>();
+
+        bindingToDomCommitHandler = new BindingToDomCommitHandler(bindingOpenedTransactions, domOpenedTransactions);
+        domToBindingCommitHandler = new DomToBindingCommitHandler(bindingOpenedTransactions, domOpenedTransactions);
+        rpcForwarding = false;
+        dataForwarding = false;
+        notificationForwarding = false;
     }
 
     @Override
@@ -190,84 +123,6 @@ public class BindingIndependentConnector implements //
         }
     }
 
-    private DataModificationTransaction createBindingToDomTransaction(
-            final DataModification<InstanceIdentifier<? extends DataObject>, DataObject> source) {
-        DataModificationTransaction target = biDataService.beginTransaction();
-        LOG.debug("Created DOM Transaction {} for {},", target.getIdentifier(), source.getIdentifier());
-        for (InstanceIdentifier<? extends DataObject> entry : source.getRemovedConfigurationData()) {
-            org.opendaylight.yangtools.yang.data.api.InstanceIdentifier biEntry = mappingService.toDataDom(entry);
-            target.removeConfigurationData(biEntry);
-            LOG.debug("Delete of Binding Configuration Data {} is translated to {}", entry, biEntry);
-        }
-        for (InstanceIdentifier<? extends DataObject> entry : source.getRemovedOperationalData()) {
-            org.opendaylight.yangtools.yang.data.api.InstanceIdentifier biEntry = mappingService.toDataDom(entry);
-            target.removeOperationalData(biEntry);
-            LOG.debug("Delete of Binding Operational Data {} is translated to {}", entry, biEntry);
-        }
-        for (Entry<InstanceIdentifier<? extends DataObject>, DataObject> entry : source.getUpdatedConfigurationData()
-                .entrySet()) {
-            Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> biEntry = mappingService
-                    .toDataDom(entry);
-            target.putConfigurationData(biEntry.getKey(), biEntry.getValue());
-            LOG.debug("Update of Binding Configuration Data {} is translated to {}", entry, biEntry);
-        }
-        for (Entry<InstanceIdentifier<? extends DataObject>, DataObject> entry : source.getUpdatedOperationalData()
-                .entrySet()) {
-            Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> biEntry = mappingService
-                    .toDataDom(entry);
-            target.putOperationalData(biEntry.getKey(), biEntry.getValue());
-            LOG.debug("Update of Binding Operational Data {} is translated to {}", entry, biEntry);
-        }
-
-        return target;
-    }
-
-    private org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction createDomToBindingTransaction(
-            final DataModification<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> source) {
-        org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction target = baDataService
-                .beginTransaction();
-        for (org.opendaylight.yangtools.yang.data.api.InstanceIdentifier entry : source.getRemovedConfigurationData()) {
-            try {
-
-                InstanceIdentifier<?> baEntry = mappingService.fromDataDom(entry);
-                target.removeConfigurationData(baEntry);
-            } catch (DeserializationException e) {
-                LOG.error("Ommiting from BA transaction: {}.", entry, e);
-            }
-        }
-        for (org.opendaylight.yangtools.yang.data.api.InstanceIdentifier entry : source.getRemovedOperationalData()) {
-            try {
-
-                InstanceIdentifier<?> baEntry = mappingService.fromDataDom(entry);
-                target.removeOperationalData(baEntry);
-            } catch (DeserializationException e) {
-                LOG.error("Ommiting from BA transaction: {}.", entry, e);
-            }
-        }
-        for (Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> entry : source
-                .getUpdatedConfigurationData().entrySet()) {
-            try {
-                InstanceIdentifier<?> baKey = mappingService.fromDataDom(entry.getKey());
-                DataObject baData = mappingService.dataObjectFromDataDom(baKey, entry.getValue());
-                target.putConfigurationData(baKey, baData);
-            } catch (DeserializationException e) {
-                LOG.error("Ommiting from BA transaction: {}.", entry.getKey(), e);
-            }
-        }
-        for (Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> entry : source
-                .getUpdatedOperationalData().entrySet()) {
-            try {
-
-                InstanceIdentifier<?> baKey = mappingService.fromDataDom(entry.getKey());
-                DataObject baData = mappingService.dataObjectFromDataDom(baKey, entry.getValue());
-                target.putOperationalData(baKey, baData);
-            } catch (DeserializationException e) {
-                LOG.error("Ommiting from BA transaction: {}.", entry.getKey(), e);
-            }
-        }
-        return target;
-    }
-
     public org.opendaylight.controller.sal.core.api.data.DataProviderService getBiDataService() {
         return biDataService;
     }
@@ -275,6 +130,7 @@ public class BindingIndependentConnector implements //
     protected void setDomDataService(
             final org.opendaylight.controller.sal.core.api.data.DataProviderService biDataService) {
         this.biDataService = biDataService;
+        bindingToDomCommitHandler.setBindingIndependentDataService(this.biDataService);
     }
 
     public DataProviderService getBaDataService() {
@@ -283,6 +139,7 @@ public class BindingIndependentConnector implements //
 
     protected void setBindingDataService(final DataProviderService baDataService) {
         this.baDataService = baDataService;
+        domToBindingCommitHandler.setBindingAwareDataService(this.baDataService);
     }
 
     public RpcProviderRegistry getRpcRegistry() {
@@ -318,14 +175,20 @@ public class BindingIndependentConnector implements //
         dataForwarding = true;
     }
 
+    //WTF? - cycle references to biFwdManager - need to solve :-/
     public void startRpcForwarding() {
+        checkNotNull(mappingService, "Unable to start Rpc forwarding. Reason: Mapping Service is not initialized properly!");
         if (biRpcRegistry != null && baRpcRegistry instanceof RouteChangePublisher<?, ?>) {
             checkState(!rpcForwarding, "Connector is already forwarding RPCs");
-            domToBindingRpcManager = baRpcRegistry.registerRouteChangeListener(new DomToBindingRpcForwardingManager());
+            final DomToBindingRpcForwardingManager biFwdManager = new DomToBindingRpcForwardingManager(mappingService, biRpcRegistry, baRpcRegistry);
+
+            domToBindingRpcManager = baRpcRegistry.registerRouteChangeListener(biFwdManager);
+            biRpcRegistry.addRpcRegistrationListener(biFwdManager);
             if (baRpcRegistry instanceof RpcProviderRegistryImpl) {
                 baRpcRegistryImpl = (RpcProviderRegistryImpl) baRpcRegistry;
                 baRpcRegistryImpl.registerRouterInstantiationListener(domToBindingRpcManager.getInstance());
                 baRpcRegistryImpl.registerGlobalRpcRegistrationListener(domToBindingRpcManager.getInstance());
+                biFwdManager.setRegistryImpl(baRpcRegistryImpl);
             }
             rpcForwarding = true;
         }
@@ -333,15 +196,23 @@ public class BindingIndependentConnector implements //
 
     public void startNotificationForwarding() {
         checkState(!notificationForwarding, "Connector is already forwarding notifications.");
-        if (baNotifyService != null && domNotificationService != null) {
-            baNotifyService.registerInterestListener(new DomToBindingNotificationForwarder());
-
+        if (mappingService == null) {
+            LOG.warn("Unable to start Notification forwarding. Reason: Mapping Service is not initialized properly!");
+        } else if (baNotifyService == null) {
+            LOG.warn("Unable to start Notification forwarding. Reason: Binding Aware Notify Service is not initialized properly!");
+        } else if (domNotificationService == null) {
+            LOG.warn("Unable to start Notification forwarding. Reason: DOM Notification Service is not initialized properly!");
+        } else {
+            baNotifyService.registerInterestListener(
+                new DomToBindingNotificationForwarder(mappingService, baNotifyService, domNotificationService));
             notificationForwarding = true;
         }
     }
 
     protected void setMappingService(final BindingIndependentMappingService mappingService) {
         this.mappingService = mappingService;
+        bindingToDomCommitHandler.setMappingService(this.mappingService);
+        domToBindingCommitHandler.setMappingService(this.mappingService);
     }
 
     @Override
@@ -356,387 +227,15 @@ public class BindingIndependentConnector implements //
 
     }
 
-    public <T extends RpcService> void onRpcRouterCreated(final Class<T> serviceType, final RpcRouter<T> router) {
-
-    }
-
     public void setDomRpcRegistry(final RpcProvisionRegistry registry) {
         biRpcRegistry = registry;
     }
 
     @Override
     public void close() throws Exception {
-        if (baCommitHandlerRegistration != null) {
-            baCommitHandlerRegistration.close();
-        }
         if (biCommitHandlerRegistration != null) {
             biCommitHandlerRegistration.close();
         }
-
-    }
-
-    private class DomToBindingTransaction implements
-            DataCommitTransaction<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> {
-
-        private final org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction backing;
-        private final DataModification<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> modification;
-
-        public DomToBindingTransaction(
-                final org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction backing,
-                final DataModification<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> modification) {
-            super();
-            this.backing = backing;
-            this.modification = modification;
-            bindingOpenedTransactions.put(backing.getIdentifier(), this);
-        }
-
-        @Override
-        public DataModification<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> getModification() {
-            return modification;
-        }
-
-        @Override
-        public RpcResult<Void> rollback() throws IllegalStateException {
-            // backing.cancel();
-            return Rpcs.<Void> getRpcResult(true, null, Collections.<RpcError> emptySet());
-        }
-
-        @Override
-        public RpcResult<Void> finish() throws IllegalStateException {
-            Future<RpcResult<TransactionStatus>> result = backing.commit();
-            try {
-                RpcResult<TransactionStatus> baResult = result.get();
-                return Rpcs.<Void> getRpcResult(baResult.isSuccessful(), null, baResult.getErrors());
-            } catch (InterruptedException e) {
-                throw new IllegalStateException("", e);
-            } catch (ExecutionException e) {
-                throw new IllegalStateException("", e);
-            }
-        }
-    }
-
-    private class BindingToDomTransaction implements
-            DataCommitTransaction<InstanceIdentifier<? extends DataObject>, DataObject> {
-
-        private final DataModificationTransaction backing;
-        private final DataModification<InstanceIdentifier<? extends DataObject>, DataObject> modification;
-
-        public BindingToDomTransaction(final DataModificationTransaction backing,
-                final DataModification<InstanceIdentifier<? extends DataObject>, DataObject> modification) {
-            this.backing = backing;
-            this.modification = modification;
-            domOpenedTransactions.put(backing.getIdentifier(), this);
-        }
-
-        @Override
-        public DataModification<InstanceIdentifier<? extends DataObject>, DataObject> getModification() {
-            return modification;
-        }
-
-        @Override
-        public RpcResult<Void> finish() throws IllegalStateException {
-            Future<RpcResult<TransactionStatus>> result = backing.commit();
-            try {
-                RpcResult<TransactionStatus> biResult = result.get();
-                return Rpcs.<Void> getRpcResult(biResult.isSuccessful(), null, biResult.getErrors());
-            } catch (InterruptedException e) {
-                throw new IllegalStateException("", e);
-            } catch (ExecutionException e) {
-                throw new IllegalStateException("", e);
-            } finally {
-                domOpenedTransactions.remove(backing.getIdentifier());
-            }
-        }
-
-        @Override
-        public RpcResult<Void> rollback() throws IllegalStateException {
-            domOpenedTransactions.remove(backing.getIdentifier());
-            return Rpcs.<Void> getRpcResult(true, null, Collections.<RpcError> emptySet());
-        }
-    }
-
-    private class BindingToDomCommitHandler implements
-            DataCommitHandler<InstanceIdentifier<? extends DataObject>, DataObject> {
-
-        @Override
-        public org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler.DataCommitTransaction<InstanceIdentifier<? extends DataObject>, DataObject> requestCommit(
-                final DataModification<InstanceIdentifier<? extends DataObject>, DataObject> bindingTransaction) {
-
-            /**
-             * Transaction was created as DOM transaction, in that case we do
-             * not need to forward it back.
-             */
-            if (bindingOpenedTransactions.containsKey(bindingTransaction.getIdentifier())) {
-
-                return CommitHandlerTransactions.allwaysSuccessfulTransaction(bindingTransaction);
-            }
-            DataModificationTransaction domTransaction = createBindingToDomTransaction(bindingTransaction);
-            BindingToDomTransaction wrapped = new BindingToDomTransaction(domTransaction, bindingTransaction);
-            LOG.trace("Forwarding Binding Transaction: {} as DOM Transaction: {} .",
-                    bindingTransaction.getIdentifier(), domTransaction.getIdentifier());
-            return wrapped;
-        }
-    }
-
-    private class DomToBindingCommitHandler implements //
-            RegistrationListener<DataCommitHandlerRegistration<InstanceIdentifier<? extends DataObject>, DataObject>>, //
-            DataCommitHandler<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> {
-
-        @Override
-        public void onRegister(
-                final DataCommitHandlerRegistration<InstanceIdentifier<? extends DataObject>, DataObject> registration) {
-
-            org.opendaylight.yangtools.yang.data.api.InstanceIdentifier domPath = mappingService.toDataDom(registration
-                    .getPath());
-
-        }
-
-        @Override
-        public void onUnregister(
-                final DataCommitHandlerRegistration<InstanceIdentifier<? extends DataObject>, DataObject> registration) {
-            // NOOP for now
-            // FIXME: do registration based on only active commit handlers.
-        }
-
-        @Override
-        public org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler.DataCommitTransaction<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> requestCommit(
-                final DataModification<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> domTransaction) {
-            Object identifier = domTransaction.getIdentifier();
-
-            /**
-             * We checks if the transcation was originated in this mapper. If it
-             * was originated in this mapper we are returing allways success
-             * commit hanlder to prevent creating loop in two-phase commit and
-             * duplicating data.
-             */
-            if (domOpenedTransactions.containsKey(identifier)) {
-                return CommitHandlerTransactions.allwaysSuccessfulTransaction(domTransaction);
-            }
-
-            org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction baTransaction = createDomToBindingTransaction(domTransaction);
-            DomToBindingTransaction forwardedTransaction = new DomToBindingTransaction(baTransaction, domTransaction);
-            LOG.trace("Forwarding DOM Transaction: {} as Binding Transaction: {}.", domTransaction.getIdentifier(),
-                    baTransaction.getIdentifier());
-            return forwardedTransaction;
-        }
-    }
-
-    /**
-     * Manager responsible for instantiating forwarders responsible for
-     * forwarding of RPC invocations from DOM Broker to Binding Aware Broker
-     *
-     */
-    private class DomToBindingRpcForwardingManager implements
-            RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>, RouterInstantiationListener,
-            GlobalRpcRegistrationListener {
-
-        private final Map<Class<? extends RpcService>, DomToBindingRpcForwarder> forwarders = new WeakHashMap<>();
-        private RpcProviderRegistryImpl registryImpl;
-
-        public RpcProviderRegistryImpl getRegistryImpl() {
-            return registryImpl;
-        }
-
-        public void setRegistryImpl(final RpcProviderRegistryImpl registryImpl) {
-            this.registryImpl = registryImpl;
-        }
-
-        @Override
-        public void onGlobalRpcRegistered(final Class<? extends RpcService> cls) {
-            getRpcForwarder(cls, null);
-        }
-
-        @Override
-        public void onGlobalRpcUnregistered(final Class<? extends RpcService> cls) {
-            // NOOP
-        }
-
-        @Override
-        public void onRpcRouterCreated(final RpcRouter<?> router) {
-            Class<? extends BaseIdentity> ctx = router.getContexts().iterator().next();
-            getRpcForwarder(router.getServiceType(), ctx);
-        }
-
-        @Override
-        public void onRouteChange(final RouteChange<RpcContextIdentifier, InstanceIdentifier<?>> change) {
-            for (Entry<RpcContextIdentifier, Set<InstanceIdentifier<?>>> entry : change.getAnnouncements().entrySet()) {
-                bindingRoutesAdded(entry);
-            }
-        }
-
-        private void bindingRoutesAdded(final Entry<RpcContextIdentifier, Set<InstanceIdentifier<?>>> entry) {
-            Class<? extends BaseIdentity> context = entry.getKey().getRoutingContext();
-            Class<? extends RpcService> service = entry.getKey().getRpcService();
-            if (context != null) {
-                getRpcForwarder(service, context).registerPaths(context, service, entry.getValue());
-            }
-        }
-
-        private DomToBindingRpcForwarder getRpcForwarder(final Class<? extends RpcService> service,
-                final Class<? extends BaseIdentity> context) {
-            DomToBindingRpcForwarder potential = forwarders.get(service);
-            if (potential != null) {
-                return potential;
-            }
-            if (context == null) {
-                potential = new DomToBindingRpcForwarder(service);
-            } else {
-                potential = new DomToBindingRpcForwarder(service, context);
-            }
-
-            forwarders.put(service, potential);
-            return potential;
-        }
-
-    }
-
-    private class DomToBindingRpcForwarder implements RpcImplementation, InvocationHandler {
-
-        private final Set<QName> supportedRpcs;
-        private final WeakReference<Class<? extends RpcService>> rpcServiceType;
-        private final Set<org.opendaylight.controller.sal.core.api.Broker.RoutedRpcRegistration> registrations;
-        private final Map<QName, RpcInvocationStrategy> strategiesByQName = new HashMap<>();
-        private final WeakHashMap<Method, RpcInvocationStrategy> strategiesByMethod = new WeakHashMap<>();
-
-        public DomToBindingRpcForwarder(final Class<? extends RpcService> service) {
-            this.rpcServiceType = new WeakReference<Class<? extends RpcService>>(service);
-            this.supportedRpcs = mappingService.getRpcQNamesFor(service);
-            try {
-                for (QName rpc : supportedRpcs) {
-                    RpcInvocationStrategy strategy = createInvocationStrategy(rpc, service);
-                    strategiesByMethod.put(strategy.targetMethod, strategy);
-                    strategiesByQName.put(rpc, strategy);
-                    biRpcRegistry.addRpcImplementation(rpc, this);
-                }
-
-            } catch (Exception e) {
-                LOG.error("Could not forward Rpcs of type {}", service.getName(), e);
-            }
-            registrations = ImmutableSet.of();
-        }
-
-        /**
-         * Constructor for Routed RPC Forwareder.
-         *
-         * @param service
-         * @param context
-         */
-        public DomToBindingRpcForwarder(final Class<? extends RpcService> service,
-                final Class<? extends BaseIdentity> context) {
-            this.rpcServiceType = new WeakReference<Class<? extends RpcService>>(service);
-            this.supportedRpcs = mappingService.getRpcQNamesFor(service);
-            Builder<RoutedRpcRegistration> registrationsBuilder = ImmutableSet
-                    .<org.opendaylight.controller.sal.core.api.Broker.RoutedRpcRegistration> builder();
-            try {
-                for (QName rpc : supportedRpcs) {
-                    RpcInvocationStrategy strategy = createInvocationStrategy(rpc, service);
-                    strategiesByMethod.put(strategy.targetMethod, strategy);
-                    strategiesByQName.put(rpc, strategy);
-                    registrationsBuilder.add(biRpcRegistry.addRoutedRpcImplementation(rpc, this));
-                }
-                createDefaultDomForwarder();
-            } catch (Exception e) {
-                LOG.error("Could not forward Rpcs of type {}", service.getName(), e);
-            }
-            registrations = registrationsBuilder.build();
-        }
-
-        public void registerPaths(final Class<? extends BaseIdentity> context,
-                final Class<? extends RpcService> service, final Set<InstanceIdentifier<?>> set) {
-            QName ctx = BindingReflections.findQName(context);
-            for (org.opendaylight.yangtools.yang.data.api.InstanceIdentifier path : FluentIterable.from(set).transform(
-                    toDOMInstanceIdentifier)) {
-                for (org.opendaylight.controller.sal.core.api.Broker.RoutedRpcRegistration reg : registrations) {
-                    reg.registerPath(ctx, path);
-                }
-            }
-        }
-
-        @Override
-        public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
-            if (EQUALS_METHOD.equals(method)) {
-                return false;
-            }
-            RpcInvocationStrategy strategy = strategiesByMethod.get(method);
-            checkState(strategy != null);
-            checkArgument(args.length <= 2);
-            if (args.length == 1) {
-                checkArgument(args[0] instanceof DataObject);
-                return strategy.forwardToDomBroker((DataObject) args[0]);
-            }
-            return strategy.forwardToDomBroker(null);
-        }
-
-        public void removePaths(final Class<? extends BaseIdentity> context, final Class<? extends RpcService> service,
-                final Set<InstanceIdentifier<?>> set) {
-            QName ctx = BindingReflections.findQName(context);
-            for (org.opendaylight.yangtools.yang.data.api.InstanceIdentifier path : FluentIterable.from(set).transform(
-                    toDOMInstanceIdentifier)) {
-                for (org.opendaylight.controller.sal.core.api.Broker.RoutedRpcRegistration reg : registrations) {
-                    reg.unregisterPath(ctx, path);
-                }
-            }
-        }
-
-        @Override
-        public Set<QName> getSupportedRpcs() {
-            return supportedRpcs;
-        }
-
-        @SuppressWarnings({ "unchecked", "rawtypes" })
-        public void createDefaultDomForwarder() {
-            if (baRpcRegistryImpl != null) {
-                Class<?> cls = rpcServiceType.get();
-                ClassLoader clsLoader = cls.getClassLoader();
-                RpcService proxy = (RpcService) Proxy.newProxyInstance(clsLoader, new Class<?>[] { cls }, this);
-
-                RpcRouter rpcRouter = baRpcRegistryImpl.getRpcRouter(rpcServiceType.get());
-                rpcRouter.registerDefaultService(proxy);
-            }
-        }
-
-        @Override
-        public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(final QName rpc, final CompositeNode domInput) {
-            checkArgument(rpc != null);
-            checkArgument(domInput != null);
-
-            Class<? extends RpcService> rpcType = rpcServiceType.get();
-            checkState(rpcType != null);
-            RpcService rpcService = baRpcRegistry.getRpcService(rpcType);
-            checkState(rpcService != null);
-            CompositeNode domUnwrappedInput = domInput.getFirstCompositeByName(QName.create(rpc, "input"));
-
-            try {
-                return Futures.immediateFuture(resolveInvocationStrategy(rpc).invokeOn(rpcService, domUnwrappedInput));
-            } catch (Exception e) {
-                return Futures.immediateFailedFuture(e);
-            }
-        }
-
-        private RpcInvocationStrategy resolveInvocationStrategy(final QName rpc) {
-            return strategiesByQName.get(rpc);
-        }
-
-        private RpcInvocationStrategy createInvocationStrategy(final QName rpc,
-                final Class<? extends RpcService> rpcType) throws Exception {
-            return ClassLoaderUtils.withClassLoader(rpcType.getClassLoader(), new Callable<RpcInvocationStrategy>() {
-                @Override
-                public RpcInvocationStrategy call() throws Exception {
-                    String methodName = BindingMapping.getMethodName(rpc);
-                    Method targetMethod = null;
-                    for (Method possibleMethod : rpcType.getMethods()) {
-                        if (possibleMethod.getName().equals(methodName)
-                                && BindingReflections.isRpcMethod(possibleMethod)) {
-                            targetMethod = possibleMethod;
-                            break;
-                        }
-                    }
-                    checkState(targetMethod != null, "Rpc method not found");
-                    return  new RpcInvocationStrategy(rpc,targetMethod, mappingService, biRpcRegistry);
-                }
-
-            });
-        }
     }
 
     public boolean isRpcForwarding() {
@@ -763,45 +262,4 @@ public class BindingIndependentConnector implements //
     public void setDomNotificationService(final NotificationPublishService domService) {
         this.domNotificationService = domService;
     }
-
-    private class DomToBindingNotificationForwarder implements NotificationInterestListener, NotificationListener {
-
-        private final ConcurrentMap<QName, WeakReference<Class<? extends Notification>>> notifications = new ConcurrentHashMap<>();
-        private final Set<QName> supportedNotifications = new HashSet<>();
-
-        @Override
-        public Set<QName> getSupportedNotifications() {
-            return Collections.unmodifiableSet(supportedNotifications);
-        }
-
-        @Override
-        public void onNotification(final CompositeNode notification) {
-            QName qname = notification.getNodeType();
-            WeakReference<Class<? extends Notification>> potential = notifications.get(qname);
-            if (potential != null) {
-                Class<? extends Notification> potentialClass = potential.get();
-                if (potentialClass != null) {
-                    final DataContainer baNotification = mappingService.dataObjectFromDataDom(potentialClass,
-                            notification);
-
-                    if (baNotification instanceof Notification) {
-                        baNotifyService.publish((Notification) baNotification);
-                    }
-                }
-            }
-        }
-
-        @Override
-        public void onNotificationSubscribtion(final Class<? extends Notification> notificationType) {
-            QName qname = BindingReflections.findQName(notificationType);
-            if (qname != null) {
-                WeakReference<Class<? extends Notification>> already = notifications.putIfAbsent(qname,
-                        new WeakReference<Class<? extends Notification>>(notificationType));
-                if (already == null) {
-                    domNotificationService.addNotificationListener(qname, this);
-                    supportedNotifications.add(qname);
-                }
-            }
-        }
-    }
 }
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/BindingToDomCommitHandler.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/BindingToDomCommitHandler.java
new file mode 100644 (file)
index 0000000..7434309
--- /dev/null
@@ -0,0 +1,104 @@
+package org.opendaylight.controller.sal.binding.impl.connect.dom;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentMap;
+
+import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler;
+import org.opendaylight.controller.md.sal.common.api.data.DataModification;
+import org.opendaylight.controller.sal.common.util.CommitHandlerTransactions;
+import org.opendaylight.controller.sal.core.api.data.DataModificationTransaction;
+import org.opendaylight.controller.sal.core.api.data.DataProviderService;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * @deprecated This is part of the legacy DataBrokerService
+ */
+@Deprecated
+class BindingToDomCommitHandler implements
+    DataCommitHandler<InstanceIdentifier<? extends DataObject>, DataObject> {
+
+    private final Logger LOG = LoggerFactory.getLogger(BindingToDomCommitHandler.class);
+
+    private final ConcurrentMap<Object, DomToBindingTransaction> bindingOpenedTransactions;
+    private final ConcurrentMap<Object, BindingToDomTransaction> domOpenedTransactions;
+    private org.opendaylight.controller.sal.core.api.data.DataProviderService biDataService;
+    private BindingIndependentMappingService mappingService;
+
+    BindingToDomCommitHandler(final ConcurrentMap<Object, DomToBindingTransaction> bindingOpenedTransactions,
+        final ConcurrentMap<Object, BindingToDomTransaction> domOpenedTransactions) {
+        this.bindingOpenedTransactions = bindingOpenedTransactions;
+        this.domOpenedTransactions = domOpenedTransactions;
+    }
+
+    public void setBindingIndependentDataService(final DataProviderService biDataService) {
+        this.biDataService = biDataService;
+    }
+
+    public void setMappingService(final BindingIndependentMappingService mappingService) {
+        this.mappingService = mappingService;
+    }
+
+    @Override
+    public org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler.DataCommitTransaction<InstanceIdentifier<? extends DataObject>, DataObject> requestCommit(
+        final DataModification<InstanceIdentifier<? extends DataObject>, DataObject> bindingTransaction) {
+
+        /**
+         * Transaction was created as DOM transaction, in that case we do
+         * not need to forward it back.
+         */
+        if (bindingOpenedTransactions.containsKey(bindingTransaction.getIdentifier())) {
+            return CommitHandlerTransactions.allwaysSuccessfulTransaction(bindingTransaction);
+        }
+        DataModificationTransaction domTransaction = createBindingToDomTransaction(bindingTransaction);
+        BindingToDomTransaction wrapped = new BindingToDomTransaction(domTransaction, bindingTransaction, domOpenedTransactions);
+        LOG.trace("Forwarding Binding Transaction: {} as DOM Transaction: {} .",
+            bindingTransaction.getIdentifier(), domTransaction.getIdentifier());
+        return wrapped;
+    }
+
+    private DataModificationTransaction createBindingToDomTransaction(
+        final DataModification<InstanceIdentifier<? extends DataObject>, DataObject> source) {
+        if (biDataService == null) {
+            final String msg = "Binding Independent Service is not initialized correctly! Binding to DOM Transaction cannot be created for ";
+            LOG.error(msg + "{}", source);
+            throw new IllegalStateException(msg + source);
+        }
+        if (mappingService == null) {
+            final String msg = "Mapping Service is not initialized correctly! Binding to DOM Transaction cannot be created for ";
+            LOG.error(msg + "{}", source);
+            throw new IllegalStateException(msg + source);
+        }
+        DataModificationTransaction target = biDataService.beginTransaction();
+        LOG.debug("Created DOM Transaction {} for {},", target.getIdentifier(), source.getIdentifier());
+        for (InstanceIdentifier<? extends DataObject> entry : source.getRemovedConfigurationData()) {
+            org.opendaylight.yangtools.yang.data.api.InstanceIdentifier biEntry = mappingService.toDataDom(entry);
+            target.removeConfigurationData(biEntry);
+            LOG.debug("Delete of Binding Configuration Data {} is translated to {}", entry, biEntry);
+        }
+        for (InstanceIdentifier<? extends DataObject> entry : source.getRemovedOperationalData()) {
+            org.opendaylight.yangtools.yang.data.api.InstanceIdentifier biEntry = mappingService.toDataDom(entry);
+            target.removeOperationalData(biEntry);
+            LOG.debug("Delete of Binding Operational Data {} is translated to {}", entry, biEntry);
+        }
+        for (Map.Entry<InstanceIdentifier<? extends DataObject>, DataObject> entry : source.getUpdatedConfigurationData()
+            .entrySet()) {
+            Map.Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> biEntry = mappingService
+                .toDataDom(entry);
+            target.putConfigurationData(biEntry.getKey(), biEntry.getValue());
+            LOG.debug("Update of Binding Configuration Data {} is translated to {}", entry, biEntry);
+        }
+        for (Map.Entry<InstanceIdentifier<? extends DataObject>, DataObject> entry : source.getUpdatedOperationalData()
+            .entrySet()) {
+            Map.Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> biEntry = mappingService
+                .toDataDom(entry);
+            target.putOperationalData(biEntry.getKey(), biEntry.getValue());
+            LOG.debug("Update of Binding Operational Data {} is translated to {}", entry, biEntry);
+        }
+        return target;
+    }
+}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/BindingToDomTransaction.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/BindingToDomTransaction.java
new file mode 100644 (file)
index 0000000..081adb4
--- /dev/null
@@ -0,0 +1,59 @@
+package org.opendaylight.controller.sal.binding.impl.connect.dom;
+
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+
+import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
+import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler;
+import org.opendaylight.controller.md.sal.common.api.data.DataModification;
+import org.opendaylight.controller.sal.core.api.data.DataModificationTransaction;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
+
+class BindingToDomTransaction implements
+    DataCommitHandler.DataCommitTransaction<InstanceIdentifier<? extends DataObject>, DataObject> {
+
+    private final DataModificationTransaction backing;
+    private final DataModification<InstanceIdentifier<? extends DataObject>, DataObject> modification;
+    private final ConcurrentMap<Object, BindingToDomTransaction> domOpenedTransactions;
+
+    public BindingToDomTransaction(final DataModificationTransaction backing,
+        final DataModification<InstanceIdentifier<? extends DataObject>, DataObject> modification,
+        ConcurrentMap<Object, BindingToDomTransaction> domOpenedTransactions) {
+        this.backing = backing;
+        this.modification = modification;
+        this.domOpenedTransactions = domOpenedTransactions;
+        this.domOpenedTransactions.put(backing.getIdentifier(), this);
+    }
+
+    @Override
+    public DataModification<InstanceIdentifier<? extends DataObject>, DataObject> getModification() {
+        return modification;
+    }
+
+    @Override
+    public RpcResult<Void> finish() throws IllegalStateException {
+        Future<RpcResult<TransactionStatus>> result = backing.commit();
+        try {
+            RpcResult<TransactionStatus> biResult = result.get();
+            domOpenedTransactions.remove(backing.getIdentifier());
+            return RpcResultBuilder.<Void> status(biResult.isSuccessful())
+                                             .withRpcErrors(biResult.getErrors()).build();
+        } catch (InterruptedException e) {
+            throw new IllegalStateException("", e);
+        } catch (ExecutionException e) {
+            throw new IllegalStateException("", e);
+        } finally {
+            domOpenedTransactions.remove(backing.getIdentifier());
+        }
+    }
+
+    @Override
+    public RpcResult<Void> rollback() throws IllegalStateException {
+        domOpenedTransactions.remove(backing.getIdentifier());
+        return RpcResultBuilder.<Void> success().build();
+    }
+}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/DataModificationTracker.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/DataModificationTracker.java
deleted file mode 100644 (file)
index 8278b36..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.binding.impl.connect.dom;
-
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-import org.opendaylight.controller.md.sal.common.api.data.DataModification;
-import org.opendaylight.yangtools.concepts.Path;
-
-public final class DataModificationTracker<P extends Path<P>,D> {
-    ConcurrentMap<Object, DataModification<P,D>> trackedTransactions = new ConcurrentHashMap<>();
-
-    public void startTrackingModification(DataModification<P,D> modification) {
-        trackedTransactions.putIfAbsent(modification.getIdentifier(), modification);
-    }
-
-    public boolean containsIdentifier(Object identifier) {
-        return trackedTransactions.containsKey(identifier);
-    }
-}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/DomToBindingCommitHandler.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/DomToBindingCommitHandler.java
new file mode 100644 (file)
index 0000000..88024b9
--- /dev/null
@@ -0,0 +1,140 @@
+package org.opendaylight.controller.sal.binding.impl.connect.dom;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentMap;
+
+import org.opendaylight.controller.md.sal.common.api.RegistrationListener;
+import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler;
+import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandlerRegistration;
+import org.opendaylight.controller.md.sal.common.api.data.DataModification;
+import org.opendaylight.controller.sal.binding.api.data.DataProviderService;
+import org.opendaylight.controller.sal.common.util.CommitHandlerTransactions;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
+import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * @deprecated This is part of the legacy DataBrokerService
+ */
+@Deprecated
+class DomToBindingCommitHandler implements //
+    RegistrationListener<DataCommitHandlerRegistration<InstanceIdentifier<? extends DataObject>, DataObject>>, //
+    DataCommitHandler<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> {
+
+    private final Logger LOG = LoggerFactory.getLogger(DomToBindingCommitHandler.class);
+
+    private final ConcurrentMap<Object, DomToBindingTransaction> bindingOpenedTransactions;
+    private final ConcurrentMap<Object, BindingToDomTransaction> domOpenedTransactions;
+
+    DomToBindingCommitHandler(final ConcurrentMap<Object, DomToBindingTransaction> bindingOpenedTransactions,
+        final ConcurrentMap<Object, BindingToDomTransaction> domOpenedTransactions) {
+        this.bindingOpenedTransactions = bindingOpenedTransactions;
+        this.domOpenedTransactions = domOpenedTransactions;
+    }
+
+    private DataProviderService baDataService;
+    private BindingIndependentMappingService mappingService;
+
+    public void setBindingAwareDataService(final DataProviderService baDataService) {
+        this.baDataService = baDataService;
+    }
+
+    public void setMappingService(final BindingIndependentMappingService mappingService) {
+        this.mappingService = mappingService;
+    }
+
+    @Override
+    public void onRegister(final DataCommitHandlerRegistration<InstanceIdentifier<? extends DataObject>, DataObject> registration) {
+        mappingService.toDataDom(registration.getPath());
+    }
+
+    @Override
+    public void onUnregister(
+        final DataCommitHandlerRegistration<InstanceIdentifier<? extends DataObject>, DataObject> registration) {
+        // NOOP for now
+        // FIXME: do registration based on only active commit handlers.
+    }
+
+    @Override
+    public org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler.DataCommitTransaction<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> requestCommit(
+        final DataModification<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> domTransaction) {
+        Object identifier = domTransaction.getIdentifier();
+
+        /**
+         * We checks if the transcation was originated in this mapper. If it
+         * was originated in this mapper we are returing allways success
+         * commit hanlder to prevent creating loop in two-phase commit and
+         * duplicating data.
+         */
+        if (domOpenedTransactions.containsKey(identifier)) {
+            return CommitHandlerTransactions.allwaysSuccessfulTransaction(domTransaction);
+        }
+
+        org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction baTransaction = createDomToBindingTransaction(domTransaction);
+        DomToBindingTransaction forwardedTransaction = new DomToBindingTransaction(baTransaction, domTransaction, bindingOpenedTransactions);
+        LOG.trace("Forwarding DOM Transaction: {} as Binding Transaction: {}.", domTransaction.getIdentifier(),
+            baTransaction.getIdentifier());
+        return forwardedTransaction;
+    }
+
+    private org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction createDomToBindingTransaction(
+        final DataModification<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> source) {
+        if (baDataService == null) {
+            final String msg = "Binding Aware Service is not initialized correctly! DOM to Binding Transaction cannot be created for ";
+            LOG.error(msg + "{}", source);
+            throw new IllegalStateException(msg + source);
+        }
+        if (mappingService == null) {
+            final String msg = "Mapping Service is not initialized correctly! DOM to Binding Transaction cannot be created for ";
+            LOG.error(msg + "{}", source);
+            throw new IllegalStateException(msg + source);
+        }
+
+        org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction target = baDataService
+            .beginTransaction();
+        for (org.opendaylight.yangtools.yang.data.api.InstanceIdentifier entry : source.getRemovedConfigurationData()) {
+            try {
+
+                InstanceIdentifier<?> baEntry = mappingService.fromDataDom(entry);
+                target.removeConfigurationData(baEntry);
+            } catch (DeserializationException e) {
+                LOG.error("Ommiting from BA transaction: {}.", entry, e);
+            }
+        }
+        for (org.opendaylight.yangtools.yang.data.api.InstanceIdentifier entry : source.getRemovedOperationalData()) {
+            try {
+
+                InstanceIdentifier<?> baEntry = mappingService.fromDataDom(entry);
+                target.removeOperationalData(baEntry);
+            } catch (DeserializationException e) {
+                LOG.error("Ommiting from BA transaction: {}.", entry, e);
+            }
+        }
+        for (Map.Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> entry : source
+            .getUpdatedConfigurationData().entrySet()) {
+            try {
+                InstanceIdentifier<?> baKey = mappingService.fromDataDom(entry.getKey());
+                DataObject baData = mappingService.dataObjectFromDataDom(baKey, entry.getValue());
+                target.putConfigurationData(baKey, baData);
+            } catch (DeserializationException e) {
+                LOG.error("Ommiting from BA transaction: {}.", entry.getKey(), e);
+            }
+        }
+        for (Map.Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> entry : source
+            .getUpdatedOperationalData().entrySet()) {
+            try {
+
+                InstanceIdentifier<?> baKey = mappingService.fromDataDom(entry.getKey());
+                DataObject baData = mappingService.dataObjectFromDataDom(baKey, entry.getValue());
+                target.putOperationalData(baKey, baData);
+            } catch (DeserializationException e) {
+                LOG.error("Ommiting from BA transaction: {}.", entry.getKey(), e);
+            }
+        }
+        return target;
+    }
+}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/DomToBindingNotificationForwarder.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/DomToBindingNotificationForwarder.java
new file mode 100644 (file)
index 0000000..841ea55
--- /dev/null
@@ -0,0 +1,70 @@
+package org.opendaylight.controller.sal.binding.impl.connect.dom;
+
+import java.lang.ref.WeakReference;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
+import org.opendaylight.controller.sal.core.api.notify.NotificationListener;
+import org.opendaylight.controller.sal.core.api.notify.NotificationPublishService;
+import org.opendaylight.yangtools.yang.binding.DataContainer;
+import org.opendaylight.yangtools.yang.binding.Notification;
+import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
+
+class DomToBindingNotificationForwarder implements NotificationProviderService.NotificationInterestListener,
+    NotificationListener {
+
+    private final ConcurrentMap<QName, WeakReference<Class<? extends Notification>>> notifications = new ConcurrentHashMap<>();
+    private final Set<QName> supportedNotifications = new HashSet<>();
+
+    private final BindingIndependentMappingService mappingService;
+    private final NotificationProviderService baNotifyService;
+    private final NotificationPublishService domNotificationService;
+
+    DomToBindingNotificationForwarder(final BindingIndependentMappingService mappingService, final NotificationProviderService baNotifyService,
+        final NotificationPublishService domNotificationService) {
+        this.mappingService = mappingService;
+        this.baNotifyService = baNotifyService;
+        this.domNotificationService = domNotificationService;
+    }
+
+    @Override
+    public Set<QName> getSupportedNotifications() {
+        return Collections.unmodifiableSet(supportedNotifications);
+    }
+
+    @Override
+    public void onNotification(final CompositeNode notification) {
+        QName qname = notification.getNodeType();
+        WeakReference<Class<? extends Notification>> potential = notifications.get(qname);
+        if (potential != null) {
+            Class<? extends Notification> potentialClass = potential.get();
+            if (potentialClass != null) {
+                final DataContainer baNotification = mappingService.dataObjectFromDataDom(potentialClass,
+                    notification);
+
+                if (baNotification instanceof Notification) {
+                    baNotifyService.publish((Notification) baNotification);
+                }
+            }
+        }
+    }
+
+    @Override
+    public void onNotificationSubscribtion(final Class<? extends Notification> notificationType) {
+        QName qname = BindingReflections.findQName(notificationType);
+        if (qname != null) {
+            WeakReference<Class<? extends Notification>> already = notifications.putIfAbsent(qname,
+                new WeakReference<Class<? extends Notification>>(notificationType));
+            if (already == null) {
+                domNotificationService.addNotificationListener(qname, this);
+                supportedNotifications.add(qname);
+            }
+        }
+    }
+}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/DomToBindingRpcForwarder.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/DomToBindingRpcForwarder.java
new file mode 100644 (file)
index 0000000..ffcab59
--- /dev/null
@@ -0,0 +1,281 @@
+package org.opendaylight.controller.sal.binding.impl.connect.dom;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkState;
+
+import java.lang.ref.WeakReference;
+import java.lang.reflect.InvocationHandler;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.WeakHashMap;
+import java.util.concurrent.Callable;
+
+import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
+import org.opendaylight.controller.sal.binding.api.rpc.RpcRouter;
+import org.opendaylight.controller.sal.binding.impl.RpcProviderRegistryImpl;
+import org.opendaylight.controller.sal.core.api.Broker;
+import org.opendaylight.controller.sal.core.api.RpcImplementation;
+import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
+import org.opendaylight.yangtools.concepts.CompositeObjectRegistration;
+import org.opendaylight.yangtools.concepts.ObjectRegistration;
+import org.opendaylight.yangtools.yang.binding.BaseIdentity;
+import org.opendaylight.yangtools.yang.binding.BindingMapping;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.binding.RpcService;
+import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
+import org.opendaylight.yangtools.yang.binding.util.ClassLoaderUtils;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Function;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+
+class DomToBindingRpcForwarder implements RpcImplementation, InvocationHandler {
+
+    private final Logger LOG = LoggerFactory.getLogger(DomToBindingRpcForwarder.class);
+
+    private final Set<QName> supportedRpcs;
+    private final WeakReference<Class<? extends RpcService>> rpcServiceType;
+    private Set<org.opendaylight.controller.sal.core.api.Broker.RoutedRpcRegistration> registrations;
+    private final Map<QName, RpcInvocationStrategy> strategiesByQName = new HashMap<>();
+    private final WeakHashMap<Method, RpcInvocationStrategy> strategiesByMethod = new WeakHashMap<>();
+    private final RpcService proxy;
+    private ObjectRegistration<?> forwarderRegistration;
+    private boolean registrationInProgress = false;
+
+    private final RpcProvisionRegistry biRpcRegistry;
+    private final RpcProviderRegistry baRpcRegistry;
+    private final RpcProviderRegistryImpl baRpcRegistryImpl;
+
+    private final Function<InstanceIdentifier<?>, org.opendaylight.yangtools.yang.data.api.InstanceIdentifier> toDOMInstanceIdentifier;
+
+    private final static Method EQUALS_METHOD;
+
+    static {
+        try {
+            EQUALS_METHOD = Object.class.getMethod("equals", Object.class);
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    public DomToBindingRpcForwarder(final Class<? extends RpcService> service, final BindingIndependentMappingService mappingService,
+        final RpcProvisionRegistry biRpcRegistry, final RpcProviderRegistry baRpcRegistry, final RpcProviderRegistryImpl registryImpl) {
+        this.rpcServiceType = new WeakReference<Class<? extends RpcService>>(service);
+        this.supportedRpcs = mappingService.getRpcQNamesFor(service);
+
+        toDOMInstanceIdentifier = new Function<InstanceIdentifier<?>, org.opendaylight.yangtools.yang.data.api.InstanceIdentifier>() {
+
+            @Override
+            public org.opendaylight.yangtools.yang.data.api.InstanceIdentifier apply(final InstanceIdentifier<?> input) {
+                return mappingService.toDataDom(input);
+            }
+        };
+
+        this.biRpcRegistry = biRpcRegistry;
+        this.baRpcRegistry = baRpcRegistry;
+        this.baRpcRegistryImpl = registryImpl;
+
+        Class<?> cls = rpcServiceType.get();
+        ClassLoader clsLoader = cls.getClassLoader();
+        proxy =(RpcService) Proxy.newProxyInstance(clsLoader, new Class<?>[] { cls }, this);
+        createStrategies(mappingService);
+    }
+
+    /**
+     * Constructor for Routed RPC Forwareder.
+     *
+     * @param service
+     * @param context
+     * @param registryImpl
+     */
+    public DomToBindingRpcForwarder(final Class<? extends RpcService> service,
+        final Class<? extends BaseIdentity> context, final BindingIndependentMappingService mappingService,
+        final RpcProvisionRegistry biRpcRegistry, final RpcProviderRegistry baRpcRegistry, final RpcProviderRegistryImpl registryImpl) {
+        this(service, mappingService, biRpcRegistry, baRpcRegistry,registryImpl);
+
+        final ImmutableSet.Builder<Broker.RoutedRpcRegistration> registrationsBuilder = ImmutableSet.builder();
+        try {
+            for (QName rpc : supportedRpcs) {
+                registrationsBuilder.add(biRpcRegistry.addRoutedRpcImplementation(rpc, this));
+            }
+            createDefaultDomForwarder();
+        } catch (Exception e) {
+            LOG.error("Could not forward Rpcs of type {}", service.getName(), e);
+        }
+        registrations = registrationsBuilder.build();
+    }
+
+
+
+    private void createStrategies(final BindingIndependentMappingService mappingService) {
+        try {
+            for (QName rpc : supportedRpcs) {
+                RpcInvocationStrategy strategy = createInvocationStrategy(rpc, rpcServiceType.get(), mappingService);
+                strategiesByMethod.put(strategy.targetMethod, strategy);
+                strategiesByQName.put(rpc, strategy);
+            }
+        } catch (Exception e) {
+            LOG.error("Could not forward Rpcs of type {}", rpcServiceType.get(), e);
+        }
+
+    }
+
+    /**
+     * Registers RPC Forwarder to DOM Broker,
+     * this means Binding Aware Broker has implementation of RPC
+     * which is registered to it.
+     *
+     * If RPC Forwarder was previously registered to DOM Broker
+     * or to Bidning Broker this method is noop to prevent
+     * creating forwarding loop.
+     *
+     */
+    public void registerToDOMBroker() {
+        if(!registrationInProgress && forwarderRegistration == null) {
+            registrationInProgress = true;
+            CompositeObjectRegistration.CompositeObjectRegistrationBuilder<DomToBindingRpcForwarder> builder = CompositeObjectRegistration.builderFor(this);
+            try {
+                for (QName rpc : supportedRpcs) {
+                    builder.add(biRpcRegistry.addRpcImplementation(rpc, this));
+                }
+            } catch (Exception e) {
+                LOG.error("Could not forward Rpcs of type {}", rpcServiceType.get(), e);
+            }
+            this.forwarderRegistration = builder.toInstance();
+            registrationInProgress = false;
+        }
+    }
+
+
+    public void registerPaths(final Class<? extends BaseIdentity> context,
+        final Class<? extends RpcService> service, final Set<InstanceIdentifier<?>> set) {
+        QName ctx = BindingReflections.findQName(context);
+        for (org.opendaylight.yangtools.yang.data.api.InstanceIdentifier path : FluentIterable.from(set).transform(
+            toDOMInstanceIdentifier)) {
+            for (org.opendaylight.controller.sal.core.api.Broker.RoutedRpcRegistration reg : registrations) {
+                reg.registerPath(ctx, path);
+            }
+        }
+    }
+
+    @Override
+    public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
+        if (EQUALS_METHOD.equals(method)) {
+            return false;
+        }
+        RpcInvocationStrategy strategy = strategiesByMethod.get(method);
+        checkState(strategy != null);
+        checkArgument(args.length <= 2);
+        if (args.length == 1) {
+            checkArgument(args[0] instanceof DataObject);
+            return strategy.forwardToDomBroker((DataObject) args[0]);
+        }
+        return strategy.forwardToDomBroker(null);
+    }
+
+    public void removePaths(final Class<? extends BaseIdentity> context, final Class<? extends RpcService> service,
+        final Set<InstanceIdentifier<?>> set) {
+        QName ctx = BindingReflections.findQName(context);
+        for (org.opendaylight.yangtools.yang.data.api.InstanceIdentifier path : FluentIterable.from(set).transform(
+            toDOMInstanceIdentifier)) {
+            for (org.opendaylight.controller.sal.core.api.Broker.RoutedRpcRegistration reg : registrations) {
+                reg.unregisterPath(ctx, path);
+            }
+        }
+    }
+
+    @Override
+    public Set<QName> getSupportedRpcs() {
+        return supportedRpcs;
+    }
+
+    @SuppressWarnings({ "unchecked", "rawtypes" })
+    public void createDefaultDomForwarder() {
+        if (baRpcRegistryImpl != null) {
+            Class<?> cls = rpcServiceType.get();
+            ClassLoader clsLoader = cls.getClassLoader();
+            RpcService proxy = (RpcService) Proxy.newProxyInstance(clsLoader, new Class<?>[] { cls }, this);
+
+            RpcRouter rpcRouter = baRpcRegistryImpl.getRpcRouter(rpcServiceType.get());
+            rpcRouter.registerDefaultService(proxy);
+        }
+    }
+
+    @Override
+    public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(final QName rpc, final CompositeNode domInput) {
+        checkArgument(rpc != null);
+        checkArgument(domInput != null);
+
+        Class<? extends RpcService> rpcType = rpcServiceType.get();
+        checkState(rpcType != null);
+        RpcService rpcService = baRpcRegistry.getRpcService(rpcType);
+        checkState(rpcService != null);
+        CompositeNode domUnwrappedInput = domInput.getFirstCompositeByName(QName.create(rpc, "input"));
+
+        try {
+            return Futures.immediateFuture(resolveInvocationStrategy(rpc).invokeOn(rpcService, domUnwrappedInput));
+        } catch (Exception e) {
+            return Futures.immediateFailedFuture(e);
+        }
+    }
+
+    private RpcInvocationStrategy resolveInvocationStrategy(final QName rpc) {
+        return strategiesByQName.get(rpc);
+    }
+
+    private RpcInvocationStrategy createInvocationStrategy(final QName rpc,
+        final Class<? extends RpcService> rpcType, final BindingIndependentMappingService mappingService) throws Exception {
+        return ClassLoaderUtils.withClassLoader(rpcType.getClassLoader(), new Callable<RpcInvocationStrategy>() {
+            @Override
+            public RpcInvocationStrategy call() throws Exception {
+                String methodName = BindingMapping.getMethodName(rpc);
+                Method targetMethod = null;
+                for (Method possibleMethod : rpcType.getMethods()) {
+                    if (possibleMethod.getName().equals(methodName)
+                        && BindingReflections.isRpcMethod(possibleMethod)) {
+                        targetMethod = possibleMethod;
+                        break;
+                    }
+                }
+                checkState(targetMethod != null, "Rpc method not found");
+                return new RpcInvocationStrategy(rpc, targetMethod, mappingService, biRpcRegistry);
+            }
+
+        });
+    }
+
+    /**
+     * Registers RPC Forwarder to Binding Broker,
+     * this means DOM Broekr has implementation of RPC
+     * which is registered to it.
+     *
+     * If RPC Forwarder was previously registered to DOM Broker
+     * or to Bidning Broker this method is noop to prevent
+     * creating forwarding loop.
+     *
+     */
+    public void registerToBindingBroker() {
+        if(!registrationInProgress && forwarderRegistration == null) {
+            try {
+                registrationInProgress = true;
+                this.forwarderRegistration = baRpcRegistry.addRpcImplementation((Class)rpcServiceType.get(), proxy);
+            } catch (Exception e) {
+                LOG.error("Unable to forward RPCs for {}",rpcServiceType.get(),e);
+            } finally {
+                registrationInProgress = false;
+            }
+        }
+    }
+}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/DomToBindingRpcForwardingManager.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/DomToBindingRpcForwardingManager.java
new file mode 100644 (file)
index 0000000..63d4b71
--- /dev/null
@@ -0,0 +1,115 @@
+package org.opendaylight.controller.sal.binding.impl.connect.dom;
+
+import java.util.Map;
+import java.util.Set;
+import java.util.WeakHashMap;
+
+import org.opendaylight.controller.md.sal.common.api.routing.RouteChange;
+import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
+import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
+import org.opendaylight.controller.sal.binding.api.rpc.RpcContextIdentifier;
+import org.opendaylight.controller.sal.binding.api.rpc.RpcRouter;
+import org.opendaylight.controller.sal.binding.impl.RpcProviderRegistryImpl;
+import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
+import org.opendaylight.controller.sal.core.api.RpcRegistrationListener;
+import org.opendaylight.yangtools.yang.binding.BaseIdentity;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.binding.RpcService;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
+
+import com.google.common.base.Optional;
+
+/**
+ * Manager responsible for instantiating forwarders responsible for
+ * forwarding of RPC invocations from DOM Broker to Binding Aware Broker
+ *
+ */
+class DomToBindingRpcForwardingManager implements
+    RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>>,
+    RpcProviderRegistryImpl.RouterInstantiationListener,
+    RpcProviderRegistryImpl.GlobalRpcRegistrationListener, RpcRegistrationListener {
+
+    private final Map<Class<? extends RpcService>, DomToBindingRpcForwarder> forwarders = new WeakHashMap<>();
+    private final BindingIndependentMappingService mappingService;
+    private final RpcProvisionRegistry biRpcRegistry;
+    private final RpcProviderRegistry baRpcRegistry;
+    private RpcProviderRegistryImpl registryImpl;
+
+    DomToBindingRpcForwardingManager(final BindingIndependentMappingService mappingService, final RpcProvisionRegistry biRpcRegistry,
+        final RpcProviderRegistry baRpcRegistry) {
+        this.mappingService = mappingService;
+        this.biRpcRegistry = biRpcRegistry;
+        this.baRpcRegistry = baRpcRegistry;
+    }
+
+    public RpcProviderRegistryImpl getRegistryImpl() {
+        return registryImpl;
+    }
+
+    public void setRegistryImpl(final RpcProviderRegistryImpl registryImpl) {
+        this.registryImpl = registryImpl;
+    }
+
+    @Override
+    public void onGlobalRpcRegistered(final Class<? extends RpcService> cls) {
+        getRpcForwarder(cls, null).registerToDOMBroker();
+    }
+
+    @Override
+    public void onGlobalRpcUnregistered(final Class<? extends RpcService> cls) {
+        // NOOP
+    }
+
+    @Override
+    public void onRpcRouterCreated(final RpcRouter<?> router) {
+        Class<? extends BaseIdentity> ctx = router.getContexts().iterator().next();
+        getRpcForwarder(router.getServiceType(), ctx);
+    }
+
+    @Override
+    public void onRouteChange(final RouteChange<RpcContextIdentifier, InstanceIdentifier<?>> change) {
+        for (Map.Entry<RpcContextIdentifier, Set<InstanceIdentifier<?>>> entry : change.getAnnouncements().entrySet()) {
+            bindingRoutesAdded(entry);
+        }
+    }
+
+    private void bindingRoutesAdded(final Map.Entry<RpcContextIdentifier, Set<InstanceIdentifier<?>>> entry) {
+        Class<? extends BaseIdentity> context = entry.getKey().getRoutingContext();
+        Class<? extends RpcService> service = entry.getKey().getRpcService();
+        if (context != null) {
+            getRpcForwarder(service, context).registerPaths(context, service, entry.getValue());
+        }
+    }
+
+    private DomToBindingRpcForwarder getRpcForwarder(final Class<? extends RpcService> service,
+        final Class<? extends BaseIdentity> context) {
+        DomToBindingRpcForwarder potential = forwarders.get(service);
+        if (potential != null) {
+            return potential;
+        }
+        if (context == null) {
+            potential = new DomToBindingRpcForwarder(service, mappingService, biRpcRegistry, baRpcRegistry,registryImpl);
+        } else {
+            potential = new DomToBindingRpcForwarder(service, context, mappingService, biRpcRegistry, baRpcRegistry,registryImpl);
+        }
+
+        forwarders.put(service, potential);
+        return potential;
+    }
+
+    @Override
+    public void onRpcImplementationAdded(final QName name) {
+
+        final Optional<Class<? extends RpcService>> rpcInterface = mappingService.getRpcServiceClassFor(
+            name.getNamespace().toString(), name.getFormattedRevision());
+        if (rpcInterface.isPresent()) {
+            getRpcForwarder(rpcInterface.get(), null).registerToBindingBroker();
+        }
+    }
+
+    @Override
+    public void onRpcImplementationRemoved(final QName name) {
+
+    }
+}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/DomToBindingTransaction.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/connect/dom/DomToBindingTransaction.java
new file mode 100644 (file)
index 0000000..cb271a1
--- /dev/null
@@ -0,0 +1,60 @@
+package org.opendaylight.controller.sal.binding.impl.connect.dom;
+
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+
+import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
+import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler;
+import org.opendaylight.controller.md.sal.common.api.data.DataModification;
+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.InstanceIdentifier;
+
+class DomToBindingTransaction implements
+    DataCommitHandler.DataCommitTransaction<InstanceIdentifier, CompositeNode> {
+
+    private final org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction backing;
+    private final DataModification<InstanceIdentifier, CompositeNode> modification;
+    private final ConcurrentMap<Object, DomToBindingTransaction> bindingOpenedTransactions;
+
+    public DomToBindingTransaction(
+    final org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction backing,
+    final DataModification<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> modification,
+        ConcurrentMap<Object, DomToBindingTransaction> bindingOpenedTransactions) {
+        super();
+        this.backing = backing;
+        this.modification = modification;
+        this.bindingOpenedTransactions = bindingOpenedTransactions;
+        this.bindingOpenedTransactions.put(backing.getIdentifier(), this);
+    }
+
+    @Override
+    public DataModification<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> getModification() {
+        return modification;
+    }
+
+    @Override
+    public RpcResult<Void> rollback() throws IllegalStateException {
+        bindingOpenedTransactions.remove(backing.getIdentifier());
+        return RpcResultBuilder.<Void> success().build();
+    }
+
+    @Override
+    public RpcResult<Void> finish() throws IllegalStateException {
+        Future<RpcResult<TransactionStatus>> result = backing.commit();
+        try {
+            RpcResult<TransactionStatus> baResult = result.get();
+            bindingOpenedTransactions.remove(backing.getIdentifier());
+            return RpcResultBuilder.<Void> status(baResult.isSuccessful())
+                                          .withRpcErrors(baResult.getErrors()).build();
+        } catch (InterruptedException e) {
+            throw new IllegalStateException("", e);
+        } catch (ExecutionException e) {
+            throw new IllegalStateException("", e);
+        } finally {
+            bindingOpenedTransactions.remove(backing.getIdentifier());
+        }
+    }
+}
index d08b217e71c547ea3cd2aa3dcb24a0b3374e9744..f03d07eb99c0fc2ae212cc358402ba67c17a4a74 100644 (file)
@@ -10,19 +10,17 @@ package org.opendaylight.controller.sal.binding.impl.connect.dom;
 
 import java.lang.ref.WeakReference;
 import java.lang.reflect.Method;
-import java.util.Collection;
 import java.util.Collections;
 import java.util.concurrent.Future;
 
-import org.opendaylight.controller.sal.common.util.Rpcs;
 import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
 import org.opendaylight.yangtools.yang.binding.DataContainer;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.RpcService;
 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.RpcError;
 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.Node;
 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
@@ -89,7 +87,7 @@ public class RpcInvocationStrategy {
     public ListenableFuture<RpcResult<?>> forwardToDomBroker(final DataObject input) {
 
         if(biRpcRegistry == null) {
-            return Futures.<RpcResult<?>> immediateFuture(Rpcs.getRpcResult(false));
+            return Futures.<RpcResult<?>> immediateFuture(RpcResultBuilder.failed().build());
         }
 
         CompositeNode inputXml = null;
@@ -102,6 +100,7 @@ public class RpcInvocationStrategy {
 
         Function<RpcResult<CompositeNode>, RpcResult<?>> transformationFunction =
                                        new Function<RpcResult<CompositeNode>, RpcResult<?>>() {
+            @SuppressWarnings("rawtypes")
             @Override
             public RpcResult<?> apply(RpcResult<CompositeNode> result) {
 
@@ -114,7 +113,7 @@ public class RpcInvocationStrategy {
                     }
                 }
 
-                return Rpcs.getRpcResult(result.isSuccessful(), output, result.getErrors());
+                return RpcResultBuilder.from( (RpcResult)result ).withResult( output ).build();
             }
         };
 
@@ -135,22 +134,18 @@ public class RpcInvocationStrategy {
         }
 
         if (futureResult == null) {
-            return Rpcs.getRpcResult(false);
+            return RpcResultBuilder.<CompositeNode>failed().build();
         }
 
-        RpcResult<?> bindingResult = futureResult.get();
-
-        Collection<RpcError> errors = bindingResult.getErrors();
-        if( errors == null ) {
-            errors = Collections.<RpcError>emptySet();
-        }
+        @SuppressWarnings("rawtypes")
+        RpcResult bindingResult = futureResult.get();
 
         final Object resultObj = bindingResult.getResult();
-        CompositeNode output = null;
+        Object output = null;
         if (resultObj instanceof DataObject) {
             output = mappingService.toDataDom((DataObject)resultObj);
         }
-        return Rpcs.getRpcResult( bindingResult.isSuccessful(), output, errors);
+        return RpcResultBuilder.from( bindingResult ).withResult( output ).build();
     }
 
     public RpcResult<CompositeNode> invokeOn(final RpcService rpcService, final CompositeNode domInput) throws Exception {
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/package-info.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/package-info.java
deleted file mode 100644 (file)
index e5f26b9..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-/*
-  * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
-  *
-  * This program and the accompanying materials are made available under the
-  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
-  * and is available at http://www.eclipse.org/legal/epl-v10.html
-  */
-package org.opendaylight.controller.sal.binding.impl;
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/util/MapUtils.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/impl/util/MapUtils.java
deleted file mode 100644 (file)
index aa6a9a2..0000000
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sal.binding.impl.util;
-
-import com.google.common.collect.Multimap;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.Map.Entry;
-import org.opendaylight.yangtools.concepts.Path;
-
-@SuppressWarnings("all")
-public class MapUtils {
-  public static <P extends Path<P>, V extends Object> Collection<Entry<? extends P,? extends V>> getAllChildren(final Multimap<? extends P,? extends V> map, final P path) {
-    HashSet<Entry<? extends P,? extends V>> _hashSet = new HashSet<Entry<? extends P, ? extends V>>();
-    final HashSet<Entry<? extends P,? extends V>> ret = _hashSet;
-    final Collection<? extends Entry<? extends P,? extends V>> entries = map.entries();
-    for (final Entry<? extends P,? extends V> entry : entries) {
-      {
-        final P currentPath = entry.getKey();
-        if (path.contains(currentPath)) {
-          ret.add(entry);
-        } else if (currentPath.contains(path)){
-            ret.add(entry);
-        }
-      }
-    }
-    return ret;
-  }
-}
-
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/spi/DelegateProxy.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/spi/DelegateProxy.java
deleted file mode 100644 (file)
index d22335e..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.binding.spi;
-
-public interface DelegateProxy<T> {
-
-    void setDelegate(T delegate);
-    T getDelegate();
-}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/spi/remote/RouteChangeListener.java b/opendaylight/md-sal/sal-binding-broker/src/main/java/org/opendaylight/controller/sal/binding/spi/remote/RouteChangeListener.java
deleted file mode 100644 (file)
index 9e66fb8..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.binding.spi.remote;
-
-import java.util.EventListener;
-
-import org.opendaylight.controller.md.sal.common.api.routing.RouteChange;
-import org.opendaylight.yangtools.yang.binding.BaseIdentity;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-
-public interface RouteChangeListener extends EventListener {
-
-    void onRouteChange(RouteChange<Class<? extends BaseIdentity>, InstanceIdentifier<?>> change);
-
-}
index 4456dea77f98fad1f4f43c79f67b224d9e44990e..cee4b1efb3a3107e27fa5325dd6d3f92cc937609 100644 (file)
@@ -105,7 +105,7 @@ module opendaylight-sal-binding-broker-impl {
             container data-broker {
                 uses config:service-ref {
                     refine type {
-                        mandatory true;
+                        mandatory false;
                         config:required-identity sal:binding-data-broker;
                     }
                 }
@@ -119,6 +119,15 @@ module opendaylight-sal-binding-broker-impl {
                     }
                 }
             }
+
+            container root-data-broker {
+                uses config:service-ref {
+                    refine type {
+                        mandatory false;
+                        config:required-identity sal:binding-async-data-broker;
+                    }
+                }
+            }
         }
     }
 
diff --git a/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/test/BindingNormalizedCodecTest.java b/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/test/BindingNormalizedCodecTest.java
new file mode 100644 (file)
index 0000000..6b05b10
--- /dev/null
@@ -0,0 +1,58 @@
+package org.opendaylight.controller.md.sal.binding.impl.test;
+
+import static org.junit.Assert.assertTrue;
+import javassist.ClassPool;
+
+import org.junit.Test;
+import org.opendaylight.controller.md.sal.binding.impl.BindingToNormalizedNodeCodec;
+import org.opendaylight.controller.md.sal.binding.test.AbstractSchemaAwareTest;
+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.augment.rev140709.TreeLeafOnlyAugment;
+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.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListKey;
+import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.AugmentationIdentifier;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+public class BindingNormalizedCodecTest extends AbstractSchemaAwareTest {
+
+    private static final TopLevelListKey TOP_FOO_KEY = new TopLevelListKey("foo");
+    private static final InstanceIdentifier<TopLevelList> BA_TOP_LEVEL_LIST = InstanceIdentifier
+            .builder(Top.class).child(TopLevelList.class, TOP_FOO_KEY).toInstance();
+    private static final InstanceIdentifier<TreeLeafOnlyAugment> BA_TREE_LEAF_ONLY = BA_TOP_LEVEL_LIST.augmentation(TreeLeafOnlyAugment.class);
+    private static final InstanceIdentifier<TreeComplexUsesAugment> BA_TREE_COMPLEX_USES = BA_TOP_LEVEL_LIST.augmentation(TreeComplexUsesAugment.class);
+    private static final QName SIMPLE_VALUE_QNAME = QName.create(TreeComplexUsesAugment.QNAME, "simple-value");
+
+
+    private RuntimeGeneratedMappingServiceImpl mappingService;
+    private BindingToNormalizedNodeCodec codec;
+
+    @Override
+    protected void setupWithSchema(final SchemaContext context) {
+        mappingService = new RuntimeGeneratedMappingServiceImpl(ClassPool.getDefault());
+        codec = new BindingToNormalizedNodeCodec(mappingService);
+        mappingService.onGlobalContextUpdated(context);
+        codec.onGlobalContextUpdated(context);
+    };
+
+    @Test
+    public void testComplexAugmentationSerialization() {
+
+        PathArgument lastArg = codec.toNormalized(BA_TREE_COMPLEX_USES).getLastPathArgument();
+        assertTrue(lastArg instanceof AugmentationIdentifier);
+    }
+
+
+    @Test
+    public void testLeafOnlyAugmentationSerialization() {
+
+        PathArgument leafOnlyLastArg = codec.toNormalized(BA_TREE_LEAF_ONLY).getLastPathArgument();
+        assertTrue(leafOnlyLastArg instanceof AugmentationIdentifier);
+        assertTrue(((AugmentationIdentifier) leafOnlyLastArg).getPossibleChildNames().contains(SIMPLE_VALUE_QNAME));
+    }
+
+}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/test/Bug1125RegressionTest.java b/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/test/Bug1125RegressionTest.java
new file mode 100644 (file)
index 0000000..9f1ae38
--- /dev/null
@@ -0,0 +1,99 @@
+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.test.model.util.ListsBindingUtils.TOP_FOO_KEY;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.path;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.topLevelList;
+
+import org.junit.Test;
+import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
+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.augment.rev140709.TreeComplexUsesAugmentBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.complex.from.grouping.ContainerWithUsesBuilder;
+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.TopBuilder;
+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;
+
+/**
+ * Regression test suite for Bug 1125 - Can't detect switch disconnection
+ * https://bugs.opendaylight.org/show_bug.cgi?id=1125
+ */
+public class Bug1125RegressionTest extends AbstractDataChangeListenerTest {
+
+    private static final InstanceIdentifier<Top> TOP_PATH = InstanceIdentifier
+            .create(Top.class);
+    private static final InstanceIdentifier<TopLevelList> TOP_FOO_PATH = TOP_PATH
+            .child(TopLevelList.class, TOP_FOO_KEY);
+
+    private static final InstanceIdentifier<TreeComplexUsesAugment> FOO_AUGMENT_PATH = TOP_FOO_PATH
+            .augmentation(TreeComplexUsesAugment.class);
+
+    private static final InstanceIdentifier<TreeComplexUsesAugment> WILDCARDED_AUGMENT_PATH = TOP_PATH
+            .child(TopLevelList.class).augmentation(
+                    TreeComplexUsesAugment.class);
+
+    private void writeInitialState() {
+        WriteTransaction initialTx = getDataBroker().newWriteOnlyTransaction();
+        initialTx.put(LogicalDatastoreType.OPERATIONAL, TOP_PATH,
+                new TopBuilder().build());
+        TreeComplexUsesAugment fooAugment = new TreeComplexUsesAugmentBuilder()
+                .setContainerWithUses(
+                        new ContainerWithUsesBuilder().setLeafFromGrouping(
+                                "foo").build()).build();
+        initialTx.put(LogicalDatastoreType.OPERATIONAL, path(TOP_FOO_KEY),
+                topLevelList(TOP_FOO_KEY, fooAugment));
+        assertCommit(initialTx.commit());
+    }
+
+    private void delete(final InstanceIdentifier<?> path) {
+        WriteTransaction tx = getDataBroker().newWriteOnlyTransaction();
+        tx.delete(LogicalDatastoreType.OPERATIONAL, path);
+        assertCommit(tx.commit());
+    }
+
+    private void verifyRemoved(
+            final AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> event) {
+        assertEmpty(event.getCreatedData());
+        assertEmpty(event.getUpdatedData());
+        assertContains(event.getRemovedPaths(), FOO_AUGMENT_PATH);
+    }
+
+    private void deleteAndListenAugment(final DataChangeScope scope,
+            final InstanceIdentifier<?> path) {
+        writeInitialState();
+        TestListener listener = createListener(
+                LogicalDatastoreType.OPERATIONAL, WILDCARDED_AUGMENT_PATH,
+                scope);
+        delete(path);
+        verifyRemoved(listener.event());
+    }
+
+    @Test
+    public void deleteAndListenAugment() {
+
+        deleteAndListenAugment(DataChangeScope.ONE, TOP_PATH);
+
+        deleteAndListenAugment(DataChangeScope.BASE, TOP_PATH);
+
+        deleteAndListenAugment(DataChangeScope.SUBTREE, TOP_PATH);
+
+        deleteAndListenAugment(DataChangeScope.BASE, TOP_FOO_PATH);
+
+        deleteAndListenAugment(DataChangeScope.ONE, TOP_FOO_PATH);
+
+        deleteAndListenAugment(DataChangeScope.SUBTREE, TOP_FOO_PATH);
+
+        deleteAndListenAugment(DataChangeScope.BASE, FOO_AUGMENT_PATH);
+
+        deleteAndListenAugment(DataChangeScope.ONE, FOO_AUGMENT_PATH);
+
+        deleteAndListenAugment(DataChangeScope.SUBTREE, FOO_AUGMENT_PATH);
+    }
+}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/test/ListInsertionDataChangeListenerTest.java b/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/test/ListInsertionDataChangeListenerTest.java
new file mode 100644 (file)
index 0000000..05bc857
--- /dev/null
@@ -0,0 +1,193 @@
+/*
+ * 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.junit.Assert.assertFalse;
+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_BAR_KEY;
+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.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.DataBroker;
+import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
+import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
+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.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 tests explanation for data change scope and data modifications
+ * which were described in
+ * https://lists.opendaylight.org/pipermail/controller-dev/2014-July/005541.html
+ *
+ *
+ */
+public class ListInsertionDataChangeListenerTest extends AbstractDataChangeListenerTest{
+
+    private static final InstanceIdentifier<Top> TOP = InstanceIdentifier.create(Top.class);
+    private static final InstanceIdentifier<TopLevelList> WILDCARDED = TOP.child(TopLevelList.class);
+    private static final InstanceIdentifier<TopLevelList> TOP_FOO = TOP.child(TopLevelList.class, TOP_FOO_KEY);
+    private static final InstanceIdentifier<TopLevelList> TOP_BAR = TOP.child(TopLevelList.class, TOP_BAR_KEY);
+
+
+    @Override
+    protected void setupWithDataBroker(final DataBroker dataBroker) {
+        WriteTransaction initialTx = dataBroker.newWriteOnlyTransaction();
+        initialTx.put(CONFIGURATION, TOP, top(topLevelList(TOP_FOO_KEY)));
+        assertCommit(initialTx.commit());
+    }
+
+    @Test
+    public void replaceTopNodeSubtreeListeners() {
+        TestListener topListener = createListener(CONFIGURATION, TOP, DataChangeScope.SUBTREE);
+        TestListener allListener = createListener(CONFIGURATION, WILDCARDED, DataChangeScope.SUBTREE);
+        TestListener fooListener = createListener(CONFIGURATION, TOP_FOO, DataChangeScope.SUBTREE);
+        TestListener barListener = createListener(CONFIGURATION, TOP_BAR, DataChangeScope.SUBTREE);
+
+        ReadWriteTransaction writeTx = getDataBroker().newReadWriteTransaction();
+        writeTx.put(CONFIGURATION, TOP, top(topLevelList(TOP_BAR_KEY)));
+        assertCommit(writeTx.commit());
+        AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> top = topListener.event();
+        AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> all = allListener.event();
+        AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> foo = fooListener.event();
+        AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> bar = barListener.event();
+
+        // Listener for TOP element
+        assertContains(top.getOriginalData(), TOP,TOP_FOO);
+        assertContains(top.getCreatedData(), TOP_BAR);
+        assertContains(top.getUpdatedData(), TOP);
+        assertContains(top.getRemovedPaths(), TOP_FOO);
+
+        /*
+         *  Listener for all list items
+         *
+         *  Updated should be empty, since no list item was
+         *  updated, items were only removed and added
+         */
+        assertContains(all.getOriginalData(), TOP_FOO);
+        assertContains(all.getCreatedData(), TOP_BAR);
+        assertEmpty(all.getUpdatedData());
+        assertContains(all.getRemovedPaths(), TOP_FOO);
+
+
+        /*
+         *  Listener for all Foo item
+         *
+         *  This one should see only Foo item removed
+         */
+        assertContains(foo.getOriginalData(), TOP_FOO);
+        assertEmpty(foo.getCreatedData());
+        assertEmpty(foo.getUpdatedData());
+        assertContains(foo.getRemovedPaths(), TOP_FOO);
+
+        /*
+         *  Listener for bar list items
+         *
+         *  Updated should be empty, since no list item was
+         *  updated, items were only removed and added
+         */
+        assertEmpty(bar.getOriginalData());
+        assertContains(bar.getCreatedData(), TOP_BAR);
+        assertEmpty(bar.getUpdatedData());
+        assertEmpty(bar.getRemovedPaths());
+    }
+
+    @Test
+    public void mergeTopNodeSubtreeListeners() {
+        TestListener topListener = createListener(CONFIGURATION, TOP, DataChangeScope.SUBTREE);
+        TestListener allListener = createListener(CONFIGURATION, WILDCARDED, DataChangeScope.SUBTREE);
+        TestListener fooListener = createListener(CONFIGURATION, TOP_FOO, DataChangeScope.SUBTREE);
+        TestListener barListener = createListener(CONFIGURATION, TOP_BAR, DataChangeScope.SUBTREE);
+
+        ReadWriteTransaction writeTx = getDataBroker().newReadWriteTransaction();
+        writeTx.merge(CONFIGURATION, TOP, top(topLevelList(TOP_BAR_KEY)));
+        assertCommit(writeTx.commit());
+
+        verifyBarOnlyAdded(topListener,allListener,fooListener,barListener);
+    }
+
+    @Test
+    public void putTopBarNodeSubtreeListeners() {
+        TestListener topListener = createListener(CONFIGURATION, TOP, DataChangeScope.SUBTREE);
+        TestListener allListener = createListener(CONFIGURATION, WILDCARDED, DataChangeScope.SUBTREE);
+        TestListener fooListener = createListener(CONFIGURATION, TOP_FOO, DataChangeScope.SUBTREE);
+        TestListener barListener = createListener(CONFIGURATION, TOP_BAR, DataChangeScope.SUBTREE);
+
+        ReadWriteTransaction writeTx = getDataBroker().newReadWriteTransaction();
+        writeTx.put(CONFIGURATION, TOP_BAR, topLevelList(TOP_BAR_KEY));
+        assertCommit(writeTx.commit());
+
+        verifyBarOnlyAdded(topListener,allListener,fooListener,barListener);
+    }
+
+    @Test
+    public void mergeTopBarNodeSubtreeListeners() {
+        TestListener topListener = createListener(CONFIGURATION, TOP, DataChangeScope.SUBTREE);
+        TestListener allListener = createListener(CONFIGURATION, WILDCARDED, DataChangeScope.SUBTREE);
+        TestListener fooListener = createListener(CONFIGURATION, TOP_FOO, DataChangeScope.SUBTREE);
+        TestListener barListener = createListener(CONFIGURATION, TOP_BAR, DataChangeScope.SUBTREE);
+
+        ReadWriteTransaction writeTx = getDataBroker().newReadWriteTransaction();
+        writeTx.merge(CONFIGURATION, TOP_BAR, topLevelList(TOP_BAR_KEY));
+        assertCommit(writeTx.commit());
+
+        verifyBarOnlyAdded(topListener,allListener,fooListener,barListener);
+    }
+
+    private void verifyBarOnlyAdded(final TestListener top, final TestListener all, final TestListener foo,
+            final TestListener bar) {
+
+        assertFalse(foo.hasEvent());
+
+        // Listener for TOP element
+        assertContains(top.event().getOriginalData(), TOP);
+        assertNotContains(top.event().getOriginalData(),TOP_FOO);
+        assertContains(top.event().getCreatedData(), TOP_BAR);
+        assertContains(top.event().getUpdatedData(), TOP);
+        assertEmpty(top.event().getRemovedPaths());
+
+        /*
+         *  Listener for all list items
+         *
+         *  Updated should be empty, since no list item was
+         *  updated, items were only removed and added
+         */
+        assertEmpty(all.event().getOriginalData());
+        assertContains(all.event().getCreatedData(), TOP_BAR);
+        assertEmpty(all.event().getUpdatedData());
+        assertEmpty(all.event().getRemovedPaths());
+
+        /*
+         *  Listener for all Foo item
+         *
+         *  Foo Listener should not have foo event
+         */
+        assertFalse(foo.hasEvent());
+
+        /*
+         *  Listener for bar list items
+         *
+         *  Updated should be empty, since no list item was
+         *  updated, items were only removed and added
+         */
+        assertEmpty(bar.event().getOriginalData());
+        assertContains(bar.event().getCreatedData(), TOP_BAR);
+        assertEmpty(bar.event().getUpdatedData());
+        assertEmpty(bar.event().getRemovedPaths());
+    }
+
+}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/test/RpcProviderRegistryTest.java b/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/test/RpcProviderRegistryTest.java
new file mode 100644 (file)
index 0000000..110e5b4
--- /dev/null
@@ -0,0 +1,137 @@
+package org.opendaylight.controller.md.sal.binding.impl.test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.fail;
+import static org.opendaylight.controller.md.sal.test.model.util.ListsBindingUtils.TOP_BAR_KEY;
+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.path;
+
+import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.opendaylight.controller.md.sal.binding.test.AssertCollections;
+import org.opendaylight.controller.md.sal.common.api.routing.RouteChange;
+import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
+import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RoutedRpcRegistration;
+import org.opendaylight.controller.sal.binding.api.BindingAwareBroker.RpcRegistration;
+import org.opendaylight.controller.sal.binding.api.rpc.RpcContextIdentifier;
+import org.opendaylight.controller.sal.binding.api.rpc.RpcRouter;
+import org.opendaylight.controller.sal.binding.impl.RpcProviderRegistryImpl;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.bi.ba.rpcservice.rev140701.OpendaylightTestRpcServiceService;
+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.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.rpc.routing.rev140701.OpendaylightTestRoutedRpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.rpc.routing.rev140701.TestContext;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+import com.google.common.util.concurrent.SettableFuture;
+
+
+public class RpcProviderRegistryTest {
+
+    private static InstanceIdentifier<TopLevelList> FOO_PATH = path(TOP_FOO_KEY);
+    private static InstanceIdentifier<TopLevelList> BAR_PATH = path(TOP_BAR_KEY);
+    private static RpcContextIdentifier ROUTING_CONTEXT = RpcContextIdentifier.contextFor(OpendaylightTestRoutedRpcService.class, TestContext.class);
+
+    private RpcProviderRegistryImpl rpcRegistry;
+
+    @Before
+    public void setup() {
+        rpcRegistry = new RpcProviderRegistryImpl("test");
+    }
+
+    private static class TestListener implements RouteChangeListener<RpcContextIdentifier, InstanceIdentifier<?>> {
+
+        final SettableFuture<RouteChange<RpcContextIdentifier, InstanceIdentifier<?>>> event = SettableFuture.create();
+        @Override
+        public void onRouteChange(
+                final RouteChange<RpcContextIdentifier, InstanceIdentifier<?>> change) {
+            event.set(change);
+        }
+    }
+
+    @Test
+    public void testGlobalRpcRegistrations() throws Exception {
+        OpendaylightTestRpcServiceService one = Mockito.mock(OpendaylightTestRpcServiceService.class);
+        OpendaylightTestRpcServiceService two = Mockito.mock(OpendaylightTestRpcServiceService.class);
+
+        RpcRegistration<OpendaylightTestRpcServiceService> regOne = rpcRegistry.addRpcImplementation(OpendaylightTestRpcServiceService.class, one);
+        assertNotNull(regOne);
+
+        try {
+            rpcRegistry.addRpcImplementation(OpendaylightTestRpcServiceService.class, two);
+        fail("Second call for registration of same RPC must throw IllegalStateException");
+        } catch (IllegalStateException e) {
+            assertNotNull(e.getMessage());
+        }
+
+        regOne.close();
+
+        RpcRegistration<OpendaylightTestRpcServiceService> regTwo = rpcRegistry.addRpcImplementation(OpendaylightTestRpcServiceService.class, two);
+        assertNotNull(regTwo);
+    }
+
+    @Test
+    public void testRpcRouterInstance() throws Exception  {
+        OpendaylightTestRoutedRpcService def = Mockito.mock(OpendaylightTestRoutedRpcService.class);
+
+        RpcRouter<OpendaylightTestRoutedRpcService> router = rpcRegistry.getRpcRouter(OpendaylightTestRoutedRpcService.class);
+
+        assertEquals(OpendaylightTestRoutedRpcService.class, router.getServiceType());
+        assertNotNull(router.getInvocationProxy());
+        assertNull(router.getDefaultService());
+
+        AssertCollections.assertContains(router.getContexts(), TestContext.class);
+
+        RpcRegistration<OpendaylightTestRoutedRpcService> regDef = router.registerDefaultService(def);
+        assertNotNull(regDef);
+        assertEquals(OpendaylightTestRoutedRpcService.class,regDef.getServiceType());
+        assertEquals(def,regDef.getInstance());
+        assertEquals(def, router.getDefaultService());
+
+        regDef.close();
+        assertNull("Default instance should be null after closing registration",  router.getDefaultService());
+    }
+
+    @Test
+    public void testRoutedRpcPathChangeEvents() throws InterruptedException, TimeoutException, ExecutionException {
+        OpendaylightTestRoutedRpcService one = Mockito.mock(OpendaylightTestRoutedRpcService.class);
+        OpendaylightTestRoutedRpcService two = Mockito.mock(OpendaylightTestRoutedRpcService.class);
+        RoutedRpcRegistration<OpendaylightTestRoutedRpcService> regOne = rpcRegistry.addRoutedRpcImplementation(OpendaylightTestRoutedRpcService.class, one);
+        RoutedRpcRegistration<OpendaylightTestRoutedRpcService> regTwo = rpcRegistry.addRoutedRpcImplementation(OpendaylightTestRoutedRpcService.class, two);
+        assertNotNull(regOne);
+        assertNotNull(regTwo);
+
+        final TestListener addListener = new TestListener();
+        rpcRegistry.registerRouteChangeListener(addListener);
+        regOne.registerPath(TestContext.class, FOO_PATH);
+
+        RouteChange<RpcContextIdentifier, InstanceIdentifier<?>> fooAddEvent = addListener.event.get(500, TimeUnit.MILLISECONDS);
+        Set<InstanceIdentifier<?>> announce = fooAddEvent.getAnnouncements().get(ROUTING_CONTEXT);
+        assertNotNull(announce);
+        AssertCollections.assertContains(announce, FOO_PATH);
+        AssertCollections.assertNotContains(announce, BAR_PATH);
+
+
+
+        final TestListener removeListener = new TestListener();
+        rpcRegistry.registerRouteChangeListener(removeListener);
+
+        regOne.unregisterPath(TestContext.class, FOO_PATH);
+
+        RouteChange<RpcContextIdentifier, InstanceIdentifier<?>> fooRemoveEvent = removeListener.event.get(500, TimeUnit.MILLISECONDS);
+        Set<InstanceIdentifier<?>> removal = fooRemoveEvent.getRemovals().get(ROUTING_CONTEXT);
+        assertNotNull(removal);
+        AssertCollections.assertContains(removal, FOO_PATH);
+        AssertCollections.assertNotContains(removal, BAR_PATH);
+
+
+    }
+
+}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/test/WriteTransactionTest.java b/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/impl/test/WriteTransactionTest.java
new file mode 100644 (file)
index 0000000..43e9514
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * 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.junit.Assert.assertEquals;
+
+import java.util.concurrent.ExecutionException;
+
+import org.junit.Test;
+import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
+import org.opendaylight.controller.md.sal.binding.test.AbstractDataBrokerTest;
+import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
+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.list.rev140701.Top;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.TopBuilder;
+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.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListKey;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+
+public class WriteTransactionTest extends AbstractDataBrokerTest {
+
+    private static final InstanceIdentifier<Top> TOP_PATH = InstanceIdentifier.create(Top.class);
+    private static final TopLevelListKey TOP_LIST_KEY = new TopLevelListKey("foo");
+    private static final InstanceIdentifier<TopLevelList> NODE_PATH = TOP_PATH.child(TopLevelList.class, TOP_LIST_KEY);
+
+    @Test
+    public void test() throws InterruptedException, ExecutionException {
+        WriteTransaction writeTx = getDataBroker().newWriteOnlyTransaction();
+        writeTx.put(LogicalDatastoreType.OPERATIONAL, TOP_PATH, new TopBuilder().build());
+        writeTx.put(LogicalDatastoreType.OPERATIONAL, NODE_PATH, new TopLevelListBuilder().setKey(TOP_LIST_KEY).build());
+        assertEquals(TransactionStatus.COMMITED, writeTx.commit().get().getResult());
+    }
+
+}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/test/AbstractDataBrokerTest.java b/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/test/AbstractDataBrokerTest.java
new file mode 100644 (file)
index 0000000..7f23ac2
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.binding.test;
+
+import static org.junit.Assert.assertEquals;
+
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+import com.google.common.util.concurrent.ListenableFuture;
+
+public class AbstractDataBrokerTest extends AbstractSchemaAwareTest {
+
+    private DataBrokerTestCustomizer testCustomizer;
+    private DataBroker dataBroker;
+    private DOMDataBroker domBroker;
+
+
+    @Override
+    protected void setupWithSchema(final SchemaContext context) {
+        testCustomizer = createDataBrokerTestCustomizer();
+        dataBroker = testCustomizer.createDataBroker();
+        domBroker = testCustomizer.createDOMDataBroker();
+        testCustomizer.updateSchema(context);
+        setupWithDataBroker(dataBroker);
+    }
+
+    protected void setupWithDataBroker(final DataBroker dataBroker) {
+        // Intentionally left No-op, subclasses may customize it
+    }
+
+   protected DataBrokerTestCustomizer createDataBrokerTestCustomizer() {
+        return new DataBrokerTestCustomizer();
+    }
+
+    public DataBroker getDataBroker() {
+        return dataBroker;
+    }
+
+    public DOMDataBroker getDomBroker() {
+        return domBroker;
+    }
+
+    protected static final void assertCommit(final ListenableFuture<RpcResult<TransactionStatus>> commit) {
+        try {
+            assertEquals(TransactionStatus.COMMITED,commit.get(500, TimeUnit.MILLISECONDS).getResult());
+        } catch (InterruptedException | ExecutionException | TimeoutException e) {
+            throw new IllegalStateException(e);
+        }
+    }
+
+
+}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/test/AbstractDataChangeListenerTest.java b/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/test/AbstractDataChangeListenerTest.java
new file mode 100644 (file)
index 0000000..7742f37
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.binding.test;
+
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
+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.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+import com.google.common.util.concurrent.SettableFuture;
+
+public abstract class AbstractDataChangeListenerTest extends AbstractDataBrokerTest {
+
+    protected static final class TestListener implements DataChangeListener {
+
+        private final SettableFuture<AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject>> event;
+        private boolean capture = false;
+
+        private TestListener() {
+            event = SettableFuture.create();
+        }
+
+        @Override
+        public void onDataChanged(final AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> arg) {
+            if (capture) {
+                event.set(arg);
+            }
+        }
+
+        public AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> event() {
+            try {
+                return event.get(500, TimeUnit.MILLISECONDS);
+            } catch (InterruptedException | TimeoutException | ExecutionException e) {
+                throw new IllegalStateException(e);
+            }
+        }
+
+        public boolean hasEvent() {
+            return event.isDone();
+        }
+
+        public void startCapture() {
+            this.capture = true;
+        }
+    }
+
+    protected final TestListener createListener(final LogicalDatastoreType store, final InstanceIdentifier<?> path,
+            final DataChangeScope scope) {
+        TestListener listener = new TestListener();
+        getDataBroker().registerDataChangeListener(store, path, listener, scope);
+        listener.startCapture();
+        return listener;
+    }
+}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/test/AbstractSchemaAwareTest.java b/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/test/AbstractSchemaAwareTest.java
new file mode 100644 (file)
index 0000000..78febb5
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.binding.test;
+
+import org.junit.Before;
+import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
+import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
+import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+public abstract class AbstractSchemaAwareTest  {
+
+    private Iterable<YangModuleInfo> moduleInfos;
+    private SchemaContext schemaContext;
+
+
+    protected Iterable<YangModuleInfo> getModuleInfos() {
+        return BindingReflections.loadModuleInfos();
+    }
+
+
+    @Before
+    public final void setup() {
+        moduleInfos = getModuleInfos();
+        ModuleInfoBackedContext moduleContext = ModuleInfoBackedContext.create();
+        moduleContext.addModuleInfos(moduleInfos);
+        schemaContext = moduleContext.tryToCreateSchemaContext().get();
+        setupWithSchema(schemaContext);
+    }
+
+    /**
+     * Setups test with Schema context.
+     * This method is called before {@link #setupWithSchemaService(SchemaService)}
+     *
+     * @param context
+     */
+    protected abstract void setupWithSchema(SchemaContext context);
+
+}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/test/AssertCollections.java b/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/test/AssertCollections.java
new file mode 100644 (file)
index 0000000..25b91bc
--- /dev/null
@@ -0,0 +1,42 @@
+package org.opendaylight.controller.md.sal.binding.test;
+
+import java.util.Collection;
+import java.util.Map;
+
+import org.junit.Assert;
+
+public class AssertCollections {
+
+    public static void assertEmpty(final Collection<?> set) {
+        Assert.assertTrue(set.isEmpty());
+    }
+
+    public static void assertEmpty(final Map<?,?> set) {
+        Assert.assertTrue(set.isEmpty());
+    }
+
+    public static void assertContains(final Collection<?> set, final Object... values) {
+        for (Object key : values) {
+            Assert.assertTrue(set.contains(key));
+        }
+
+    }
+
+    public static void assertNotContains(final Collection<?> set, final Object... values) {
+        for (Object key : values) {
+            Assert.assertFalse(set.contains(key));
+        }
+    }
+
+    public static void assertContains(final Map<?,?> map, final Object... values) {
+        for (Object key : values) {
+            Assert.assertTrue(map.containsKey(key));
+        }
+    }
+
+    public static void assertNotContains(final Map<?,?> map, final Object... values) {
+        for (Object key : values) {
+            Assert.assertFalse(map.containsKey(key));
+        }
+    }
+}
diff --git a/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/test/DataBrokerTestCustomizer.java b/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/md/sal/binding/test/DataBrokerTestCustomizer.java
new file mode 100644 (file)
index 0000000..79aa6b6
--- /dev/null
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.binding.test;
+
+import javassist.ClassPool;
+
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.binding.impl.ForwardedBindingDataBroker;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
+import org.opendaylight.controller.md.sal.dom.broker.impl.DOMDataBrokerImpl;
+import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
+import org.opendaylight.controller.sal.binding.test.util.MockSchemaService;
+import org.opendaylight.controller.sal.core.api.model.SchemaService;
+import org.opendaylight.controller.sal.core.spi.data.DOMStore;
+import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
+import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
+
+public class DataBrokerTestCustomizer {
+
+    private DOMDataBroker domDataBroker;
+    private final RuntimeGeneratedMappingServiceImpl mappingService;
+    private final MockSchemaService schemaService;
+    private ImmutableMap<LogicalDatastoreType, DOMStore> datastores;
+
+    public ImmutableMap<LogicalDatastoreType, DOMStore> createDatastores() {
+        return ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
+                .put(LogicalDatastoreType.OPERATIONAL, createOperationalDatastore())
+                .put(LogicalDatastoreType.CONFIGURATION,createConfigurationDatastore())
+                .build();
+    }
+
+    public DataBrokerTestCustomizer() {
+        schemaService = new MockSchemaService();
+        mappingService = new RuntimeGeneratedMappingServiceImpl(ClassPool.getDefault());
+    }
+
+    public DOMStore createConfigurationDatastore() {
+        InMemoryDOMDataStore store = new InMemoryDOMDataStore("CFG", MoreExecutors.sameThreadExecutor());
+        schemaService.registerSchemaServiceListener(store);
+        return store;
+    }
+
+    public DOMStore createOperationalDatastore() {
+        InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER", MoreExecutors.sameThreadExecutor());
+        schemaService.registerSchemaServiceListener(store);
+        return store;
+    }
+
+    public DOMDataBroker createDOMDataBroker() {
+        return new DOMDataBrokerImpl(getDatastores(), getCommitCoordinatorExecutor());
+    }
+
+    public ListeningExecutorService getCommitCoordinatorExecutor() {
+        return MoreExecutors.sameThreadExecutor();
+    }
+
+    public DataBroker createDataBroker() {
+        return new ForwardedBindingDataBroker(getDOMDataBroker(), getMappingService(), getSchemaService());
+    }
+
+    private SchemaService getSchemaService() {
+        return schemaService;
+    }
+
+    private BindingIndependentMappingService getMappingService() {
+        return mappingService;
+    }
+
+    private DOMDataBroker getDOMDataBroker() {
+        if(domDataBroker == null) {
+            domDataBroker = createDOMDataBroker();
+        }
+        return domDataBroker;
+    }
+
+    private ImmutableMap<LogicalDatastoreType, DOMStore> getDatastores() {
+        if(datastores == null) {
+            datastores = createDatastores();
+        }
+        return datastores;
+    }
+
+    public void updateSchema(final SchemaContext ctx) {
+        schemaService.changeSchema(ctx);
+        mappingService.onGlobalContextUpdated(ctx);
+    }
+
+}
index c5aea8f2ab666cb5e777e3f20d808910ab3308c6..6977588a017265f003de2e9ac0f3bba29383cc2f 100644 (file)
@@ -25,13 +25,13 @@ import org.junit.Before;
 import org.junit.Test;
 import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.sal.common.util.Rpcs;
 import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.RpcService;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.RpcError;
 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.impl.codec.BindingIndependentMappingService;
 
@@ -96,9 +96,11 @@ public class RpcInvocationStrategyTest {
 
     private void setupForForwardToDom(boolean hasOutput, boolean hasInput, int expectedErrorSize) {
 
-        if (expectedErrorSize > 0)
+        if (expectedErrorSize > 0) {
             errors.add(rpcError);
-        RpcResult<CompositeNode> result = Rpcs.getRpcResult(true, invokeRpcResult, errors);
+        }
+        RpcResult<CompositeNode> result = RpcResultBuilder.<CompositeNode>success(invokeRpcResult)
+                                                            .withRpcErrors( errors ).build();
         futureCompNode = Futures.immediateFuture(result);
         if( hasInput )
         {
@@ -191,22 +193,28 @@ public class RpcInvocationStrategyTest {
      * invokeOn Tests
      */
     private void setupRpcResultsWithOutput(int expectedErrorSize) {
-        if (expectedErrorSize > 0)
+        if (expectedErrorSize > 0) {
             errors.add(rpcError);
-        RpcResult<CompositeNode> resultCompNode = Rpcs.getRpcResult(true, inputInvokeOn, errors);
+        }
+        RpcResult<CompositeNode> resultCompNode = RpcResultBuilder.<CompositeNode>success(inputInvokeOn)
+                                                                        .withRpcErrors(errors).build();
         futureCompNode = Futures.immediateFuture(resultCompNode);
-        RpcResult<DataObject> resultDataObj = Rpcs.getRpcResult(true, toDataDomInput, errors);
+        RpcResult<DataObject> resultDataObj = RpcResultBuilder.<DataObject>success(toDataDomInput)
+                                                                           .withRpcErrors(errors).build();
         futureDataObj = Futures.immediateFuture(resultDataObj);
 
         when(mockMappingService.toDataDom(toDataDomInput)).thenReturn(outputInvokeOn);
     }
 
     private void setupRpcResultsNoOutput(int expectedErrorSize) {
-        if (expectedErrorSize > 0)
+        if (expectedErrorSize > 0) {
             errors.add(rpcError);
-        RpcResult<CompositeNode> resultCompNode = Rpcs.getRpcResult(true, inputInvokeOn, errors);
+        }
+        RpcResult<CompositeNode> resultCompNode = RpcResultBuilder.<CompositeNode>success(inputInvokeOn)
+                                                                          .withRpcErrors(errors).build();
         futureCompNode = Futures.immediateFuture(resultCompNode);
-        RpcResult<DataObject> resultDataObj = Rpcs.getRpcResult(true, null, errors);
+        RpcResult<DataObject> resultDataObj = RpcResultBuilder.<DataObject>success()
+                                                                          .withRpcErrors(errors).build();
         futureDataObj = Futures.immediateFuture(resultDataObj);
     }
 
index 6c80f4d7394947cd34af1aa3eedb305dc2f99113..591e07d00440465f1bc6763d8ef4ef1508d9191c 100644 (file)
@@ -7,28 +7,21 @@
  */
 package org.opendaylight.controller.sal.binding.test;
 
-import org.junit.After;
 import org.junit.Before;
 import org.opendaylight.controller.sal.binding.api.data.DataProviderService;
 import org.opendaylight.controller.sal.binding.test.util.BindingBrokerTestFactory;
 import org.opendaylight.controller.sal.binding.test.util.BindingTestContext;
-import org.opendaylight.controller.sal.core.api.data.DataStore;
-import org.opendaylight.controller.sal.dom.broker.impl.DataStoreStatsWrapper;
 import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
 import com.google.common.util.concurrent.ListeningExecutorService;
 import com.google.common.util.concurrent.MoreExecutors;
 
+@SuppressWarnings("deprecation")
 public abstract class AbstractDataServiceTest {
-    private static Logger log = LoggerFactory.getLogger(AbstractDataServiceTest.class);
 
     protected org.opendaylight.controller.sal.core.api.data.DataProviderService biDataService;
     protected DataProviderService baDataService;
     protected BindingIndependentMappingService mappingService;
-    private DataStoreStatsWrapper dataStoreStats;
-    protected DataStore dataStore;
     protected BindingTestContext testContext;
 
     @Before
@@ -42,18 +35,10 @@ public abstract class AbstractDataServiceTest {
 
         baDataService = testContext.getBindingDataBroker();
         biDataService = testContext.getDomDataBroker();
-        dataStore = testContext.getDomDataStore();
         mappingService = testContext.getBindingToDomMappingService();
     }
 
     protected boolean getStartWithSchema() {
         return true;
     }
-
-    @After
-    public void afterTest() {
-
-        testContext.logDataStoreStatistics();
-
-    }
 }
index e6cd1aa1ad638716b474fa9570c7d3ace3d767a1..9ba65339710b50c5e3a1e453fa5b5ff3805484f3 100644 (file)
@@ -10,6 +10,7 @@ package org.opendaylight.controller.sal.binding.test;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertSame;
+import static org.junit.Assert.fail;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 
@@ -154,6 +155,31 @@ public class RuntimeCodeGeneratorTest {
 
         // We should have call to instance 1
         verify(service[1]).simple(instance_1_input[0]);
+
+        /*
+         * Generated RPC service should throw illegalArgumentException
+         * with message if rpc input is null.
+         */
+        try {
+            product.getInvocationProxy().simple(null);
+            fail("Generated RPC router should throw IllegalArgumentException on null input");
+        } catch (IllegalArgumentException e){
+            assertNotNull(e.getMessage());
+        }
+
+
+        /*
+         * Generated RPC service should throw illegalArgumentException
+         * with message if rpc route is null.
+         */
+        try {
+            SimpleInput withoutValue = new SimpleInputImpl(null);
+            product.getInvocationProxy().simple(withoutValue);
+            fail("Generated RPC router should throw IllegalArgumentException on null value for route");
+        } catch (IllegalArgumentException e){
+            assertNotNull(e.getMessage());
+        }
+
     }
 
     private InstanceIdentifier<?>[][] identifiers(final int serviceSize, final int instancesPerService) {
@@ -5,7 +5,7 @@
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
-package org.opendaylight.controller.sal.binding.test.bugfix;
+package org.opendaylight.controller.sal.binding.test.compat;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
@@ -5,7 +5,7 @@
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
-package org.opendaylight.controller.sal.binding.test.bugfix;
+package org.opendaylight.controller.sal.binding.test.compat;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
diff --git a/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/compat/package-info.java b/opendaylight/md-sal/sal-binding-broker/src/test/java/org/opendaylight/controller/sal/binding/test/compat/package-info.java
new file mode 100644 (file)
index 0000000..ec74c3e
--- /dev/null
@@ -0,0 +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
+ */
+/**
+ *
+ * Test suite targeting legacy Data APIs
+ *
+ */
+package org.opendaylight.controller.sal.binding.test.compat;
\ No newline at end of file
index 08c5d061dc832d47cdcffe991cacc2ddb25b6332..c58e258e8b64daa1151a88d1153aac3571d813ea 100644 (file)
@@ -11,10 +11,12 @@ import java.util.concurrent.ExecutorService;
 
 import javassist.ClassPool;
 
+import com.google.common.annotations.Beta;
 import com.google.common.base.Preconditions;
 import com.google.common.util.concurrent.ListeningExecutorService;
 import com.google.common.util.concurrent.MoreExecutors;
 
+@Beta
 public class BindingBrokerTestFactory {
 
     private static final ClassPool CLASS_POOL = ClassPool.getDefault();
index 623b2fdd6365c5f14d3948d2b567ab65c81435cd..f5e902c775a9320857e9665ff79792f71b0a628c 100644 (file)
@@ -9,15 +9,14 @@ package org.opendaylight.controller.sal.binding.test.util;
 
 import static com.google.common.base.Preconditions.checkState;
 
-import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
 import java.util.Set;
 import java.util.concurrent.Future;
 
 import javassist.ClassPool;
 
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 import org.opendaylight.controller.md.sal.binding.impl.ForwardedBackwardsCompatibleDataBroker;
+import org.opendaylight.controller.md.sal.binding.impl.ForwardedBindingDataBroker;
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
 import org.opendaylight.controller.md.sal.dom.broker.impl.DOMDataBrokerImpl;
@@ -39,35 +38,33 @@ import org.opendaylight.controller.sal.core.api.BrokerService;
 import org.opendaylight.controller.sal.core.api.RpcImplementation;
 import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
 import org.opendaylight.controller.sal.core.api.RpcRegistrationListener;
-import org.opendaylight.controller.sal.core.api.data.DataStore;
 import org.opendaylight.controller.sal.core.api.mount.MountProvisionService;
 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
 import org.opendaylight.controller.sal.dom.broker.BrokerImpl;
 import org.opendaylight.controller.sal.dom.broker.MountPointManagerImpl;
-import org.opendaylight.controller.sal.dom.broker.impl.DataStoreStatsWrapper;
-import org.opendaylight.controller.sal.dom.broker.impl.HashMapDataStore;
-import org.opendaylight.controller.sal.dom.broker.impl.SchemaAwareDataStoreAdapter;
 import org.opendaylight.controller.sal.dom.broker.impl.SchemaAwareRpcBroker;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
 import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
+import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
+import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
-import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
-import org.reflections.Reflections;
-import org.reflections.scanners.ResourcesScanner;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Predicate;
+import com.google.common.annotations.Beta;
 import com.google.common.collect.ClassToInstanceMap;
 import com.google.common.collect.ImmutableClassToInstanceMap;
 import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.MutableClassToInstanceMap;
 import com.google.common.util.concurrent.ListeningExecutorService;
 
+@Beta
 public class BindingTestContext implements AutoCloseable {
 
     public static final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier TREE_ROOT = org.opendaylight.yangtools.yang.data.api.InstanceIdentifier
@@ -83,14 +80,9 @@ public class BindingTestContext implements AutoCloseable {
     private BindingIndependentConnector baConnectImpl;
 
     private org.opendaylight.controller.sal.dom.broker.DataBrokerImpl biDataImpl;
+    @SuppressWarnings("deprecation")
     private org.opendaylight.controller.sal.core.api.data.DataProviderService biDataLegacyBroker;
     private BrokerImpl biBrokerImpl;
-    private HashMapDataStore rawDataStore;
-    private SchemaAwareDataStoreAdapter schemaAwareDataStore;
-    private DataStoreStatsWrapper dataStoreStats;
-    private DataStore dataStore;
-
-    private final boolean dataStoreStatisticsEnabled = false;
 
     private final ListeningExecutorService executor;
     private final ClassPool classPool;
@@ -105,12 +97,15 @@ public class BindingTestContext implements AutoCloseable {
 
     private BackwardsCompatibleDataBroker biCompatibleBroker;
 
+    @SuppressWarnings("deprecation")
     private DataProviderService baData;
 
     private DOMDataBroker newDOMDataBroker;
 
     private final MockSchemaService mockSchemaService = new MockSchemaService();
 
+    private DataBroker dataBroker;
+
 
 
     public DOMDataBroker getDomAsyncDataBroker() {
@@ -123,25 +118,6 @@ public class BindingTestContext implements AutoCloseable {
         this.startWithSchema = startWithSchema;
     }
 
-    @Deprecated
-    public void startDomDataStore() {
-        checkState(dataStore == null, "DataStore already started.");
-        checkState(biDataImpl != null, "Dom Data Broker not present");
-        rawDataStore = new HashMapDataStore();
-        schemaAwareDataStore = new SchemaAwareDataStoreAdapter();
-        schemaAwareDataStore.changeDelegate(rawDataStore);
-        if (dataStoreStatisticsEnabled) {
-            dataStoreStats = new DataStoreStatsWrapper(schemaAwareDataStore);
-            dataStore = dataStoreStats;
-        } else {
-            dataStore = schemaAwareDataStore;
-        }
-        mockSchemaService.registerSchemaServiceListener(schemaAwareDataStore);
-        biDataImpl.registerConfigurationReader(TREE_ROOT, dataStore);
-        biDataImpl.registerOperationalReader(TREE_ROOT, dataStore);
-        biDataImpl.registerCommitHandler(TREE_ROOT, dataStore);
-    }
-
     public void startDomDataBroker() {
         checkState(executor != null, "Executor needs to be set");
         biDataImpl = new org.opendaylight.controller.sal.dom.broker.DataBrokerImpl();
@@ -149,6 +125,12 @@ public class BindingTestContext implements AutoCloseable {
         biDataLegacyBroker = biDataImpl;
     }
 
+    public void startNewDataBroker() {
+        checkState(executor != null, "Executor needs to be set");
+        checkState(newDOMDataBroker != null, "DOM Data Broker must be set");
+        dataBroker = new ForwardedBindingDataBroker(newDOMDataBroker, mappingServiceImpl, mockSchemaService);
+    }
+
     public void startNewDomDataBroker() {
         checkState(executor != null, "Executor needs to be set");
         InMemoryDOMDataStore operStore = new InMemoryDOMDataStore("OPER", executor);
@@ -160,11 +142,10 @@ public class BindingTestContext implements AutoCloseable {
 
         newDOMDataBroker = new DOMDataBrokerImpl(newDatastores, executor);
 
-        biCompatibleBroker = new BackwardsCompatibleDataBroker(newDOMDataBroker);
+        biCompatibleBroker = new BackwardsCompatibleDataBroker(newDOMDataBroker,mockSchemaService);
 
         mockSchemaService.registerSchemaServiceListener(configStore);
         mockSchemaService.registerSchemaServiceListener(operStore);
-        mockSchemaService.registerSchemaServiceListener(biCompatibleBroker);
         biDataLegacyBroker = biCompatibleBroker;
     }
 
@@ -203,6 +184,7 @@ public class BindingTestContext implements AutoCloseable {
 
     private ProviderSession createMockContext() {
 
+        @SuppressWarnings("deprecation")
         final ClassToInstanceMap<BrokerService> domBrokerServices = ImmutableClassToInstanceMap
                 .<BrokerService> builder()
                 //
@@ -267,56 +249,24 @@ public class BindingTestContext implements AutoCloseable {
         mockSchemaService.registerSchemaServiceListener(mappingServiceImpl);
     }
 
-    public void updateYangSchema(final String[] files) {
-        mockSchemaService.changeSchema(getContext(files));
+    private void updateYangSchema(final ImmutableSet<YangModuleInfo> moduleInfos) {
+        mockSchemaService.changeSchema(getContext(moduleInfos));
     }
 
-    public static String[] getAllYangFilesOnClasspath() {
-        Predicate<String> predicate = new Predicate<String>() {
-            @Override
-            public boolean apply(final String input) {
-                return input.endsWith(".yang");
-            }
-        };
-        Reflections reflection = new Reflections("META-INF.yang", new ResourcesScanner());
-        Set<String> result = reflection.getResources(predicate);
-        return result.toArray(new String[result.size()]);
-    }
-
-    private static SchemaContext getContext(final String[] yangFiles) {
-        ClassLoader loader = BindingTestContext.class.getClassLoader();
-        List<InputStream> streams = new ArrayList<>();
-        for (String string : yangFiles) {
-            InputStream stream = loader.getResourceAsStream(string);
-            streams.add(stream);
-        }
-        YangParserImpl parser = new YangParserImpl();
-        Set<Module> modules = parser.parseYangModelsFromStreams(streams);
-        return parser.resolveSchemaContext(modules);
-    }
-
-    public void startLegacy() {
-        startBindingDataBroker();
-        startBindingNotificationBroker();
-        startBindingBroker();
-        startDomDataBroker();
-        startDomDataStore();
-        startDomBroker();
-        startDomMountPoint();
-        startBindingToDomMappingService();
-        startForwarding();
-        if (startWithSchema) {
-            loadYangSchemaFromClasspath();
-        }
+    private SchemaContext getContext(final ImmutableSet<YangModuleInfo> moduleInfos) {
+        ModuleInfoBackedContext ctx = ModuleInfoBackedContext.create();
+        ctx.addModuleInfos(moduleInfos);
+        return ctx.tryToCreateSchemaContext().get();
     }
 
     public void start() {
         startNewDomDataBroker();
+
         startDomBroker();
         startDomMountPoint();
         startBindingToDomMappingService();
+        startNewDataBroker();
         startNewBindingDataBroker();
-
         startBindingNotificationBroker();
         startBindingBroker();
 
@@ -338,8 +288,10 @@ public class BindingTestContext implements AutoCloseable {
 
     private void startDomBroker() {
         checkState(executor != null);
-        biBrokerImpl = new BrokerImpl();
-        biBrokerImpl.setRouter(new SchemaAwareRpcBroker("/", mockSchemaService));
+
+        SchemaAwareRpcBroker router = new SchemaAwareRpcBroker("/", mockSchemaService);
+        ClassToInstanceMap<BrokerService> services = MutableClassToInstanceMap.create();
+        biBrokerImpl = new BrokerImpl(router,services);
 
     }
 
@@ -350,44 +302,24 @@ public class BindingTestContext implements AutoCloseable {
     }
 
     public void loadYangSchemaFromClasspath() {
-        String[] files = getAllYangFilesOnClasspath();
-        updateYangSchema(files);
+        ImmutableSet<YangModuleInfo> moduleInfos = BindingReflections.loadModuleInfos();
+        updateYangSchema(moduleInfos);
     }
 
+    @SuppressWarnings("deprecation")
     public DataProviderService getBindingDataBroker() {
         return baData;
     }
 
+    @SuppressWarnings("deprecation")
     public org.opendaylight.controller.sal.core.api.data.DataProviderService getDomDataBroker() {
         return biDataLegacyBroker;
     }
 
-    public DataStore getDomDataStore() {
-        return dataStore;
-    }
-
     public BindingIndependentMappingService getBindingToDomMappingService() {
         return mappingServiceImpl;
     }
 
-    public void logDataStoreStatistics() {
-        if (dataStoreStats == null) {
-            return;
-        }
-
-        LOG.info("BIDataStore Statistics: Configuration Read Count: {} TotalTime: {} ms AverageTime (ns): {} ms",
-                dataStoreStats.getConfigurationReadCount(), dataStoreStats.getConfigurationReadTotalTime(),
-                dataStoreStats.getConfigurationReadAverageTime());
-
-        LOG.info("BIDataStore Statistics: Operational Read Count: {} TotalTime: {} ms AverageTime (ns): {} ms",
-                dataStoreStats.getOperationalReadCount(), dataStoreStats.getOperationalReadTotalTime(),
-                dataStoreStats.getOperationalReadAverageTime());
-
-        LOG.info("BIDataStore Statistics: Request Commit Count: {} TotalTime: {} ms AverageTime (ns): {} ms",
-                dataStoreStats.getRequestCommitCount(), dataStoreStats.getRequestCommitTotalTime(),
-                dataStoreStats.getRequestCommitAverageTime());
-    }
-
     public RpcProviderRegistry getBindingRpcRegistry() {
         return baBrokerImpl.getRoot();
     }
@@ -416,5 +348,9 @@ public class BindingTestContext implements AutoCloseable {
         return biMountImpl;
     }
 
+    public DataBroker getDataBroker() {
+        return dataBroker;
+    }
+
 
 }
index 4a2ec8a06346d8a6a13ce94f26d90c874eb69d71..8636ff613bb2c480e7dd62367ef2174a73ceed73 100644 (file)
@@ -25,7 +25,7 @@ module opendaylight-md-sal-binding {
     
     identity binding-async-data-broker {
         base "config:service-type";
-        config:java-class "org.opendaylight.controller.md.sal.binding.api.BindingDataBroker";
+        config:java-class "org.opendaylight.controller.md.sal.binding.api.DataBroker";
     }
 
     identity binding-data-consumer-broker {
index fd5c5be18dc787c2bc6ae2237df3ce848b930ee7..42d5cfff65e755e29ef2f9198fb6478eabf783d6 100644 (file)
       <artifactId>pax-exam-container-native</artifactId>
       <scope>test</scope>
     </dependency>
-
     <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-simple</artifactId>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>org.opendaylight.yangtools</groupId>
+      <artifactId>yang-parser-impl</artifactId>
+      <scope>test</scope>
+    </dependency>
+      <dependency>
+          <groupId>org.opendaylight.controller</groupId>
+          <artifactId>sal-test-model</artifactId>
+          <version>1.1-SNAPSHOT</version>
+      </dependency>
   </dependencies>
   <build>
     <plugins>
           </execution>
         </executions>
       </plugin>
-      <plugin>
-        <groupId>org.opendaylight.yangtools</groupId>
-        <artifactId>yang-maven-plugin</artifactId>
-        <executions>
-          <execution>
-            <goals>
-              <goal>generate-sources</goal>
-            </goals>
-            <configuration>
-              <codeGenerators>
-                <generator>
-                  <codeGeneratorClass>org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl</codeGeneratorClass>
-                  <outputBaseDir>${salGeneratorPath}</outputBaseDir>
-                </generator>
-              </codeGenerators>
-              <inspectDependencies>true</inspectDependencies>
-            </configuration>
-          </execution>
-        </executions>
-      </plugin>
     </plugins>
   </build>
   <scm>
index c5dbdcecae747b7f4930b0f0f1119ec753f941e3..aefc53b124335b5801910faaed56adca6be32d46 100644 (file)
@@ -25,6 +25,11 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.N
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 
+/*
+ * FIXME: THis test should be moved to sal-binding-broker and rewriten
+ * to use new DataBroker API
+ */
+@SuppressWarnings("deprecation")
 public class ConcurrentImplicitCreateTest extends AbstractDataServiceTest {
 
     private static final NodeKey NODE_FOO_KEY = new NodeKey(new NodeId("foo"));
index 800c1b4cc426e1ef09c04983f594ecb059d036d1..cd68559ae5304eb721771981069c312333b33868 100644 (file)
@@ -20,7 +20,7 @@ import java.util.concurrent.ExecutionException;
 import org.junit.Test;
 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.dom.api.DOMDataReadTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
 import org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction;
 import org.opendaylight.controller.sal.binding.test.AbstractDataServiceTest;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.store.rev140422.Lists;
@@ -50,12 +50,10 @@ import com.google.common.collect.ImmutableList;
 import com.google.common.util.concurrent.ListenableFuture;
 
 /*
- * 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
+ * FIXME: THis test should be moved to sal-binding-broker and rewriten
+ * to use new DataBroker API
  */
+@SuppressWarnings("deprecation")
 public class ListProcessingAndOrderingTest extends AbstractDataServiceTest {
 
     private static final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier DOM_UNORDERED_LIST_PATH = org.opendaylight.yangtools.yang.data.api.InstanceIdentifier
@@ -139,7 +137,7 @@ public class ListProcessingAndOrderingTest extends AbstractDataServiceTest {
     private NormalizedNode<?, ?> resolveDataAsserted(
             final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier domPath) {
 
-        try (DOMDataReadTransaction readTx = testContext.getDomAsyncDataBroker().newReadOnlyTransaction()){
+        try (DOMDataReadOnlyTransaction readTx = testContext.getDomAsyncDataBroker().newReadOnlyTransaction()){
             ListenableFuture<Optional<NormalizedNode<?, ?>>> data = readTx.read(LogicalDatastoreType.OPERATIONAL, domPath);
             Optional<NormalizedNode<?, ?>> potential = data.get();
             assertTrue(potential.isPresent());
@@ -171,7 +169,6 @@ public class ListProcessingAndOrderingTest extends AbstractDataServiceTest {
         assertEquals(TransactionStatus.COMMITED,result.getResult());
     }
 
-    @SuppressWarnings("deprecation")
     private void assertXmlRepresentation(final InstanceIdentifier<?> containerPath, final String... childNameValues) {
 
         org.opendaylight.yangtools.yang.data.api.InstanceIdentifier domPath = testContext.getBindingToDomMappingService().toDataDom(containerPath);
index 6b4cc5779806288d4f0cf26116d2ef3f7ca10ba1..2b5171369bb31a7195b029c1377201c76ba24849 100644 (file)
@@ -43,12 +43,10 @@ import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import com.google.common.util.concurrent.SettableFuture;
 
 /*
- * 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
+ * FIXME: THis test should be moved to compat test-suite and rewriten
+ * to use sal-test-model
  */
+@SuppressWarnings("deprecation")
 public class WildcardedDataChangeListenerTest extends AbstractDataServiceTest {
 
     private static final NodeKey NODE_0_KEY = new NodeKey(new NodeId("test:0"));
index 471935248506b9cf4c3cdf53d37e8ad43568b33b..0c767f61850e0102a6f8534d753b542064edfaaa 100644 (file)
@@ -14,7 +14,6 @@ import static org.junit.Assert.assertNull;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
-import java.util.Map;
 import java.util.concurrent.Callable;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
@@ -49,49 +48,29 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026
 import org.opendaylight.yang.gen.v1.urn.opendaylight.model.match.types.rev131026.vlan.match.fields.VlanIdBuilder;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 
-import com.google.common.collect.ImmutableMap;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
 import com.google.common.util.concurrent.ListeningExecutorService;
 import com.google.common.util.concurrent.MoreExecutors;
 
+@SuppressWarnings("deprecation")
 public class DOMCodecBug01Test extends AbstractDataServiceTest {
 
-    private static final QName NODE_ID_QNAME = QName.create(Node.QNAME, "id");
-    private static final QName FLOW_ID_QNAME = QName.create(Flow.QNAME, "id");
-    private static final QName FLOW_NODE_QNAME = QName.create(Flow.QNAME, "node");
     private static final long FLOW_ID = 1234;
     private static final String NODE_ID = "node:1";
 
     private static final NodeKey NODE_KEY = new NodeKey(new NodeId(NODE_ID));
 
-    private static final Map<QName, Object> NODE_KEY_BI = Collections.<QName, Object> singletonMap(NODE_ID_QNAME,
-            NODE_ID);
-
     private static final InstanceIdentifier<Node> NODE_INSTANCE_ID_BA = InstanceIdentifier.builder(Nodes.class) //
             .child(Node.class, NODE_KEY).toInstance();
 
-    private static final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier NODE_INSTANCE_ID_BI = //
-    org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.builder() //
-            .node(Nodes.QNAME) //
-            .nodeWithKey(Node.QNAME, NODE_KEY_BI) //
-            .toInstance();
     private static final NodeRef NODE_REF = new NodeRef(NODE_INSTANCE_ID_BA);
 
     private static final FlowKey FLOW_KEY = new FlowKey(FLOW_ID, NODE_REF);
 
-    private static final Map<QName, Object> FLOW_KEY_BI = //
-    ImmutableMap.<QName, Object> of(FLOW_ID_QNAME, FLOW_ID, FLOW_NODE_QNAME, NODE_INSTANCE_ID_BI);
-
-    private static final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier FLOW_INSTANCE_ID_BI = //
-    org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.builder() //
-            .node(Flows.QNAME) //
-            .nodeWithKey(Flow.QNAME, FLOW_KEY_BI) //
-            .toInstance();
     private static final InstanceIdentifier<? extends DataObject> FLOW_INSTANCE_ID_BA = //
     InstanceIdentifier.builder(Flows.class) //
             .child(Flow.class, FLOW_KEY) //
index bc6f567c2bd01fd3346cc0c8d9769fd20f9cfdc8..bddbc4e95400965da7533b3d66dfee72fa6c3710 100644 (file)
@@ -11,7 +11,6 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 
 import java.util.Collections;
-import java.util.Map;
 import java.util.concurrent.Callable;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
@@ -22,47 +21,21 @@ import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
 import org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction;
 import org.opendaylight.controller.sal.binding.test.AbstractDataServiceTest;
 import org.opendaylight.controller.sal.binding.test.util.BindingBrokerTestFactory;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodesBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 
 import com.google.common.util.concurrent.ListeningExecutorService;
 import com.google.common.util.concurrent.MoreExecutors;
 
+@SuppressWarnings("deprecation")
 public class DOMCodecBug02Test extends AbstractDataServiceTest {
 
-    private static final QName NODE_ID_QNAME = QName.create(Node.QNAME, "id");
-    private static final String NODE_ID = "node:1";
-
-    private static final NodeKey NODE_KEY = new NodeKey(new NodeId(NODE_ID));
-
-    private static final Map<QName, Object> NODE_KEY_BI = Collections.<QName, Object> singletonMap(NODE_ID_QNAME,
-            NODE_ID);
-
     private static final InstanceIdentifier<Nodes> NODES_INSTANCE_ID_BA = InstanceIdentifier.builder(Nodes.class) //
             .toInstance();
 
-    private static final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier NODES_INSTANCE_ID_BI = //
-    org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.builder() //
-            .node(Nodes.QNAME) //
-            .toInstance();
-
-    private static final InstanceIdentifier<Node> NODE_INSTANCE_ID_BA = InstanceIdentifier.builder(Nodes.class) //
-            .child(Node.class, NODE_KEY).toInstance();
-
-    private static final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier NODE_INSTANCE_ID_BI = //
-    org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.builder() //
-            .node(Nodes.QNAME) //
-            .nodeWithKey(Node.QNAME, NODE_KEY_BI) //
-            .toInstance();
-    private static final NodeRef NODE_REF = new NodeRef(NODE_INSTANCE_ID_BA);
-
     /**
      * This test is ignored, till found out better way to test generation of
      * classes without leaking of instances from previous run
@@ -81,7 +54,6 @@ public class DOMCodecBug02Test extends AbstractDataServiceTest {
 
         baDataService = testContext.getBindingDataBroker();
         biDataService = testContext.getDomDataBroker();
-        dataStore = testContext.getDomDataStore();
         mappingService = testContext.getBindingToDomMappingService();
     };
 
index ccbd52fc77ea27711c19c934fb2109a3991343d6..dd8eaa7d5f6f821a54c9694c7469e0b96e0d9d49 100644 (file)
@@ -46,6 +46,7 @@ import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 
 import com.google.common.util.concurrent.SettableFuture;
 
+@SuppressWarnings("deprecation")
 public class DOMCodecBug03Test extends AbstractDataServiceTest implements DataChangeListener {
 
     private static final QName NODE_ID_QNAME = QName.create(Node.QNAME, "id");
index c1eba3ee257abeb7bb864a810e8bad3b676ad529..fb5fd1fa6c8f438b120078d1d995ca839dc6b5a7 100644 (file)
@@ -24,12 +24,12 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 
 import com.google.common.util.concurrent.SettableFuture;
 
+@SuppressWarnings("deprecation")
 public class DeleteNestedAugmentationListenParentTest extends AbstractDataServiceTest {
 
     private static final NodeKey NODE_KEY = new NodeKey(new NodeId("foo"));
@@ -38,11 +38,6 @@ public class DeleteNestedAugmentationListenParentTest extends AbstractDataServic
 
     private static final FlowKey FLOW_KEY = new FlowKey(new FlowId("100"));
 
-    private static final InstanceIdentifier<FlowCapableNode> LISTENER_PATH = InstanceIdentifier.builder(Nodes.class) //
-            .child(Node.class)
-            .augmentation(FlowCapableNode.class).build();
-
-
     private static final InstanceIdentifier<FlowCapableNode> NODE_AUGMENT_PATH = InstanceIdentifier.builder(Nodes.class)
             .child(Node.class,NODE_KEY)
             .augmentation(FlowCapableNode.class)
@@ -63,7 +58,7 @@ public class DeleteNestedAugmentationListenParentTest extends AbstractDataServic
 
         final SettableFuture<DataChangeEvent<InstanceIdentifier<?>, DataObject>> event = SettableFuture.create();
 
-        ListenerRegistration<DataChangeListener> listenerReg = baDataService.registerDataChangeListener(FLOW_PATH, new DataChangeListener() {
+        baDataService.registerDataChangeListener(FLOW_PATH, new DataChangeListener() {
 
             @Override
             public void onDataChanged(final DataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
index 30c7af705f2ccba4a25e3b1d19f8261e3439386a..7143352c1f9c8ec625b4f29e93912d30db815414 100644 (file)
@@ -14,7 +14,6 @@ import static org.junit.Assert.assertNull;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
-import java.util.Map;
 
 import org.junit.Test;
 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
@@ -39,7 +38,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instru
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
@@ -54,11 +52,9 @@ import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 
 import com.google.common.collect.ImmutableSet;
 
+@SuppressWarnings("deprecation")
 public class FlagsSerializationTest extends AbstractDataServiceTest {
 
-    private static final QName NODE_ID_QNAME = QName.create(Node.QNAME, "id");
-    private static final QName FLOW_ID_QNAME = QName.create(Flow.QNAME, "id");
-    private static final QName FLOW_NODE_QNAME = QName.create(Flow.QNAME, "node");
     private static final String FLOW_ID = "1234";
     private static final short TABLE_ID = (short)0;
     private static final String NODE_ID = "node:1";
@@ -67,27 +63,9 @@ public class FlagsSerializationTest extends AbstractDataServiceTest {
     private static final FlowKey FLOW_KEY = new FlowKey(new FlowId(FLOW_ID));
     private static final TableKey TABLE_KEY = new TableKey(TABLE_ID);
 
-    private static final Map<QName, Object> NODE_KEY_BI = Collections.<QName, Object> singletonMap(NODE_ID_QNAME,
-            NODE_ID);
-
     private static final InstanceIdentifier<Node> NODE_INSTANCE_ID_BA = InstanceIdentifier.builder(Nodes.class) //
             .child(Node.class, NODE_KEY).toInstance();
 
-    private static final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier NODE_INSTANCE_ID_BI = //
-    org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.builder() //
-            .node(Nodes.QNAME) //
-            .nodeWithKey(Node.QNAME, NODE_KEY_BI) //
-            .toInstance();
-    private static final NodeRef NODE_REF = new NodeRef(NODE_INSTANCE_ID_BA);
-
-
-
-//    private static final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier FLOW_INSTANCE_ID_BI = //
-//    org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.builder() //
-//
-//            .node(Flows.QNAME) //
-//            .nodeWithKey(Flow.QNAME, FLOW_KEY_BI) //
-//            .toInstance();
     private static final InstanceIdentifier<? extends DataObject> FLOW_INSTANCE_ID_BA = //
             NODE_INSTANCE_ID_BA.builder() //
             .augmentation(FlowCapableNode.class)
@@ -113,15 +91,13 @@ public class FlagsSerializationTest extends AbstractDataServiceTest {
         ImmutableSet<String> domAllTrueFlags = ImmutableSet.<String>of("CHECK_OVERLAP","NO_BYT_COUNTS", "NO_PKT_COUNTS", "RESET_COUNTS", "SEND_FLOW_REM");
         testFlags(allTrueFlags,domAllTrueFlags);
 
-        FlowModFlags nullFlags = null;
-        ImmutableSet<String> domNullFlags = null;
         testFlags(null,null);
 
 
 
     }
 
-    private void testFlags(FlowModFlags flagsToTest, ImmutableSet<String> domFlags) throws Exception {
+    private void testFlags(final FlowModFlags flagsToTest, final ImmutableSet<String> domFlags) throws Exception {
         Flow flow = createFlow(flagsToTest);
         assertNotNull(flow);
 
@@ -145,7 +121,7 @@ public class FlagsSerializationTest extends AbstractDataServiceTest {
 
     }
 
-    private Flow createFlow(FlowModFlags flagsToTest) throws Exception {
+    private Flow createFlow(final FlowModFlags flagsToTest) throws Exception {
 
         DataModificationTransaction modification = baDataService.beginTransaction();
 
index 7f1632081490003aa8921b14a8c37c6941df4c29..33a4399cb513519ead16e0c16b9e81d57f13e0a7 100644 (file)
@@ -27,7 +27,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.Fl
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnectorBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.flow.node.SupportedActions;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
@@ -45,6 +44,7 @@ import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 
 import com.google.common.util.concurrent.SettableFuture;
 
+@SuppressWarnings("deprecation")
 public class PutAugmentationTest extends AbstractDataServiceTest implements DataChangeListener {
 
     private static final QName NODE_ID_QNAME = QName.create(Node.QNAME, "id");
@@ -62,12 +62,6 @@ public class PutAugmentationTest extends AbstractDataServiceTest implements Data
             NODES_INSTANCE_ID_BA.builder() //
             .child(Node.class, NODE_KEY).toInstance();
 
-    private static final InstanceIdentifier<SupportedActions> SUPPORTED_ACTIONS_INSTANCE_ID_BA = //
-            NODES_INSTANCE_ID_BA.builder() //
-            .child(Node.class, NODE_KEY) //
-            .augmentation(FlowCapableNode.class) //
-            .child(SupportedActions.class).toInstance();
-
     private static final InstanceIdentifier<FlowCapableNode> ALL_FLOW_CAPABLE_NODES = //
             NODES_INSTANCE_ID_BA.builder() //
             .child(Node.class) //
@@ -79,15 +73,6 @@ public class PutAugmentationTest extends AbstractDataServiceTest implements Data
             .node(Nodes.QNAME) //
             .nodeWithKey(Node.QNAME, NODE_KEY_BI) //
             .toInstance();
-    private static final QName SUPPORTED_ACTIONS_QNAME = QName.create(FlowCapableNode.QNAME,
-            SupportedActions.QNAME.getLocalName());
-
-    private static final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier SUPPORTED_ACTIONS_INSTANCE_ID_BI = //
-    org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.builder() //
-            .node(Nodes.QNAME) //
-            .nodeWithKey(Node.QNAME, NODE_KEY_BI) //
-            .node(SUPPORTED_ACTIONS_QNAME) //
-            .toInstance();
     private static final InstanceIdentifier<FlowCapableNode> FLOW_AUGMENTATION_PATH =
             NODE_INSTANCE_ID_BA.builder() //
             .augmentation(FlowCapableNode.class) //
@@ -231,31 +216,11 @@ public class PutAugmentationTest extends AbstractDataServiceTest implements Data
         assertNull(node);
     }
 
-    private void verifyNodes(final Nodes nodes, final Node original) {
-        assertNotNull(nodes);
-        assertNotNull(nodes.getNode());
-        assertEquals(1, nodes.getNode().size());
-        Node readedNode = nodes.getNode().get(0);
-        assertEquals(original.getId(), readedNode.getId());
-        assertEquals(original.getKey(), readedNode.getKey());
-
-        FlowCapableNode fnu = original.getAugmentation(FlowCapableNode.class);
-        FlowCapableNode readedAugment = readedNode.getAugmentation(FlowCapableNode.class);
-        assertNotNull(fnu);
-        assertEquals(fnu.getDescription(), readedAugment.getDescription());
-        assertEquals(fnu.getSerialNumber(), readedAugment.getSerialNumber());
-
-    }
-
     private void assertBindingIndependentVersion(final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier nodeId) {
         CompositeNode node = biDataService.readOperationalData(nodeId);
         assertNotNull(node);
     }
 
-    private Nodes checkForNodes() {
-        return (Nodes) baDataService.readOperationalData(NODES_INSTANCE_ID_BA);
-    }
-
     @Override
     public void onDataChanged(final DataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
         lastReceivedChangeEvent.set(change);
index cb31885f02673685342d35796d81e7bb3c38fa71..b09ba39a65e120f20c51801f2a699552f91132eb 100644 (file)
@@ -31,6 +31,7 @@ import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 
 import com.google.common.util.concurrent.SettableFuture;
 
+@SuppressWarnings("deprecation")
 public class WriteParentListenAugmentTest extends AbstractDataServiceTest {
 
     private static final String NODE_ID = "node:1";
index f7b81a44e9e2b685860b7269425c2630911b817b..ad02d9a6f6df31239c108352294a595452d43f7e 100644 (file)
@@ -40,6 +40,7 @@ import org.opendaylight.yangtools.yang.common.RpcResult;
 
 import com.google.common.collect.ImmutableList;
 
+@SuppressWarnings("deprecation")
 public class WriteParentReadChildTest extends AbstractDataServiceTest {
 
     private static final String FLOW_ID = "1234";
diff --git a/opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/bugfix/package-info.java b/opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/bugfix/package-info.java
new file mode 100644 (file)
index 0000000..84559d5
--- /dev/null
@@ -0,0 +1,15 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+/**
+ * This testsuite test Hydrogen-level API and regression for most of it,
+ *
+ * FIXME: this testsuite needs to be refactored to use new DataBroker API,
+ * moved to sal-binding-broker-impl and uses models only from sal-test-model.
+ *
+ */
+package org.opendaylight.controller.sal.binding.test.bugfix;
\ No newline at end of file
index 6d0226849f3a81a02b143046ea8d092cfd755b5b..481a7ddfa2c42863b3cb17b17826d0a5748fa778 100644 (file)
@@ -11,16 +11,12 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 
-
 import java.util.concurrent.Future;
 
-
 import org.junit.Test;
 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
 import org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction;
-
 import org.opendaylight.controller.sal.binding.test.AbstractDataServiceTest;
-
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
@@ -31,6 +27,8 @@ import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 
+// FIXME: Migrate to use new Data Broker APIs
+@SuppressWarnings("deprecation")
 public class BrokerIntegrationTest extends AbstractDataServiceTest {
 
     @Test
@@ -105,14 +103,14 @@ public class BrokerIntegrationTest extends AbstractDataServiceTest {
         assertNull(readedData2);
     }
 
-    private static NodeRef createNodeRef(String string) {
+    private static NodeRef createNodeRef(final String string) {
         NodeKey key = new NodeKey(new NodeId(string));
         InstanceIdentifier<Node> path = InstanceIdentifier.builder(Nodes.class).child(Node.class, key)
                 .toInstance();
         return new NodeRef(path);
     }
 
-    private static Node createNode(String string) {
+    private static Node createNode(final String string) {
         NodeBuilder ret = new NodeBuilder();
         ret.setId(new NodeId(string));
         ret.setKey(new NodeKey(ret.getId()));
index 422b9ccee5c4cc9e1048d2812fe784d7a9a08075..ae54896c6d0faa75b40d105319e4c7b3c8b3dc1c 100644 (file)
@@ -45,7 +45,6 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instru
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.Instruction;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.instruction.list.InstructionBuilder;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
@@ -63,13 +62,14 @@ import org.slf4j.LoggerFactory;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.util.concurrent.SettableFuture;
 
+// FIXME: Migrate to use new Data Broker APIs
+@SuppressWarnings("deprecation")
 public class ChangeOriginatedInDomBrokerTest extends AbstractDataServiceTest {
 
     private static final Logger LOG = LoggerFactory.getLogger(ChangeOriginatedInDomBrokerTest.class);
 
     private static final QName NODE_ID_QNAME = QName.create(Node.QNAME, "id");
     private static final QName FLOW_ID_QNAME = QName.create(Flow.QNAME, "id");
-    private static final QName FLOW_NODE_QNAME = QName.create(Flow.QNAME, "node");
     private static final QName TABLE_ID_QNAME = QName.create(Table.QNAME, "id");
 
     private static final String NODE_ID = "node:1";
@@ -87,13 +87,6 @@ public class ChangeOriginatedInDomBrokerTest extends AbstractDataServiceTest {
     private static final InstanceIdentifier<Node> NODE_INSTANCE_ID_BA = InstanceIdentifier.builder(Nodes.class) //
             .child(Node.class, NODE_KEY).toInstance();
 
-    private static final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier NODE_INSTANCE_ID_BI = //
-    org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.builder() //
-            .node(Nodes.QNAME) //
-            .nodeWithKey(Node.QNAME, NODE_KEY_BI) //
-            .toInstance();
-    private static final NodeRef NODE_REF = new NodeRef(NODE_INSTANCE_ID_BA);
-
     private static final Map<QName, Object> FLOW_KEY_BI = //
     ImmutableMap.<QName, Object> of(FLOW_ID_QNAME, FLOW_ID.getValue());
 
index 94570510ab0cd4d3c0fefe41ccd61e5670bf56d9..804fcc9fbe8bb4983b10e1120467e4ae03f50bf5 100644 (file)
@@ -24,15 +24,12 @@ import org.opendaylight.controller.sal.binding.test.util.BindingTestContext;
 import org.opendaylight.controller.sal.core.api.mount.MountProvisionInstance;
 import org.opendaylight.controller.sal.core.api.mount.MountProvisionService;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.NodeGroupStatistics;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.group.statistics.GroupStatistics;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.GroupId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeRef;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
@@ -43,13 +40,10 @@ import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
 
 import com.google.common.util.concurrent.MoreExecutors;
 
+@SuppressWarnings("deprecation")
 public class CrossBrokerMountPointTest {
 
     private static final QName NODE_ID_QNAME = QName.create(Node.QNAME, "id");
-    private static final QName FLOW_ID_QNAME = QName.create(Flow.QNAME, "id");
-    private static final QName FLOW_NODE_QNAME = QName.create(Flow.QNAME, "node");
-    private static final QName TABLE_ID_QNAME = QName.create(Table.QNAME, "id");
-
     private static final String NODE_ID = "node:1";
 
     private static final NodeKey NODE_KEY = new NodeKey(new NodeId(NODE_ID));
@@ -83,8 +77,6 @@ public class CrossBrokerMountPointTest {
             .nodeWithKey(QName.create(FlowCapableNode.QNAME, "group"), QName.create(FlowCapableNode.QNAME, "group-id"),
                     0L).node(AUGMENTED_GROUP_STATISTICS).toInstance();
 
-    private static final NodeRef NODE_REF = new NodeRef(NODE_INSTANCE_ID_BA);
-
     private BindingTestContext testContext;
     private MountProviderService bindingMountPointService;
     private MountProvisionService domMountPointService;
@@ -123,13 +115,13 @@ public class CrossBrokerMountPointTest {
         DataReader<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> simpleReader = new DataReader<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode>() {
 
             @Override
-            public CompositeNode readConfigurationData(org.opendaylight.yangtools.yang.data.api.InstanceIdentifier arg0) {
+            public CompositeNode readConfigurationData(final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier arg0) {
                 return null;
             }
 
 
             @Override
-            public CompositeNode readOperationalData(org.opendaylight.yangtools.yang.data.api.InstanceIdentifier arg0) {
+            public CompositeNode readOperationalData(final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier arg0) {
                 if (arg0.equals(GROUP_STATISTICS_ID_BI)) {
                     ImmutableCompositeNode data = ImmutableCompositeNode
                             .builder()
index ca38ed0797e1f1d0433a2281a2763672d1d19300..48e1db0e631c3c02505913c02192866d35756ae7 100644 (file)
@@ -23,7 +23,6 @@ import org.junit.Test;
 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
 import org.opendaylight.controller.sal.binding.test.util.BindingBrokerTestFactory;
 import org.opendaylight.controller.sal.binding.test.util.BindingTestContext;
-import org.opendaylight.controller.sal.common.util.Rpcs;
 import org.opendaylight.controller.sal.core.api.RpcImplementation;
 import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.AddFlowInput;
@@ -42,12 +41,11 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.N
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.RpcError;
 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.impl.CompositeNodeTOImpl;
 
-import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
@@ -136,7 +134,7 @@ public class CrossBrokerRpcTest {
             @Override
             public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(QName rpc, CompositeNode input) {
                 CompositeNode result = testContext.getBindingToDomMappingService().toDataDom(output);
-                return Futures.immediateFuture(Rpcs.getRpcResult(true, result, ImmutableList.<RpcError>of()));
+                return Futures.immediateFuture(RpcResultBuilder.<CompositeNode>success(result).build());
             }
         });
         registration.registerPath(NodeContext.QNAME, BI_NODE_C_ID);
@@ -168,7 +166,7 @@ public class CrossBrokerRpcTest {
     private Future<RpcResult<AddFlowOutput>> addFlowResult(boolean success, long xid) {
         AddFlowOutput output = new AddFlowOutputBuilder() //
                 .setTransactionId(new TransactionId(BigInteger.valueOf(xid))).build();
-        RpcResult<AddFlowOutput> result = Rpcs.getRpcResult(success, output, ImmutableList.<RpcError> of());
+        RpcResult<AddFlowOutput> result = RpcResultBuilder.<AddFlowOutput>status(success).withResult(output).build();
         return Futures.immediateFuture(result);
     }
 
diff --git a/opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/connect/dom/DOMRpcServiceTestBugfix560.java b/opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/connect/dom/DOMRpcServiceTestBugfix560.java
new file mode 100644 (file)
index 0000000..0c123eb
--- /dev/null
@@ -0,0 +1,175 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.sal.binding.test.connect.dom;
+
+import static junit.framework.Assert.assertNotNull;
+import static junit.framework.Assert.assertTrue;
+import static junit.framework.Assert.fail;
+
+import java.io.InputStream;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.controller.sal.binding.api.mount.MountProviderInstance;
+import org.opendaylight.controller.sal.binding.api.mount.MountProviderService;
+import org.opendaylight.controller.sal.binding.test.util.BindingBrokerTestFactory;
+import org.opendaylight.controller.sal.binding.test.util.BindingTestContext;
+import org.opendaylight.controller.sal.core.api.RpcImplementation;
+import org.opendaylight.controller.sal.core.api.mount.MountProvisionInstance;
+import org.opendaylight.controller.sal.core.api.mount.MountProvisionService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.bi.ba.rpcservice.rev140701.OpendaylightTestRpcServiceService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.bi.ba.rpcservice.rev140701.RockTheHouseInputBuilder;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
+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.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser;
+import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.MoreExecutors;
+
+/**
+ * Test case for reported bug 560
+ *
+ * @author Lukas Sedlak
+ * @see <a
+ *      href="https://bugs.opendaylight.org/show_bug.cgi?id=560">https://bugs.opendaylight.org/show_bug.cgi?id=560</a>
+ */
+public class DOMRpcServiceTestBugfix560 {
+
+    private final static String RPC_SERVICE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:bi:ba:rpcservice";
+    private final static String REVISION_DATE = "2014-07-01";
+    private final static QName RPC_NAME = QName.create(RPC_SERVICE_NAMESPACE,
+            REVISION_DATE, "rock-the-house");
+
+    private static final NodeId MOUNT_NODE = new NodeId("id");
+    private static final QName NODE_ID_QNAME = QName.create(Node.QNAME, "id");
+
+    private static final InstanceIdentifier<Node> BA_MOUNT_ID = createBANodeIdentifier(MOUNT_NODE);
+    private static final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier BI_MOUNT_ID = createBINodeIdentifier(MOUNT_NODE);
+
+    private BindingTestContext testContext;
+    private MountProvisionService domMountPointService;
+    private MountProviderService bindingMountPointService;
+    private SchemaContext schemaContext;
+
+    /**
+     * @throws java.lang.Exception
+     */
+    @Before
+    public void setUp() throws Exception {
+        BindingBrokerTestFactory testFactory = new BindingBrokerTestFactory();
+        testFactory.setExecutor(MoreExecutors.sameThreadExecutor());
+        testFactory.setStartWithParsedSchema(true);
+        testContext = testFactory.getTestContext();
+
+        testContext.start();
+        domMountPointService = testContext.getDomMountProviderService();
+        bindingMountPointService = testContext.getBindingMountProviderService();
+        assertNotNull(domMountPointService);
+
+        final YangContextParser parser = new YangParserImpl();
+        final InputStream moduleStream = BindingReflections.getModuleInfo(
+                OpendaylightTestRpcServiceService.class)
+                .getModuleSourceStream();
+
+        assertNotNull(moduleStream);
+        List<InputStream> rpcModels = Collections.singletonList(moduleStream);
+        @SuppressWarnings("deprecation")
+        Set<Module> modules = parser.parseYangModelsFromStreams(rpcModels);
+        @SuppressWarnings("deprecation")
+        SchemaContext mountSchemaContext = parser.resolveSchemaContext(modules);
+        schemaContext = mountSchemaContext;
+    }
+
+    private static org.opendaylight.yangtools.yang.data.api.InstanceIdentifier createBINodeIdentifier(
+            final NodeId mountNode) {
+        return org.opendaylight.yangtools.yang.data.api.InstanceIdentifier
+                .builder().node(Nodes.QNAME)
+                .nodeWithKey(Node.QNAME, NODE_ID_QNAME, mountNode.getValue())
+                .toInstance();
+    }
+
+    private static InstanceIdentifier<Node> createBANodeIdentifier(
+            final NodeId mountNode) {
+        return InstanceIdentifier.builder(Nodes.class)
+                .child(Node.class, new NodeKey(mountNode)).toInstance();
+    }
+
+    @SuppressWarnings("deprecation")
+    @Test
+    public void test() throws ExecutionException, InterruptedException {
+        // FIXME: This is made to only make sure instance identifier codec
+        // for path is instantiated.
+        testContext.getBindingDataBroker().readOperationalData(BA_MOUNT_ID);
+        final MountProvisionInstance mountPoint = domMountPointService
+                .createMountPoint(BI_MOUNT_ID);
+        mountPoint.setSchemaContext(schemaContext);
+        assertNotNull(mountPoint);
+
+        mountPoint.addRpcImplementation(RPC_NAME, new RpcImplementation() {
+
+            @Override
+            public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(
+                    final QName rpc, final CompositeNode input) {
+
+                return Futures.immediateFuture(RpcResultBuilder
+                        .<CompositeNode> success().build());
+            }
+
+            @Override
+            public Set<QName> getSupportedRpcs() {
+                return ImmutableSet.of(RPC_NAME);
+            }
+        });
+
+        final Set<QName> biSupportedRpcs = mountPoint.getSupportedRpcs();
+        assertNotNull(biSupportedRpcs);
+        assertTrue(!biSupportedRpcs.isEmpty());
+
+        MountProviderInstance mountInstance = bindingMountPointService
+                .getMountPoint(BA_MOUNT_ID);
+        assertNotNull(mountInstance);
+        final OpendaylightTestRpcServiceService rpcService = mountInstance
+                .getRpcService(OpendaylightTestRpcServiceService.class);
+        assertNotNull(rpcService);
+
+        try {
+            Future<RpcResult<Void>> result = rpcService
+                    .rockTheHouse(new RockTheHouseInputBuilder().build());
+            assertTrue(result.get().isSuccessful());
+        } catch (IllegalStateException ex) {
+            fail("OpendaylightTestRpcServiceService class doesn't contain rockTheHouse method!");
+        }
+    }
+
+    /**
+     * @throws java.lang.Exception
+     */
+    @After
+    public void teardown() throws Exception {
+        testContext.close();
+    }
+}
index 5ede600d9777917a0df963c01b5a08128057f722..c389618f2eb829f2dedb12ec58b0b365f7654ff0 100644 (file)
@@ -54,6 +54,7 @@ public class TestHelper {
                 mavenBundle("io.netty", "netty-transport").versionAsInProject(), //
 
                 mavenBundle(CONTROLLER, "config-manager").versionAsInProject(), // //
+                mavenBundle(CONTROLLER, "config-util").versionAsInProject(), // //
                 mavenBundle("commons-io", "commons-io").versionAsInProject(), //
                 mavenBundle(CONTROLLER, "config-manager").versionAsInProject(), //
                 mavenBundle(CONTROLLER, "yang-jmx-generator").versionAsInProject(), //
index 37ef257224d30ad749a6030557fab85f7fb734c6..63a921d6f309db37a0a438bbadbafdaadb528485 100644 (file)
@@ -20,7 +20,6 @@
                 </capability>
                 <capability>urn:ietf:params:xml:ns:yang:ietf-inet-types?module=ietf-inet-types&amp;revision=2010-09-24
                 </capability>
-                <capability>urn:ietf:params:netconf:capability:rollback-on-error:1.0</capability>
                 <capability>urn:ietf:params:xml:ns:yang:ietf-yang-types?module=ietf-yang-types&amp;revision=2010-09-24
                 </capability>
                 <capability>
index 3df33ba377376182e3485f6506af70d4a5e932aa..49ac59fe95da5071aa7f9b59332ae2aef0b97113 100644 (file)
@@ -11,6 +11,14 @@ import org.opendaylight.controller.md.sal.common.api.data.DataReader;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 
+/**
+ *
+ *
+ * @deprecated Use
+ *             {@link org.opendaylight.controller.md.sal.binding.api.ReadTransaction#read(org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType, InstanceIdentifier)}
+ *             instead.
+ */
+@Deprecated
 public final class TypeSafeDataReader {
 
     private final DataReader<InstanceIdentifier<? extends DataObject>, DataObject> delegate;
@@ -19,21 +27,25 @@ public final class TypeSafeDataReader {
         return delegate;
     }
 
-    public TypeSafeDataReader(DataReader<InstanceIdentifier<? extends DataObject>, DataObject> delegate) {
+    public TypeSafeDataReader(
+            final DataReader<InstanceIdentifier<? extends DataObject>, DataObject> delegate) {
         this.delegate = delegate;
     }
 
     @SuppressWarnings("unchecked")
-    public <D extends DataObject> D readConfigurationData(InstanceIdentifier<D> path) {
+    public <D extends DataObject> D readConfigurationData(
+            final InstanceIdentifier<D> path) {
         return (D) delegate.readConfigurationData(path);
     }
 
     @SuppressWarnings("unchecked")
-    public <D extends DataObject> D readOperationalData(InstanceIdentifier<D> path) {
+    public <D extends DataObject> D readOperationalData(
+            final InstanceIdentifier<D> path) {
         return (D) delegate.readOperationalData(path);
     }
 
-    public static TypeSafeDataReader forReader(DataReader<InstanceIdentifier<? extends DataObject>, DataObject> delegate) {
+    public static TypeSafeDataReader forReader(
+            final DataReader<InstanceIdentifier<? extends DataObject>, DataObject> delegate) {
         return new TypeSafeDataReader(delegate);
     }
 }
index fb429e5fd1342c0ca675040a315c1b8ad76456c7..3a68092f07e27f0ffe56dc090c01a0e04b37d3fd 100644 (file)
@@ -12,14 +12,11 @@ import org.opendaylight.yangtools.concepts.Path;
 
 /**
  *
- * Provides access to a conceptual data tree store.
+ * Base interface that provides access to a conceptual data tree store and also provides the ability to
+ * subscribe for changes to data under a given branch of the tree.
  *
  * <p>
- * Also provides the ability to subscribe for changes to data under a given
- * branch of the tree.
- *
- * <p>
- * All operations on data tree are performed via one of the transactions:
+ * All operations on the data tree are performed via one of the transactions:
  * <ul>
  * <li>Read-Only - allocated using {@link #newReadOnlyTransaction()}
  * <li>Write-Only - allocated using {@link #newWriteOnlyTransaction()}
@@ -133,7 +130,7 @@ public interface AsyncDataBroker<P extends Path<P>, D, L extends AsyncDataChange
      * {@inheritDoc}
      */
     @Override
-    public AsyncReadTransaction<P, D> newReadOnlyTransaction();
+    public AsyncReadOnlyTransaction<P, D> newReadOnlyTransaction();
 
     /**
      * {@inheritDoc}
index 29c9bae31f76e2b1a1269116c2b3438cfa572172..ac4a0ffc331226504b47b5f1cf45b996b0522b5c 100644 (file)
@@ -101,7 +101,7 @@ public interface AsyncDataChangeEvent<P extends Path<P>, D> extends Immutable {
      *
      * @return map of paths and original state of updated and removed objects.
      */
-    Map<P, ? extends D> getOriginalData();
+    Map<P, D> getOriginalData();
 
     /**
      * Returns an immutable stable view of data state, which captures the state of
index dca5200d392687e25493876f945e347d3e394bf4..0bdaf7bf3766736aa76337a1e6e772e036ed0cb5 100644 (file)
@@ -41,9 +41,12 @@ public interface AsyncDataChangeListener<P extends Path<P>, D> extends EventList
      * This initial event will contain all preexisting data as created.
      *
      * <p>
-     * <b>Note</b> that this method may be invoked from a shared thread pool, so
-     * implementations SHOULD NOT perform CPU-intensive operations and they
-     * definitely MUST NOT invoke any potentially blocking operations.
+     * <b>Note</b>: This method may be invoked from a shared thread pool.
+     * <li>Implementations <b>SHOULD NOT</b> perform CPU-intensive operations on the calling thread.
+     * <li>Implementations <b>MUST NOT block the calling thread</b> - to do so could lead to deadlock
+     * scenarios.
+     *
+     *<br>
      *
      * @param change
      *            Data Change Event being delivered.
index cedd883b220199116502b47bc034ac1fe98ea5f2..a558b96b2d56fa26658741d8ee11ac63f3e735a3 100644 (file)
@@ -72,7 +72,7 @@ public interface AsyncDataTransactionFactory<P extends Path<P>, D> {
      *
      * @return new read-only transaction
      */
-    AsyncReadTransaction<P, D> newReadOnlyTransaction();
+    AsyncReadOnlyTransaction<P, D> newReadOnlyTransaction();
 
     /**
      * Allocates new read-write transaction which provides a mutable view of the data
diff --git a/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncReadOnlyTransaction.java b/opendaylight/md-sal/sal-common-api/src/main/java/org/opendaylight/controller/md/sal/common/api/data/AsyncReadOnlyTransaction.java
new file mode 100644 (file)
index 0000000..46c90b9
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * 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.common.api.data;
+
+import org.opendaylight.yangtools.concepts.Path;
+
+/**
+ * Marker interface for a read-only view of the data tree.
+ *
+ * @see AsyncReadTransaction
+ *
+ * @param <P>
+ *            Type of path (subtree identifier), which represents location in
+ *            tree
+ * @param <D>
+ *            Type of data (payload), which represents data payload
+ */
+public interface AsyncReadOnlyTransaction<P extends Path<P>, D> extends AsyncReadTransaction<P, D>, AutoCloseable {
+
+    /**
+     * Closes this transaction and releases all resources associated with it.
+     *
+     */
+    @Override
+    public void close();
+}
index 6cf5a5b532d41725ce76f45299536de76c63ece2..afa86704ff7de0e17c12b3a15f401f9c88f06232 100644 (file)
@@ -9,12 +9,9 @@ package org.opendaylight.controller.md.sal.common.api.data;
 
 import org.opendaylight.yangtools.concepts.Path;
 
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.ListenableFuture;
-
 /**
  *
- * Provides a stateful read-only view of the data tree.
+ * Marker interface for stateful read view of the data tree.
  *
  * <p>
  * View of the data tree is a stable point-in-time snapshot of the current data tree state when
@@ -25,8 +22,8 @@ import com.google.common.util.concurrent.ListenableFuture;
  * <b>Implementation Note:</b> This interface is not intended to be implemented
  * by users of MD-SAL, but only to be consumed by them.
  *
- * <h2>Transaction isolation example</h2> Lest assume initial state of data tree
- * for <code>PATH</code> is <code>A</code>.
+ * <h2>Transaction isolation example</h2>
+ * Lets assume initial state of data tree for <code>PATH</code> is <code>A</code>.
  *
  * <pre>
  * txRead = broker.newReadOnlyTransaction();   // read Transaction is snapshot of data
@@ -47,9 +44,9 @@ import com.google.common.util.concurrent.ListenableFuture;
  * <p>
  * <b>Note:</b> example contains blocking calls on future only to illustrate
  * that action happened after other asynchronous action. Use of blocking call
- * {@link ListenableFuture#get()} is discouraged for most uses and you should
- * use
- * {@link com.google.common.util.concurrent.Futures#addCallback(ListenableFuture, com.google.common.util.concurrent.FutureCallback)}
+ * {@link com.google.common.util.concurrent.ListenableFuture#get()} is discouraged for most
+ * uses and you should use
+ * {@link com.google.common.util.concurrent.Futures#addCallback(com.google.common.util.concurrent.ListenableFuture, com.google.common.util.concurrent.FutureCallback)}
  * or other functions from {@link com.google.common.util.concurrent.Futures} to
  * register more specific listeners.
  *
@@ -58,30 +55,10 @@ import com.google.common.util.concurrent.ListenableFuture;
  *            tree
  * @param <D>
  *            Type of data (payload), which represents data payload
+ *
+ * @see org.opendaylight.controller.md.sal.binding.api.ReadTransaction
+ * @see org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction
  */
 public interface AsyncReadTransaction<P extends Path<P>, D> extends AsyncTransaction<P, D> {
 
-    /**
-     *
-     * Reads data from provided logical data store located at the provided path.
-     *<p>
-     * If the target is a subtree, then the whole subtree is read (and will be
-     * accessible from the returned data object).
-     *
-     * @param store
-     *            Logical data store from which read should occur.
-     * @param path
-     *            Path which uniquely identifies subtree which client want to
-     *            read
-     * @return Listenable Future which contains read result
-     *         <ul>
-     *         <li>If data at supplied path exists the
-     *         {@link ListeblaFuture#get()} returns Optional object containing
-     *         data once read is done.
-     *         <li>If data at supplied path does not exists the
-     *         {@link ListenbleFuture#get()} returns {@link Optional#absent()}.
-     *         </ul>
-     */
-    ListenableFuture<Optional<D>> read(LogicalDatastoreType store, P path);
-
 }
index 34101366c806fe56884622ed3118e7d35090228c..16b4ed4fe2ed14d7cf7db8e5e88621df801d9f1c 100644 (file)
@@ -124,6 +124,8 @@ import org.opendaylight.yangtools.concepts.Path;
  * or other functions from {@link com.google.common.util.concurrent.Futures} to
  * register more specific listeners.
  *
+ * @see AsyncReadTransaction
+ * @see AsyncWriteTransaction
  *
  * @param <P>
  *            Type of path (subtree identifier), which represents location in
index c7cc91528b7c255f60416df67e1ebddf4660c7b5..08ddfe689819702e5805bb8a78f5dbee6eb2f4ee 100644 (file)
@@ -29,15 +29,10 @@ import org.opendaylight.yangtools.concepts.Path;
  * @param <D> Type of data (payload), which represents data payload
  */
 public interface AsyncTransaction<P extends Path<P>,D> extends //
-    Identifiable<Object>,
-    AutoCloseable {
+    Identifiable<Object> {
 
     @Override
     public Object getIdentifier();
 
-    /**
-     * Closes transaction and releases all resources associated with it.
-     */
-    @Override
-    public void close();
+
 }
index e2734eaddc4845396e3d866dec8d918ac9fe4bca..f7eae27320107ef6a90696ff73f2cf40b3c99fde 100644 (file)
@@ -53,13 +53,19 @@ public interface AsyncWriteTransaction<P extends Path<P>, D> extends AsyncTransa
      * {@link TransactionStatus#NEW} or {@link TransactionStatus#SUBMITED}
      *
      * Invoking cancel() on {@link TransactionStatus#FAILED} or
-     * {@link TransactionStatus#CANCELED} will have no effect.
+     * {@link TransactionStatus#CANCELED} will have no effect, and transaction
+     * is considered cancelled.
      *
-     * @throws IllegalStateException
-     *             If transaction status is {@link TransactionStatus#COMMITED}
+     * Invoking cancel() on finished transaction  (future returned by {@link #commit()}
+     * already completed with {@link TransactionStatus#COMMITED}) will always
+     * fail (return false).
+     *
+     * @return <tt>false</tt> if the task could not be cancelled,
+     * typically because it has already completed normally;
+     * <tt>true</tt> otherwise
      *
      */
-    public void cancel();
+    public boolean cancel();
 
     /**
      * Store a piece of data at specified path. This acts as an add / replace
@@ -141,20 +147,6 @@ public interface AsyncWriteTransaction<P extends Path<P>, D> extends AsyncTransa
      */
     public void delete(LogicalDatastoreType store, P path);
 
-    /**
-     *
-     * Closes transaction and resources allocated to the transaction.
-     *
-     * This call does not change Transaction status. Client SHOULD explicitly
-     * {@link #commit()} or {@link #cancel()} transaction.
-     *
-     * @throws IllegalStateException
-     *             if the transaction has not been updated by invoking
-     *             {@link #commit()} or {@link #cancel()}.
-     */
-    @Override
-    public void close();
-
     /**
      * Submits transaction to be applied to update logical data tree.
      * <p>
index 15d1daa1bbe882393f863e892728490c212f5e71..5e5ea0c1388da6b4ca85718a53fcef43feb8fb31 100644 (file)
@@ -10,6 +10,15 @@ package org.opendaylight.controller.md.sal.common.api.data;
 import org.opendaylight.yangtools.concepts.Immutable;
 import org.opendaylight.yangtools.concepts.Path;
 
+/**
+ *
+ *
+ *
+ * @param <P>
+ * @param <D>
+ * @deprecated Replaced by {@link AsyncDataChangeEvent}
+ */
+@Deprecated
 public interface DataChangeEvent<P extends Path<P>,D> extends DataChange<P, D>, Immutable {
 
     /**
index 669baa8d9e96a6601bfe7cbe49cb99d2ffb00233..21006173f205603d481211db5a733475e50a7ee5 100644 (file)
@@ -10,7 +10,12 @@ package org.opendaylight.controller.md.sal.common.api.data;
 import java.util.EventListener;
 
 import org.opendaylight.yangtools.concepts.Path;
-
+/**
+ *
+ *
+ * @deprecated Replaced by {@link AsyncDataChangeEvent}
+ */
+@Deprecated
 public interface DataChangeListener<P extends Path<P>, D> extends EventListener {
     /**
      * Note that this method may be invoked from a shared thread pool, so
index 0c4c6d179ff84faf955fb6989d8ca900cbb8722e..222dba8eafc8e1be5bec4aab39ede6ca9187685d 100644 (file)
@@ -10,6 +10,11 @@ package org.opendaylight.controller.md.sal.common.api.data;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.concepts.Path;
 
+/**
+ *
+ * @deprecated Replaced by {@link AsyncDataBroker}
+ */
+@Deprecated
 public interface DataChangePublisher<P extends Path<P>, D, L extends DataChangeListener<P,D>> {
 
     ListenerRegistration<L> registerDataChangeListener(P path, L listener);
index 22e95197bb4c2fb9c3886492cf7635cacf18c7d2..a9f02a8ee5ed13cac55a436311f1b556225703c0 100644 (file)
@@ -79,7 +79,9 @@ import org.opendaylight.yangtools.yang.common.RpcResult;
  *
  * @param <P> Class representing a path
  * @param <D> Superclass from which all data objects are derived from.
+ * @deprecated Replaced by {@link AsyncConfigurationCommitHandler}
  */
+@Deprecated
 public interface DataCommitHandler<P extends Path<P>, D> {
 
 
index 86f1f9b13875ba4015e6bb5dbb111f693ba07b57..224751c37dbd8dabebe44da114b8d1055253877e 100644 (file)
@@ -10,6 +10,16 @@ package org.opendaylight.controller.md.sal.common.api.data;
 import org.opendaylight.yangtools.concepts.Path;
 import org.opendaylight.yangtools.concepts.Registration;
 
+/**
+ *
+ *
+ * @deprecated THis was intended as Registration object, normal use of {@link org.opendaylight.yangtools.concepts.ObjectRegistration}
+ * is suffiecient, since {@link #getPath()} was implementation leak.
+ *
+ * @param <P>
+ * @param <D>
+ */
+@Deprecated
 public interface DataCommitHandlerRegistration<P extends Path<P>,D> extends Registration<DataCommitHandler<P, D>>{
 
     P getPath();
index 22c5fa0c1d25eb4a71e19b2b271a5a777dada2e3..630078dcedea1da1a45a279d3f2ed3e313858a69 100644 (file)
@@ -12,7 +12,11 @@ import java.util.concurrent.Future;
 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
 import org.opendaylight.yangtools.concepts.Path;
 import org.opendaylight.yangtools.yang.common.RpcResult;
-
+/**
+ *
+ * @deprecated Replaced by {@link AsyncWriteTransaction}
+ */
+@Deprecated
 public interface DataModification<P extends Path<P>, D> extends DataChange<P, D>, DataReader<P, D> {
     /**
      * Returns transaction identifier
index 34f6fe970dd2e0105e6a21d32ca7049815ea87e7..6a370b8cd168be3f196b779523e3a8cd8bb03ef9 100644 (file)
@@ -8,7 +8,11 @@
 package org.opendaylight.controller.md.sal.common.api.data;
 
 import org.opendaylight.yangtools.concepts.Path;
-
+/**
+ *
+ * @deprecated Replaced by {@link AsyncDataTransactionFactory}
+ */
+@Deprecated
 public interface DataModificationTransactionFactory<P extends Path<P> ,D> {
 
     DataModification<P, D> beginTransaction();
index dae9a1144b966a2e3c5e61884c1281e09a6229f3..fdeda2800bbd447ac028a028172347e5a30ce043 100644 (file)
@@ -9,6 +9,12 @@ package org.opendaylight.controller.md.sal.common.api.data;
 
 import org.opendaylight.yangtools.concepts.Path;
 
+/**
+ *
+ *
+ * @deprecated Replaced by org.opendaylight.controller.sal.core.spi.data.DOMStore contract.
+ */
+@Deprecated
 public interface DataProvider<P extends Path<P>, D> extends DataReader<P, D> {
 
 }
index da7efebdfeb1f7f02eda505d48a1f83be6a79b89..bd80a5389316f754a202af7c363c2332f7951859 100644 (file)
@@ -12,7 +12,12 @@ import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.concepts.Path;
 import org.opendaylight.yangtools.concepts.Registration;
 
-
+/**
+ *
+ *
+ * @deprecated replaced by {@link AsyncDataBroker} and {@link AsyncConfigurationCommitCoordinator}
+ */
+@Deprecated
 public interface DataProvisionService<P extends Path<P> , D> {
 
     public Registration<DataCommitHandler<P, D>> registerCommitHandler(P path, DataCommitHandler<P, D> commitHandler);
index 14731d688c964adaf264d8909a4c3e90ccc4484e..2f657b8e5049dc196fbb5a04d3ddcc5f0a5a244a 100644 (file)
@@ -17,7 +17,9 @@ import org.opendaylight.yangtools.concepts.Path;
  *
  * @param <P> Path Type
  * @param <D> Data Type
+ * @deprecated Replaced by org.opendaylight.controller.sal.core.spi.data.DOMStore contract.
  */
+@Deprecated
 public interface DataReader<P extends Path<P> ,D> {
 
     /**
index 3520ba1819b42fb0ce37ae3548631cd80753334b..5688dd0988968b52a2957cd9998b0f98c8995e4a 100644 (file)
@@ -9,6 +9,11 @@ package org.opendaylight.controller.md.sal.common.api.data;
 
 import org.opendaylight.yangtools.concepts.Path;
 
+/**
+ *
+ * @deprecated Replaced by org.opendaylight.controller.sal.core.spi.data.DOMStore Contract.
+ */
+@Deprecated
 public interface DataStore<P extends Path<P>, D> extends //
         DataReader<P, D>, //
         DataModificationTransactionFactory<P, D> {
index e7e0eb0ff87e424973de4b9c9d6fdf9111ccae4c..940559ef895bf9cec406eee2fbe73a7617da581a 100644 (file)
@@ -27,7 +27,7 @@ public interface TransactionChain<P extends Path<P>, D> extends AutoCloseable, A
      * @throws TransactionChainClosedException if the chain has been closed.
      */
     @Override
-    public AsyncReadTransaction<P, D> newReadOnlyTransaction();
+    public AsyncReadOnlyTransaction<P, D> newReadOnlyTransaction();
 
 
     /**
index f5f03a106b36119b188ca489924d514f88b12f00..bb866f276e713151ccf18b0e57e589c65633647f 100644 (file)
@@ -9,9 +9,63 @@ package org.opendaylight.controller.md.sal.common.api.notify;
 
 import java.util.concurrent.ExecutorService;
 
+/**
+ * Interface for publishing YANG-modeled notifications.
+ * <p>
+ * Users of this interface can publish any YANG-modeled notification which will
+ * be delivered to all subscribed listeners.
+ * <p>
+ * Prefered way of publishing of notifications is done by invoking {@link #publish(Object)}.
+ *
+ * <p>You may consider using {@link #publish(Object, ExecutorService)} if and only if
+ * your use-case requires customized  execution policy or run-to-completion
+ * inside process.
+ *
+ * <p>
+ * The metadata required to deliver a notification to the correct listeners is
+ * extracted from the published notification.
+ *
+ *
+ * FIXME: Consider clarification of execution/delivery policy, how it will be
+ * affected by Actor model and cluster-wide notifications.
+ *
+ * @param <N>
+ *            the type of notifications
+ */
 public interface NotificationPublishService<N> {
 
+    /**
+     * Publishes a notification and notifies subscribed listeners. All listener
+     * notifications are done via a default executor.
+     * <p>
+     * <b>Note:</b> This call will block when the default executor is saturated
+     * and the notification queue for this executor is full.
+     *
+     * @param notification
+     *            the notification to publish.
+     */
     void publish(N notification);
 
-    void publish(N notification,ExecutorService executor);
+    /**
+     * Publishes a notification and notifies subscribed listeners. All listener
+     * notifications are done via the provided executor.
+     * <p>
+     * <b>Note:</b> Use only if ineccessary. Consider using
+     * {@link #publish(Object)} for most use-cases.
+     *
+     * <p>
+     * By using this method you could customize execution policy of listeners present
+     * inside process (e.g. using  single-threaded executor or even same-thread executor
+     * delivery.
+     *
+     * <p>
+     * This executor is used only for inside-process notification deliveries.
+     *
+     * @param notification
+     *            the notification to publish.
+     * @param executor
+     *            the executor that will be used to deliver notifications to
+     *            subscribed listeners.
+     */
+    void publish(N notification, ExecutorService executor);
 }
index 5f84ec579d7dd25bdc9580f785aca6d300c35a0a..0c04b936b668847d6914cefe522190751f10f733 100644 (file)
@@ -9,9 +9,36 @@ package org.opendaylight.controller.md.sal.common.api.routing;
 
 import java.util.Map;
 import java.util.Set;
-
+/**
+ * Event representing change in RPC routing table.
+ *
+ *
+ * @param <C> Type, which is used to represent Routing context.
+ * @param <P> Type of data tree path, which is used to identify route.
+ */
 public interface RouteChange<C,P> {
 
+    /**
+     *
+     * Returns a map of removed routes in associated routing contexts.
+     * <p>
+     * This map represents routes, which were withdrawn from broker local
+     * routing table and broker may need to forward RPC to other broker
+     * in order to process RPC request.
+     *
+     * @return Map of contexts and removed routes
+     */
     Map<C,Set<P>> getRemovals();
+    /**
+    *
+    * Returns a map of announced routes in associated routing contexts.
+    *
+    * This map represents routes, which were announced by broker
+    * and are present in broker's local routing table. This routes
+    * are processed by implementations which are registered
+    * to originating broker.
+    *
+    * @return Map of contexts and announced routes
+    */
     Map<C,Set<P>> getAnnouncements();
 }
index 62206013f816fea5a85885e1f5696d6b93603a4f..b3b6fe6ee93ba44a30abaf32028044c7c89d006f 100644 (file)
@@ -8,8 +8,23 @@
 package org.opendaylight.controller.md.sal.common.api.routing;
 
 import java.util.EventListener;
-
+/**
+ *
+ * Listener which is interested in receiving RouteChangeEvents
+ * for its local broker.
+ * <p>
+ * Listener is registerd via {@link RouteChangePublisher#registerRouteChangeListener(RouteChangeListener)}
+ *
+ *
+ * @param <C> Type, which is used to represent Routing context.
+ * @param <P> Type of data tree path, which is used to identify route.
+ */
 public interface RouteChangeListener<C,P> extends EventListener {
 
+    /**
+     * Callback which is invoked if there is an rpc routing table change.
+     *
+     * @param change Event representing change in local RPC routing table.
+     */
     void onRouteChange(RouteChange<C, P> change);
 }
index 7bf61fab0b726cd9ebc4f3fdcac428c447f74b26..dc6b6dd3b7d89c3d23a3ed6bf7e2157bd49bbc4c 100644 (file)
@@ -9,6 +9,12 @@ package org.opendaylight.controller.md.sal.common.api.routing;
 
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
 
+/**
+ * Publishes changes in local RPC routing table to registered listener.
+ *
+ * @param <C> Type, which is used to represent Routing context.
+ * @param <P> Type of data tree path, which is used to identify route.
+ */
 public interface RouteChangePublisher<C,P> {
 
     <L extends RouteChangeListener<C,P>> ListenerRegistration<L> registerRouteChangeListener(L listener);
index 6ce7b5a5c7f990360ff1d5cb3d01e63989fc42da..6fe8d6921730fc55e4fe3900ea66823ee2b644ed 100644 (file)
@@ -10,9 +10,31 @@ package org.opendaylight.controller.md.sal.common.api.routing;
 import org.opendaylight.yangtools.concepts.Path;
 import org.opendaylight.yangtools.concepts.Registration;
 
+/**
+ * Base interface for a routed RPC RPC implementation registration.
+ *
+ * @param <C> the context type used for routing
+ * @param <P> the path identifier type
+ * @param <S> the RPC implementation type
+ */
 public interface RoutedRegistration<C, P extends Path<P>, S> extends Registration<S> {
 
+    /**
+     * Registers the RPC implementation associated with this registration for the given path
+     * identifier and context.
+     *
+     * @param context the context used for routing RPCs to this implementation.
+     * @param path the path identifier for which to register.
+     */
     void registerPath(C context, P path);
+
+    /**
+     * Unregisters the RPC implementation associated with this registration for the given path
+     * identifier and context.
+     *
+     * @param context the context used for routing RPCs to this implementation.
+     * @param path the path identifier for which to unregister.
+     */
     void unregisterPath(C context, P path);
 
     @Override
index a51dc64816d0822778ff1b690bd10fdd19268afa..007122e41df26eaf6c3c9e803e2d3f75abcf8deb 100644 (file)
@@ -8,7 +8,6 @@
 package org.opendaylight.controller.md.sal.common.impl.service;
 
 import java.util.ArrayList;
-import java.util.Collections;
 import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
@@ -21,10 +20,9 @@ import org.opendaylight.controller.md.sal.common.api.data.DataChangeEvent;
 import org.opendaylight.controller.md.sal.common.api.data.DataChangeListener;
 import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler;
 import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler.DataCommitTransaction;
-import org.opendaylight.controller.sal.common.util.Rpcs;
 import org.opendaylight.yangtools.concepts.Path;
-import org.opendaylight.yangtools.yang.common.RpcError;
 import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -68,8 +66,7 @@ public class TwoPhaseCommit<P extends Path<P>, D extends Object, DCL extends Dat
 
             log.trace("Transaction: {} Finished successfully (no effects).", transactionId);
 
-            return Rpcs.<TransactionStatus> getRpcResult(true, TransactionStatus.COMMITED,
-                    Collections.<RpcError> emptySet());
+            return RpcResultBuilder.<TransactionStatus> success( TransactionStatus.COMMITED ).build();
         }
 
         final ImmutableList.Builder<ListenerStateCapture<P, D, DCL>> listenersBuilder = ImmutableList.builder();
@@ -127,8 +124,7 @@ public class TwoPhaseCommit<P extends Path<P>, D extends Object, DCL extends Dat
         log.trace("Transaction: {} Notifying listeners.", transactionId);
 
         publishDataChangeEvent(listeners);
-        return Rpcs.<TransactionStatus> getRpcResult(true, TransactionStatus.COMMITED,
-                Collections.<RpcError> emptySet());
+        return RpcResultBuilder.<TransactionStatus> success(TransactionStatus.COMMITED).build();
     }
 
     private void captureInitialState(ImmutableList<ListenerStateCapture<P, D, DCL>> listeners) {
@@ -240,7 +236,6 @@ public class TwoPhaseCommit<P extends Path<P>, D extends Object, DCL extends Dat
         for (final DataCommitTransaction<P, D> transaction : transactions) {
             transaction.rollback();
         }
-        Set<RpcError> _emptySet = Collections.<RpcError> emptySet();
-        return Rpcs.<TransactionStatus> getRpcResult(false, TransactionStatus.FAILED, _emptySet);
+        return RpcResultBuilder.<TransactionStatus> failed().withResult(TransactionStatus.FAILED).build();
     }
 }
index 7ce475dd59ea1a056ac8d5a85d751a33f6d9a17f..617697710449b32602682802d10dd2022f551ee2 100644 (file)
@@ -10,10 +10,6 @@ package org.opendaylight.controller.md.sal.common.impl.util.compat;
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkNotNull;
 
-import com.google.common.base.Optional;
-import com.google.common.collect.FluentIterable;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
 import java.util.Collections;
 import java.util.HashSet;
 import java.util.List;
@@ -21,6 +17,7 @@ import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
+
 import org.opendaylight.yangtools.concepts.Identifiable;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
@@ -50,19 +47,31 @@ import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaNode;
+
+import com.google.common.base.Optional;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
 
 public abstract class DataNormalizationOperation<T extends PathArgument> implements Identifiable<T> {
 
     private final T identifier;
+    private final Optional<DataSchemaNode> dataSchemaNode;
 
     @Override
     public T getIdentifier() {
         return identifier;
     };
 
-    protected DataNormalizationOperation(final T identifier) {
+    protected DataNormalizationOperation(final T identifier, final SchemaNode schema) {
         super();
         this.identifier = identifier;
+        if(schema instanceof DataSchemaNode) {
+            this.dataSchemaNode = Optional.of((DataSchemaNode) schema);
+        } else {
+            this.dataSchemaNode = Optional.absent();
+        }
     }
 
     public boolean isMixin() {
@@ -86,10 +95,15 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
 
     public abstract boolean isLeaf();
 
+    public Optional<DataSchemaNode> getDataSchemaNode() {
+        // FIXME
+        return dataSchemaNode;
+    }
+
     private static abstract class SimpleTypeNormalization<T extends PathArgument> extends DataNormalizationOperation<T> {
 
-        protected SimpleTypeNormalization(final T identifier) {
-            super(identifier);
+        protected SimpleTypeNormalization(final T identifier, final DataSchemaNode potential) {
+            super(identifier,potential);
         }
 
         @Override
@@ -125,8 +139,8 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
 
     private static final class LeafNormalization extends SimpleTypeNormalization<NodeIdentifier> {
 
-        protected LeafNormalization(final NodeIdentifier identifier) {
-            super(identifier);
+        protected LeafNormalization(final LeafSchemaNode potential) {
+            super(new NodeIdentifier(potential.getQName()),potential);
         }
 
         @Override
@@ -139,7 +153,7 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
     private static final class LeafListEntryNormalization extends SimpleTypeNormalization<NodeWithValue> {
 
         public LeafListEntryNormalization(final LeafListSchemaNode potential) {
-            super(new NodeWithValue(potential.getQName(), null));
+            super(new NodeWithValue(potential.getQName(), null),potential);
         }
 
         @Override
@@ -156,10 +170,10 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
     }
 
     private static abstract class CompositeNodeNormalizationOperation<T extends PathArgument> extends
-            DataNormalizationOperation<T> {
+    DataNormalizationOperation<T> {
 
-        protected CompositeNodeNormalizationOperation(final T identifier) {
-            super(identifier);
+        protected CompositeNodeNormalizationOperation(final T identifier, final DataSchemaNode schema) {
+            super(identifier,schema);
         }
 
         @SuppressWarnings({ "rawtypes", "unchecked" })
@@ -218,14 +232,14 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
     }
 
     private static abstract class DataContainerNormalizationOperation<T extends PathArgument> extends
-            CompositeNodeNormalizationOperation<T> {
+    CompositeNodeNormalizationOperation<T> {
 
         private final DataNodeContainer schema;
         private final Map<QName, DataNormalizationOperation<?>> byQName;
         private final Map<PathArgument, DataNormalizationOperation<?>> byArg;
 
-        protected DataContainerNormalizationOperation(final T identifier, final DataNodeContainer schema) {
-            super(identifier);
+        protected DataContainerNormalizationOperation(final T identifier, final DataNodeContainer schema, final DataSchemaNode node) {
+            super(identifier,node);
             this.schema = schema;
             this.byArg = new ConcurrentHashMap<>();
             this.byQName = new ConcurrentHashMap<>();
@@ -276,12 +290,12 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
     }
 
     private static final class ListItemNormalization extends
-            DataContainerNormalizationOperation<NodeIdentifierWithPredicates> {
+    DataContainerNormalizationOperation<NodeIdentifierWithPredicates> {
 
         private final List<QName> keyDefinition;
 
         protected ListItemNormalization(final NodeIdentifierWithPredicates identifier, final ListSchemaNode schema) {
-            super(identifier, schema);
+            super(identifier, schema,schema);
             keyDefinition = schema.getKeyDefinition();
         }
 
@@ -322,7 +336,7 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
     private static final class UnkeyedListItemNormalization extends DataContainerNormalizationOperation<NodeIdentifier> {
 
         protected UnkeyedListItemNormalization(final ListSchemaNode schema) {
-            super(new NodeIdentifier(schema.getQName()), schema);
+            super(new NodeIdentifier(schema.getQName()), schema,schema);
         }
 
         @Override
@@ -340,7 +354,7 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
     private static final class ContainerNormalization extends DataContainerNormalizationOperation<NodeIdentifier> {
 
         protected ContainerNormalization(final ContainerSchemaNode schema) {
-            super(new NodeIdentifier(schema.getQName()), schema);
+            super(new NodeIdentifier(schema.getQName()),schema, schema);
         }
 
         @Override
@@ -356,10 +370,10 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
     }
 
     private static abstract class MixinNormalizationOp<T extends PathArgument> extends
-            CompositeNodeNormalizationOperation<T> {
+    CompositeNodeNormalizationOperation<T> {
 
-        protected MixinNormalizationOp(final T identifier) {
-            super(identifier);
+        protected MixinNormalizationOp(final T identifier, final DataSchemaNode schema) {
+            super(identifier,schema);
         }
 
         @Override
@@ -393,7 +407,7 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
         private final DataNormalizationOperation<?> innerOp;
 
         public UnorderedLeafListMixinNormalization(final LeafListSchemaNode potential) {
-            super(new NodeIdentifier(potential.getQName()));
+            super(new NodeIdentifier(potential.getQName()),potential);
             innerOp = new LeafListEntryNormalization(potential);
         }
 
@@ -428,7 +442,7 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
 
         public AugmentationNormalization(final AugmentationSchema augmentation, final DataNodeContainer schema) {
             //super();
-            super(augmentationIdentifierFrom(augmentation), augmentationProxy(augmentation,schema));
+            super(augmentationIdentifierFrom(augmentation), augmentationProxy(augmentation,schema),null);
         }
 
         @Override
@@ -477,7 +491,7 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
         private final ListItemNormalization innerNode;
 
         public UnorderedMapMixinNormalization(final ListSchemaNode list) {
-            super(new NodeIdentifier(list.getQName()));
+            super(new NodeIdentifier(list.getQName()),list);
             this.innerNode = new ListItemNormalization(new NodeIdentifierWithPredicates(list.getQName(),
                     Collections.<QName, Object> emptyMap()), list);
         }
@@ -517,7 +531,7 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
         private final UnkeyedListItemNormalization innerNode;
 
         public UnkeyedListMixinNormalization(final ListSchemaNode list) {
-            super(new NodeIdentifier(list.getQName()));
+            super(new NodeIdentifier(list.getQName()),list);
             this.innerNode = new UnkeyedListItemNormalization(list);
         }
 
@@ -575,7 +589,7 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
         private final ImmutableMap<PathArgument, DataNormalizationOperation<?>> byArg;
 
         protected ChoiceNodeNormalization(final org.opendaylight.yangtools.yang.model.api.ChoiceNode schema) {
-            super(new NodeIdentifier(schema.getQName()));
+            super(new NodeIdentifier(schema.getQName()),schema);
             ImmutableMap.Builder<QName, DataNormalizationOperation<?>> byQNameBuilder = ImmutableMap.builder();
             ImmutableMap.Builder<PathArgument, DataNormalizationOperation<?>> byArgBuilder = ImmutableMap.builder();
 
@@ -615,25 +629,25 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
 
     private static class AnyXmlNormalization extends DataNormalizationOperation<NodeIdentifier> {
 
-        protected AnyXmlNormalization( NodeIdentifier identifier ) {
-            super( identifier );
+        protected AnyXmlNormalization( final AnyXmlSchemaNode schema) {
+            super( new NodeIdentifier(schema.getQName()), schema);
         }
 
         @Override
-        public DataNormalizationOperation<?> getChild( PathArgument child ) throws DataNormalizationException {
+        public DataNormalizationOperation<?> getChild( final PathArgument child ) throws DataNormalizationException {
             return null;
         }
 
         @Override
-        public DataNormalizationOperation<?> getChild( QName child ) throws DataNormalizationException {
+        public DataNormalizationOperation<?> getChild( final QName child ) throws DataNormalizationException {
             return null;
         }
 
         @Override
-        public NormalizedNode<?, ?> normalize( Node<?> legacyData ) {
+        public NormalizedNode<?, ?> normalize( final Node<?> legacyData ) {
             NormalizedNodeAttrBuilder<NodeIdentifier, Node<?>, AnyXmlNode> builder =
                     Builders.anyXmlBuilder().withNodeIdentifier(
-                                                new NodeIdentifier( legacyData.getNodeType() ) );
+                            new NodeIdentifier( legacyData.getNodeType() ) );
             builder.withValue(legacyData);
             return builder.build();
         }
@@ -644,7 +658,7 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
         }
 
         @Override
-        public NormalizedNode<?, ?> createDefault( PathArgument currentArg ) {
+        public NormalizedNode<?, ?> createDefault( final PathArgument currentArg ) {
             return null;
         }
     }
@@ -694,7 +708,7 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
         for (DataSchemaNode child : augmentation.getChildNodes()) {
             potentialChildren.add(child.getQName());
         }
-        return new AugmentationIdentifier(null, potentialChildren.build());
+        return new AugmentationIdentifier(potentialChildren.build());
     }
 
     private static DataNodeContainer augmentationProxy(final AugmentationSchema augmentation, final DataNodeContainer schema) {
@@ -744,13 +758,13 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
 
             return fromListSchemaNode((ListSchemaNode) potential);
         } else if (potential instanceof LeafSchemaNode) {
-            return new LeafNormalization(new NodeIdentifier(potential.getQName()));
+            return new LeafNormalization((LeafSchemaNode) potential);
         } else if (potential instanceof org.opendaylight.yangtools.yang.model.api.ChoiceNode) {
             return new ChoiceNodeNormalization((org.opendaylight.yangtools.yang.model.api.ChoiceNode) potential);
         } else if (potential instanceof LeafListSchemaNode) {
             return fromLeafListSchemaNode((LeafListSchemaNode) potential);
         } else if (potential instanceof AnyXmlSchemaNode) {
-            return new AnyXmlNormalization( new NodeIdentifier(potential.getQName() ) );
+            return new AnyXmlNormalization( (AnyXmlSchemaNode) potential);
         }
         return null;
     }
index ec8ce6ecd5a96e628d2883ab38f24aaab383095a..e2a960a67aae708d34a4145479b8797fe535d0d6 100644 (file)
@@ -9,15 +9,11 @@ package org.opendaylight.controller.md.sal.common.impl.util.compat;
 
 import static com.google.common.base.Preconditions.checkArgument;
 
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicates;
-import com.google.common.collect.FluentIterable;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
 import java.util.AbstractMap;
 import java.util.ArrayList;
 import java.util.Iterator;
 import java.util.Map;
+
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
@@ -36,6 +32,12 @@ import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
+import com.google.common.base.Preconditions;
+import com.google.common.base.Predicates;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+
 public class DataNormalizer {
 
     private final DataNormalizationOperation<?> operation;
@@ -48,7 +50,7 @@ public class DataNormalizer {
         ImmutableList.Builder<PathArgument> normalizedArgs = ImmutableList.builder();
 
         DataNormalizationOperation<?> currentOp = operation;
-        Iterator<PathArgument> arguments = legacy.getPath().iterator();
+        Iterator<PathArgument> arguments = legacy.getPathArguments().iterator();
 
         try {
             while (arguments.hasNext()) {
@@ -67,7 +69,17 @@ public class DataNormalizer {
             throw new IllegalArgumentException(String.format("Failed to normalize path %s", legacy), e);
         }
 
-        return new InstanceIdentifier(normalizedArgs.build());
+        return InstanceIdentifier.create(normalizedArgs.build());
+    }
+
+    public DataNormalizationOperation<?> getOperation(final InstanceIdentifier legacy) throws DataNormalizationException {
+        DataNormalizationOperation<?> currentOp = operation;
+        Iterator<PathArgument> arguments = legacy.getPathArguments().iterator();
+
+        while (arguments.hasNext()) {
+            currentOp = currentOp.getChild(arguments.next());
+        }
+        return currentOp;
     }
 
     public Map.Entry<InstanceIdentifier, NormalizedNode<?, ?>> toNormalized(
@@ -81,7 +93,7 @@ public class DataNormalizer {
         InstanceIdentifier normalizedPath = toNormalized(legacyPath);
 
         DataNormalizationOperation<?> currentOp = operation;
-        for (PathArgument arg : normalizedPath.getPath()) {
+        for (PathArgument arg : normalizedPath.getPathArguments()) {
             try {
                 currentOp = currentOp.getChild(arg);
             } catch (DataNormalizationException e) {
@@ -103,9 +115,7 @@ public class DataNormalizer {
 
             if (potentialOp.getIdentifier() instanceof AugmentationIdentifier) {
                 currentOp = potentialOp;
-                ArrayList<PathArgument> reworkedArgs = new ArrayList<>(normalizedPath.getPath());
-                reworkedArgs.add(potentialOp.getIdentifier());
-                normalizedPath = new InstanceIdentifier(reworkedArgs);
+                normalizedPath = normalizedPath.node(potentialOp.getIdentifier());
             }
         }
 
@@ -117,15 +127,14 @@ public class DataNormalizer {
 
     public InstanceIdentifier toLegacy(final InstanceIdentifier normalized) throws DataNormalizationException {
         ImmutableList.Builder<PathArgument> legacyArgs = ImmutableList.builder();
-        PathArgument previous = null;
         DataNormalizationOperation<?> currentOp = operation;
-        for (PathArgument normalizedArg : normalized.getPath()) {
+        for (PathArgument normalizedArg : normalized.getPathArguments()) {
             currentOp = currentOp.getChild(normalizedArg);
-            if(!currentOp.isMixin()) {
+            if (!currentOp.isMixin()) {
                 legacyArgs.add(normalizedArg);
             }
         }
-        return new InstanceIdentifier(legacyArgs.build());
+        return InstanceIdentifier.create(legacyArgs.build());
     }
 
     public CompositeNode toLegacy(final InstanceIdentifier normalizedPath, final NormalizedNode<?, ?> normalizedData) {
@@ -135,7 +144,7 @@ public class DataNormalizer {
             return toLegacyFromDataContainer((DataContainerNode<?>) normalizedData);
         } else if (normalizedData instanceof AnyXmlNode) {
             Node<?> value = ((AnyXmlNode) normalizedData).getValue();
-            return value instanceof CompositeNode ? (CompositeNode)value : null;
+            return value instanceof CompositeNode ? (CompositeNode) value : null;
         }
         return null;
     }
@@ -170,7 +179,7 @@ public class DataNormalizer {
         for (NormalizedNode<?, ?> child : node.getValue()) {
             if (child instanceof MixinNode && child instanceof NormalizedNodeContainer<?, ?, ?>) {
                 builder.addAll(toLegacyNodesFromMixin((NormalizedNodeContainer) child));
-            } else ifchild instanceof UnkeyedListNode) {
+            } else if (child instanceof UnkeyedListNode) {
                 builder.addAll(toLegacyNodesFromUnkeyedList((UnkeyedListNode) child));
             } else {
                 addToBuilder(builder, toLegacy(child));
index ddf089c68fd0e5000d0eec58d51b2ee841311bd0..dcb90a83ba1e3b15284b9a7d8d8bcabacf99cb3b 100644 (file)
@@ -14,10 +14,13 @@ import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
 import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 import com.google.common.collect.Sets;
+
 import java.util.AbstractMap;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.Comparator;
@@ -25,6 +28,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;
+
 import org.junit.Test;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
@@ -67,7 +71,7 @@ public class DataNormalizerTest {
         Class<?> nodeClass;
         Object nodeData; // List for a container, value Object for a leaf
 
-        NormalizedNodeData(PathArgument nodeID, Class<?> nodeClass, Object nodeData) {
+        NormalizedNodeData(final PathArgument nodeID, final Class<?> nodeClass, final Object nodeData) {
             this.nodeID = nodeID;
             this.nodeClass = nodeClass;
             this.nodeData = nodeData;
@@ -77,9 +81,9 @@ public class DataNormalizerTest {
     static class LegacyNodeData {
         QName nodeKey;
         Object nodeData; // List for a CompositeNode, value Object for a
-                         // SimpeNode
+        // SimpeNode
 
-        LegacyNodeData(QName nodeKey, Object nodeData) {
+        LegacyNodeData(final QName nodeKey, final Object nodeData) {
             this.nodeKey = nodeKey;
             this.nodeData = nodeData;
         }
@@ -143,13 +147,13 @@ public class DataNormalizerTest {
                 OUTER_LIST_QNAME, ID_QNAME, OUTER_LIST_ID }, OUTER_CHOICE_QNAME, TWO_QNAME);
     }
 
-    private void verifyNormalizedInstanceIdentifier(InstanceIdentifier actual, Object... expPath) {
+    private void verifyNormalizedInstanceIdentifier(final InstanceIdentifier actual, final Object... expPath) {
 
         assertNotNull("Actual InstanceIdentifier is null", actual);
-        assertEquals("InstanceIdentifier path length", expPath.length, actual.getPath().size());
+        assertEquals("InstanceIdentifier path length", expPath.length, Iterables.size(actual.getPathArguments()));
 
         for (int i = 0; i < expPath.length; i++) {
-            PathArgument actualArg = actual.getPath().get(i);
+            PathArgument actualArg = Iterables.get(actual.getPathArguments(), i);
             if (expPath[i] instanceof Object[]) { // NodeIdentifierWithPredicates
                 Object[] exp = (Object[]) expPath[i];
                 assertEquals("Actual path arg " + (i + 1) + " class", NodeIdentifierWithPredicates.class,
@@ -255,12 +259,12 @@ public class DataNormalizerTest {
                                 expectCompositeNode(INNER_LIST_QNAME, expectSimpleNode(NAME_QNAME, "inner-name1"),
                                         expectSimpleNode(VALUE_QNAME, "inner-value1")),
 
-                                expectCompositeNode(INNER_LIST_QNAME, expectSimpleNode(NAME_QNAME, "inner-name2"),
-                                        expectSimpleNode(VALUE_QNAME, "inner-value2"))),
-                        expectCompositeNode(OUTER_LIST_QNAME, expectSimpleNode(ID_QNAME, outerListID2),
-                                expectSimpleNode(ONE_QNAME, "one")),
-                        expectCompositeNode(UNKEYED_LIST_QNAME, expectSimpleNode(NAME_QNAME, "unkeyed1")),
-                        expectCompositeNode(UNKEYED_LIST_QNAME, expectSimpleNode(NAME_QNAME, "unkeyed2"))));
+                                        expectCompositeNode(INNER_LIST_QNAME, expectSimpleNode(NAME_QNAME, "inner-name2"),
+                                                expectSimpleNode(VALUE_QNAME, "inner-value2"))),
+                                                expectCompositeNode(OUTER_LIST_QNAME, expectSimpleNode(ID_QNAME, outerListID2),
+                                                        expectSimpleNode(ONE_QNAME, "one")),
+                                                        expectCompositeNode(UNKEYED_LIST_QNAME, expectSimpleNode(NAME_QNAME, "unkeyed1")),
+                                                        expectCompositeNode(UNKEYED_LIST_QNAME, expectSimpleNode(NAME_QNAME, "unkeyed2"))));
 
         // Conversion of Mixin type nodes is not supported.
 
@@ -365,12 +369,12 @@ public class DataNormalizerTest {
                                 expectSimpleNode(AUGMENTED_LEAF_QNAME, "augmented-value"))));
     }
 
-    private boolean isOrdered(QName nodeName) {
+    private boolean isOrdered(final QName nodeName) {
         return ORDERED_LEAF_LIST_QNAME.equals(nodeName) || INNER_LIST_QNAME.equals(nodeName);
     }
 
     @SuppressWarnings("unchecked")
-    private void verifyLegacyNode(Node<?> actual, LegacyNodeData expNodeData) {
+    private void verifyLegacyNode(final Node<?> actual, final LegacyNodeData expNodeData) {
 
         assertNotNull("Actual Node is null", actual);
         assertTrue("Expected CompositeNode instance", actual instanceof CompositeNode);
@@ -389,16 +393,45 @@ public class DataNormalizerTest {
 
         Collections.sort(unorderdChildData, new Comparator<LegacyNodeData>() {
             @Override
-            public int compare(LegacyNodeData arg1, LegacyNodeData arg2) {
-                String str1 = arg1.nodeKey.getLocalName();
-                if (!(arg1.nodeData instanceof List))
-                    str1 += arg1.nodeData; // add simple node value
-
-                String str2 = arg2.nodeKey.getLocalName();
-                if (!(arg2.nodeData instanceof List))
-                    str2 += arg2.nodeData; // add simple node value
-
-                return str1.compareTo(str2);
+            public int compare(final LegacyNodeData arg1, final LegacyNodeData arg2) {
+                if (!(arg1.nodeData instanceof List) && !(arg2.nodeData instanceof List)) {
+                    // if neither is a list, just compare them
+                    String str1 = arg1.nodeKey.getLocalName() + arg1.nodeData;
+                    String str2 = arg2.nodeKey.getLocalName() + arg2.nodeData;
+                    return str1.compareTo(str2);
+                } else if (arg1.nodeData instanceof List && arg2.nodeData instanceof List) {
+                    // if both are lists, first check their local name
+                    String str1 = arg1.nodeKey.getLocalName();
+                    String str2 = arg2.nodeKey.getLocalName();
+                    if (!str1.equals(str2)) {
+                        return str1.compareTo(str2);
+                    } else {
+                        // if local names are the same, then look at the list contents
+                        List<LegacyNodeData> l1 = (List<LegacyNodeData>) arg1.nodeData;
+                        List<LegacyNodeData> l2 = (List<LegacyNodeData>) arg2.nodeData;
+
+                        if (l1.size() != l2.size()) {
+                            // if the sizes are different, use that
+                            return l2.size() - l1.size();
+                        } else {
+                            // lastly sort and recursively check the list contents
+                            Collections.sort(l1, this);
+                            Collections.sort(l2, this);
+
+                            for (int i = 0 ; i < l1.size() ; i++) {
+                                int diff = this.compare(l1.get(i), l2.get(i));
+                                if (diff != 0) {
+                                    return diff;
+                                }
+                            }
+                            return 0;
+                        }
+                    }
+                } else if( arg1.nodeData instanceof List ) {
+                    return -1;
+                } else{
+                    return 1;
+                }
             }
         });
 
@@ -416,16 +449,50 @@ public class DataNormalizerTest {
 
         Collections.sort(unorderedChildNodes, new Comparator<Node<?>>() {
             @Override
-            public int compare(Node<?> n1, Node<?> n2) {
-                String str1 = n1.getKey().getLocalName();
-                if (n1 instanceof SimpleNode)
-                    str1 += ((SimpleNode<?>) n1).getValue();
-
-                String str2 = n2.getKey().getLocalName();
-                if (n2 instanceof SimpleNode)
-                    str2 += ((SimpleNode<?>) n2).getValue();
-
-                return str1.compareTo(str2);
+            public int compare(final Node<?> n1, final Node<?> n2) {
+                if (n1 instanceof SimpleNode && n2 instanceof SimpleNode) {
+                    // if they're SimpleNodes just compare their strings
+                    String str1 = n1.getKey().getLocalName() + ((SimpleNode<?>)n1).getValue();
+                    String str2 = n2.getKey().getLocalName() + ((SimpleNode<?>)n2).getValue();
+                    return str1.compareTo(str2);
+                } else if (n1 instanceof CompositeNode && n2 instanceof CompositeNode) {
+                    // if they're CompositeNodes, things are more interesting
+                    String str1 = n1.getKey().getLocalName();
+                    String str2 = n2.getKey().getLocalName();
+                    if (!str1.equals(str2)) {
+                        // if their local names differ, return that difference
+                        return str1.compareTo(str2);
+                    } else {
+                        // otherwise, we need to look at their contents
+                        ArrayList<Node<?>> l1 = new ArrayList<Node<?>>( ((CompositeNode)n1).getValue() );
+                        ArrayList<Node<?>> l2 = new ArrayList<Node<?>>( ((CompositeNode)n2).getValue() );
+
+                        if (l1.size() != l2.size()) {
+                            // if they have different numbers of things in them return that
+                            return l2.size() - l1.size();
+                        } else {
+                            // otherwise, compare the individual elements, first sort them
+                            Collections.sort(l1, this);
+                            Collections.sort(l2, this);
+
+                            // then compare them individually
+                            for(int i = 0 ; i < l2.size() ; i++) {
+                                int diff = this.compare(l1.get(i), l2.get(i));
+                                if(diff != 0){
+                                    return diff;
+                                }
+                            }
+                            return 0;
+                        }
+                    }
+                } else if (n1 instanceof CompositeNode && n2 instanceof SimpleNode) {
+                    return -1;
+                } else if (n2 instanceof CompositeNode && n1 instanceof SimpleNode) {
+                    return 1;
+                } else {
+                    assertTrue("Expected either SimpleNodes CompositeNodes", false);
+                    return 0;
+                }
             }
         });
 
@@ -437,7 +504,7 @@ public class DataNormalizerTest {
             assertEquals("Child node QName", expData.nodeKey, actualChild.getKey());
 
             if (expData.nodeData instanceof List) { // List represents a
-                                                    // composite node
+                // composite node
                 verifyLegacyNode(actualChild, expData);
             } else { // else a simple node
                 assertTrue("Expected SimpleNode instance", actualChild instanceof SimpleNode);
@@ -451,11 +518,11 @@ public class DataNormalizerTest {
         }
     }
 
-    private LegacyNodeData expectCompositeNode(QName key, LegacyNodeData... childData) {
+    private LegacyNodeData expectCompositeNode(final QName key, final LegacyNodeData... childData) {
         return new LegacyNodeData(key, Lists.newArrayList(childData));
     }
 
-    private LegacyNodeData expectSimpleNode(QName key, Object value) {
+    private LegacyNodeData expectSimpleNode(final QName key, final Object value) {
         return new LegacyNodeData(key, value);
     }
 
@@ -497,7 +564,7 @@ public class DataNormalizerTest {
         }
 
         Entry<InstanceIdentifier, NormalizedNode<?, ?>> normalizedNodeEntry = normalizer
-                .toNormalized(new AbstractMap.SimpleEntry<InstanceIdentifier, CompositeNode>(new InstanceIdentifier(
+                .toNormalized(new AbstractMap.SimpleEntry<InstanceIdentifier, CompositeNode>(InstanceIdentifier.create(
                         ImmutableList.<PathArgument> of(new NodeIdentifier(TEST_QNAME))), testBuilder.toInstance()));
 
         verifyNormalizedInstanceIdentifier(normalizedNodeEntry.getKey(), TEST_QNAME);
@@ -519,25 +586,25 @@ public class DataNormalizerTest {
                                                 expectMapEntryNode(INNER_LIST_QNAME, NAME_QNAME, "inner-name3",
                                                         expectLeafNode(NAME_QNAME, "inner-name3"),
                                                         expectLeafNode(VALUE_QNAME, "inner-value3")),
-                                                expectMapEntryNode(INNER_LIST_QNAME, NAME_QNAME, "inner-name2",
-                                                        expectLeafNode(NAME_QNAME, "inner-name2"),
-                                                        expectLeafNode(VALUE_QNAME, "inner-value2")),
-                                                expectMapEntryNode(INNER_LIST_QNAME, NAME_QNAME, "inner-name1",
-                                                        expectLeafNode(NAME_QNAME, "inner-name1"),
-                                                        expectLeafNode(VALUE_QNAME, "inner-value1")))),
-                                expectMapEntryNode(
-                                        OUTER_LIST_QNAME,
-                                        ID_QNAME,
-                                        20,
-                                        expectLeafNode(ID_QNAME, 20),
-                                        expectChoiceNode(OUTER_CHOICE_QNAME, expectLeafNode(TWO_QNAME, "two"),
-                                                expectLeafNode(THREE_QNAME, "three")))),
-                        expectUnkeyedListNode(
-                                UNKEYED_LIST_QNAME,
-                                expectUnkeyedListEntryNode(UNKEYED_LIST_QNAME,
-                                        expectLeafNode(NAME_QNAME, "unkeyed-name1")),
-                                expectUnkeyedListEntryNode(UNKEYED_LIST_QNAME,
-                                        expectLeafNode(NAME_QNAME, "unkeyed-name2")))));
+                                                        expectMapEntryNode(INNER_LIST_QNAME, NAME_QNAME, "inner-name2",
+                                                                expectLeafNode(NAME_QNAME, "inner-name2"),
+                                                                expectLeafNode(VALUE_QNAME, "inner-value2")),
+                                                                expectMapEntryNode(INNER_LIST_QNAME, NAME_QNAME, "inner-name1",
+                                                                        expectLeafNode(NAME_QNAME, "inner-name1"),
+                                                                        expectLeafNode(VALUE_QNAME, "inner-value1")))),
+                                                                        expectMapEntryNode(
+                                                                                OUTER_LIST_QNAME,
+                                                                                ID_QNAME,
+                                                                                20,
+                                                                                expectLeafNode(ID_QNAME, 20),
+                                                                                expectChoiceNode(OUTER_CHOICE_QNAME, expectLeafNode(TWO_QNAME, "two"),
+                                                                                        expectLeafNode(THREE_QNAME, "three")))),
+                                                                                        expectUnkeyedListNode(
+                                                                                                UNKEYED_LIST_QNAME,
+                                                                                                expectUnkeyedListEntryNode(UNKEYED_LIST_QNAME,
+                                                                                                        expectLeafNode(NAME_QNAME, "unkeyed-name1")),
+                                                                                                        expectUnkeyedListEntryNode(UNKEYED_LIST_QNAME,
+                                                                                                                expectLeafNode(NAME_QNAME, "unkeyed-name2")))));
     }
 
     @Test
@@ -561,7 +628,7 @@ public class DataNormalizerTest {
         testBuilder.add(anyXmlLegacy);
 
         Entry<InstanceIdentifier, NormalizedNode<?, ?>> normalizedNodeEntry = normalizer
-                .toNormalized(new AbstractMap.SimpleEntry<InstanceIdentifier, CompositeNode>(new InstanceIdentifier(
+                .toNormalized(new AbstractMap.SimpleEntry<InstanceIdentifier, CompositeNode>(InstanceIdentifier.create(
                         ImmutableList.<PathArgument> of(new NodeIdentifier(TEST_QNAME))), testBuilder.toInstance()));
 
         verifyNormalizedInstanceIdentifier(normalizedNodeEntry.getKey(), TEST_QNAME);
@@ -585,7 +652,7 @@ public class DataNormalizerTest {
         testBuilder.add(outerContBuilder.toInstance());
 
         Entry<InstanceIdentifier, NormalizedNode<?, ?>> normalizedNodeEntry = normalizer
-                .toNormalized(new AbstractMap.SimpleEntry<InstanceIdentifier, CompositeNode>(new InstanceIdentifier(
+                .toNormalized(new AbstractMap.SimpleEntry<InstanceIdentifier, CompositeNode>(InstanceIdentifier.create(
                         ImmutableList.<PathArgument> of(new NodeIdentifier(TEST_QNAME))), testBuilder.toInstance()));
 
         verifyNormalizedInstanceIdentifier(normalizedNodeEntry.getKey(), TEST_QNAME);
@@ -597,7 +664,7 @@ public class DataNormalizerTest {
                 expectContainerNode(TEST_QNAME, expectContainerNode(OUTER_CONTAINER_QNAME, expAugmentation)));
 
         normalizedNodeEntry = normalizer.toNormalized(new AbstractMap.SimpleEntry<InstanceIdentifier, CompositeNode>(
-                new InstanceIdentifier(Lists.newArrayList(new NodeIdentifier(TEST_QNAME), new NodeIdentifier(
+                InstanceIdentifier.create(Lists.newArrayList(new NodeIdentifier(TEST_QNAME), new NodeIdentifier(
                         OUTER_CONTAINER_QNAME))), outerContBuilder.toInstance()));
 
         verifyNormalizedInstanceIdentifier(normalizedNodeEntry.getKey(), TEST_QNAME, OUTER_CONTAINER_QNAME,
@@ -623,7 +690,7 @@ public class DataNormalizerTest {
         }
 
         Entry<InstanceIdentifier, NormalizedNode<?, ?>> normalizedNodeEntry = normalizer
-                .toNormalized(new AbstractMap.SimpleEntry<InstanceIdentifier, CompositeNode>(new InstanceIdentifier(
+                .toNormalized(new AbstractMap.SimpleEntry<InstanceIdentifier, CompositeNode>(InstanceIdentifier.create(
                         ImmutableList.<PathArgument> of(new NodeIdentifier(TEST_QNAME))), testBuilder.toInstance()));
 
         verifyNormalizedInstanceIdentifier(normalizedNodeEntry.getKey(), TEST_QNAME);
@@ -636,14 +703,14 @@ public class DataNormalizerTest {
                                 expectLeafSetEntryNode(UNORDERED_LEAF_LIST_QNAME, "unordered-value1"),
                                 expectLeafSetEntryNode(UNORDERED_LEAF_LIST_QNAME, "unordered-value2"),
                                 expectLeafSetEntryNode(UNORDERED_LEAF_LIST_QNAME, "unordered-value3")),
-                        expectOrderedLeafSetNode(ORDERED_LEAF_LIST_QNAME,
-                                expectLeafSetEntryNode(ORDERED_LEAF_LIST_QNAME, "ordered-value3"),
-                                expectLeafSetEntryNode(ORDERED_LEAF_LIST_QNAME, "ordered-value2"),
-                                expectLeafSetEntryNode(ORDERED_LEAF_LIST_QNAME, "ordered-value1"))));
+                                expectOrderedLeafSetNode(ORDERED_LEAF_LIST_QNAME,
+                                        expectLeafSetEntryNode(ORDERED_LEAF_LIST_QNAME, "ordered-value3"),
+                                        expectLeafSetEntryNode(ORDERED_LEAF_LIST_QNAME, "ordered-value2"),
+                                        expectLeafSetEntryNode(ORDERED_LEAF_LIST_QNAME, "ordered-value1"))));
     }
 
     @SuppressWarnings("unchecked")
-    private void verifyNormalizedNode(NormalizedNode<?, ?> actual, NormalizedNodeData expNodeData) {
+    private void verifyNormalizedNode(final NormalizedNode<?, ?> actual, final NormalizedNodeData expNodeData) {
 
         Class<?> expNodeClass = expNodeData.nodeClass;
         PathArgument expNodeID = expNodeData.nodeID;
@@ -679,18 +746,18 @@ public class DataNormalizerTest {
                 NormalizedNodeData expChildData = expNodeClass.equals(UnkeyedListNode.class) ? expChildDataList
                         .remove(0) : expChildDataMap.remove(actualChild.getIdentifier());
 
-                assertNotNull(
-                        "Unexpected child node " + actualChild.getClass() + " with identifier "
-                                + actualChild.getIdentifier() + " for parent node " + actual.getClass()
-                                + " with identifier " + actual.getIdentifier(), expChildData);
+                        assertNotNull(
+                                "Unexpected child node " + actualChild.getClass() + " with identifier "
+                                        + actualChild.getIdentifier() + " for parent node " + actual.getClass()
+                                        + " with identifier " + actual.getIdentifier(), expChildData);
 
-                if (orderingMap != null) {
-                    assertEquals("Order index for child node " + actualChild.getIdentifier(),
-                            orderingMap.get(actualChild.getIdentifier()), Integer.valueOf(i));
-                }
+                        if (orderingMap != null) {
+                            assertEquals("Order index for child node " + actualChild.getIdentifier(),
+                                    orderingMap.get(actualChild.getIdentifier()), Integer.valueOf(i));
+                        }
 
-                verifyNormalizedNode(actualChild, expChildData);
-                i++;
+                        verifyNormalizedNode(actualChild, expChildData);
+                        i++;
             }
 
             if (expNodeClass.equals(UnkeyedListNode.class)) {
@@ -707,62 +774,62 @@ public class DataNormalizerTest {
         }
     }
 
-    private NormalizedNodeData expectOrderedLeafSetNode(QName nodeName, NormalizedNodeData... childData) {
+    private NormalizedNodeData expectOrderedLeafSetNode(final QName nodeName, final NormalizedNodeData... childData) {
         return new NormalizedNodeData(new NodeIdentifier(nodeName), OrderedLeafSetNode.class,
                 Lists.newArrayList(childData));
     }
 
-    private NormalizedNodeData expectLeafSetNode(QName nodeName, NormalizedNodeData... childData) {
+    private NormalizedNodeData expectLeafSetNode(final QName nodeName, final NormalizedNodeData... childData) {
         return new NormalizedNodeData(new NodeIdentifier(nodeName), LeafSetNode.class, Lists.newArrayList(childData));
     }
 
-    private NormalizedNodeData expectLeafSetEntryNode(QName nodeName, Object value) {
+    private NormalizedNodeData expectLeafSetEntryNode(final QName nodeName, final Object value) {
         return new NormalizedNodeData(new NodeWithValue(nodeName, value), LeafSetEntryNode.class, value);
     }
 
-    private NormalizedNodeData expectUnkeyedListNode(QName nodeName, NormalizedNodeData... childData) {
+    private NormalizedNodeData expectUnkeyedListNode(final QName nodeName, final NormalizedNodeData... childData) {
         return new NormalizedNodeData(new NodeIdentifier(nodeName), UnkeyedListNode.class,
                 Lists.newArrayList(childData));
     }
 
-    private NormalizedNodeData expectUnkeyedListEntryNode(QName nodeName, NormalizedNodeData... childData) {
+    private NormalizedNodeData expectUnkeyedListEntryNode(final QName nodeName, final NormalizedNodeData... childData) {
         return new NormalizedNodeData(new NodeIdentifier(nodeName), UnkeyedListEntryNode.class,
                 Lists.newArrayList(childData));
     }
 
-    private NormalizedNodeData expectAugmentation(QName augmentedNodeName, NormalizedNodeData... childData) {
+    private NormalizedNodeData expectAugmentation(final QName augmentedNodeName, final NormalizedNodeData... childData) {
         return new NormalizedNodeData(new AugmentationIdentifier(Sets.newHashSet(augmentedNodeName)),
                 AugmentationNode.class, Lists.newArrayList(childData));
     }
 
-    private NormalizedNodeData expectAnyXmlNode(QName nodeName, Object value) {
+    private NormalizedNodeData expectAnyXmlNode(final QName nodeName, final Object value) {
         return new NormalizedNodeData(new NodeIdentifier(nodeName), AnyXmlNode.class, value);
     }
 
-    private NormalizedNodeData expectContainerNode(QName nodeName, NormalizedNodeData... childData) {
+    private NormalizedNodeData expectContainerNode(final QName nodeName, final NormalizedNodeData... childData) {
         return new NormalizedNodeData(new NodeIdentifier(nodeName), ContainerNode.class, Lists.newArrayList(childData));
     }
 
-    private NormalizedNodeData expectChoiceNode(QName nodeName, NormalizedNodeData... childData) {
+    private NormalizedNodeData expectChoiceNode(final QName nodeName, final NormalizedNodeData... childData) {
         return new NormalizedNodeData(new NodeIdentifier(nodeName), ChoiceNode.class, Lists.newArrayList(childData));
     }
 
-    private NormalizedNodeData expectLeafNode(QName nodeName, Object value) {
+    private NormalizedNodeData expectLeafNode(final QName nodeName, final Object value) {
         return new NormalizedNodeData(new NodeIdentifier(nodeName), LeafNode.class, value);
 
     }
 
-    private NormalizedNodeData expectMapEntryNode(QName nodeName, QName key, Object value,
-            NormalizedNodeData... childData) {
+    private NormalizedNodeData expectMapEntryNode(final QName nodeName, final QName key, final Object value,
+            final NormalizedNodeData... childData) {
         return new NormalizedNodeData(new NodeIdentifierWithPredicates(nodeName, key, value), MapEntryNode.class,
                 Lists.newArrayList(childData));
     }
 
-    private NormalizedNodeData expectMapNode(QName key, NormalizedNodeData... childData) {
+    private NormalizedNodeData expectMapNode(final QName key, final NormalizedNodeData... childData) {
         return new NormalizedNodeData(new NodeIdentifier(key), MapNode.class, Lists.newArrayList(childData));
     }
 
-    private NormalizedNodeData expectOrderedMapNode(QName key, NormalizedNodeData... childData) {
+    private NormalizedNodeData expectOrderedMapNode(final QName key, final NormalizedNodeData... childData) {
         return new NormalizedNodeData(new NodeIdentifier(key), OrderedMapNode.class, Lists.newArrayList(childData));
     }
 }
index 1af7ccc79ad2de55b1f26a3b53b11b6b44bfadea..9aacf1e0a8b8123d0c75360b7e9c9c88a73cb827 100644 (file)
@@ -7,13 +7,11 @@
  */
 package org.opendaylight.controller.sal.common.util;
 
-import java.util.Collections;
-
 import org.opendaylight.controller.md.sal.common.api.data.DataModification;
 import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler.DataCommitTransaction;
 import org.opendaylight.yangtools.concepts.Path;
-import org.opendaylight.yangtools.yang.common.RpcError;
 import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 
 public class CommitHandlerTransactions {
 
@@ -26,11 +24,11 @@ public class CommitHandlerTransactions {
         }
         @Override
         public RpcResult<Void> rollback() throws IllegalStateException {
-            return Rpcs.<Void>getRpcResult(true, null, Collections.<RpcError>emptyList());
+            return RpcResultBuilder.<Void>success().build();
         }
         @Override
         public RpcResult<Void> finish() throws IllegalStateException {
-            return Rpcs.<Void>getRpcResult(true, null, Collections.<RpcError>emptyList());
+            return RpcResultBuilder.<Void>success().build();
         }
 
         @Override
index 4d41249b4d5600e7932d9b56dd34bbaaf80f8854..cacb167f6f54f962c4f7bb49b39452ed140186e1 100644 (file)
@@ -12,9 +12,9 @@ import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
 
 /**
- * @author mirehak
- *
+ * @deprecated Use {@link org.opendaylight.yangtools.yang.common.RpcResultBuilder}
  */
+@Deprecated
 public class RpcErrors {
 
     /**
index f30394187125153004e9b5c3a1b4d4cb2cc74886..69458b6a6d6e3492ed484c958bd3380e049bff0f 100644 (file)
@@ -16,6 +16,10 @@ import org.opendaylight.yangtools.yang.common.RpcResult;
 
 import com.google.common.collect.ImmutableList;
 
+/**
+ * @deprecated Use {@link org.opendaylight.yangtools.yang.common.RpcResultBuilder}
+ */
+@Deprecated
 public class Rpcs {
 
     public static <T> RpcResult<T> getRpcResult(boolean successful) {
diff --git a/opendaylight/md-sal/sal-compability/src/main/java/org/opendaylight/controller/sal/compability/ToSalPropertyClassUtils.java b/opendaylight/md-sal/sal-compability/src/main/java/org/opendaylight/controller/sal/compability/ToSalPropertyClassUtils.java
deleted file mode 100644 (file)
index 3894fbe..0000000
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.compability;
-
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.PortFeatures;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector;
-
-public class ToSalPropertyClassUtils {
-    public static Bandwidth salAdvertisedBandwidthFrom(NodeConnector nodeConnector) {
-        FlowCapableNodeConnector flowCapNodeConn = nodeConnector.getAugmentation(FlowCapableNodeConnector.class);
-        PortFeatures portFeatures = flowCapNodeConn.getAdvertisedFeatures();
-        return new AdvertisedBandwidth(resolveBandwidth(portFeatures));
-    }
-
-    public static Bandwidth salPeerBandwidthFrom(NodeConnector nodeConnector) {
-        FlowCapableNodeConnector flowCapNodeConn = nodeConnector.getAugmentation(FlowCapableNodeConnector.class);
-        PortFeatures portFeatures = flowCapNodeConn.getPeerFeatures();
-        return new PeerBandwidth(resolveBandwidth(portFeatures));
-    }
-
-    public static Bandwidth salSupportedBandwidthFrom(NodeConnector nodeConnector) {
-        FlowCapableNodeConnector flowCapNodeConn = nodeConnector.getAugmentation(FlowCapableNodeConnector.class);
-        PortFeatures portFeatures = flowCapNodeConn.getSupported();
-        return new SupportedBandwidth(resolveBandwidth(portFeatures));
-    }
-
-    public static MacAddress salMacAddressFrom(NodeConnector nodeConnector) {
-        FlowCapableNodeConnector flowCapNodeConn = nodeConnector.getAugmentation(FlowCapableNodeConnector.class);
-        String hwAddress = flowCapNodeConn.getHardwareAddress().getValue();
-        return new MacAddress(bytesFrom(hwAddress));
-    }
-
-
-    public static Name salNameFrom(NodeConnector nodeConnector) {
-        FlowCapableNodeConnector flowCapNodeConn = nodeConnector.getAugmentation(FlowCapableNodeConnector.class);
-        return new Name(flowCapNodeConn.getName());
-    }
-
-
-
-    private static byte[] bytesFrom(String hwAddress) {
-        String[] mac = hwAddress.split(":");
-        byte[] macAddress = new byte[6]; // mac.length == 6 bytes
-        for (int i = 0; i < mac.length; i++) {
-            macAddress[i] = Integer.decode("0x" + mac[i]).byteValue();
-        }
-        return macAddress;
-    }
-
-    private static long resolveBandwidth(PortFeatures portFeatures) {
-        if (portFeatures.is_1tbFd()) {
-            return Bandwidth.BW1Tbps;
-        } else if (portFeatures.is_100gbFd()) {
-            return Bandwidth.BW100Gbps;
-        } else if (portFeatures.is_40gbFd()) {
-            return Bandwidth.BW40Gbps;
-        } else if (portFeatures.is_10gbFd()) {
-            return Bandwidth.BW10Gbps;
-        } else if (portFeatures.is_1gbHd() || portFeatures.is_1gbFd()) {
-            return Bandwidth.BW1Gbps;
-        } else if (portFeatures.is_100mbHd() || portFeatures.is_100mbFd()) {
-            return Bandwidth.BW100Mbps;
-        } else if (portFeatures.is_10mbHd() || portFeatures.is_10mbFd()) {
-            return Bandwidth.BW10Mbps;
-        } else {
-            return Bandwidth.BWUNK;
-        }
-    }
-
-}
index ea686d966ffa63b60e1cf3cb839db2f2eb034f1e..5152363ab2640e1dc1a612612bdcb0129e64692a 100644 (file)
       <artifactId>sal-binding-config</artifactId>
     </dependency>
 
-    <!--
-      Adding a temporary dependency on the sal-broker-impl so that we can use InMemoryDOMDataStore
+      <dependency>
+          <groupId>org.opendaylight.yangtools</groupId>
+          <artifactId>yang-data-api</artifactId>
+      </dependency>
+
+      <dependency>
+      <groupId>org.opendaylight.yangtools</groupId>
+      <artifactId>yang-data-impl</artifactId>
+      </dependency>
 
-      InMemoryDOMDataStore needs to be moved into its own module and be wired up using config subsystem before
-      this bundle can use it
-    -->
     <dependency>
       <groupId>org.opendaylight.controller</groupId>
-      <artifactId>sal-broker-impl</artifactId>
+      <artifactId>sal-inmemory-datastore</artifactId>
+      <version>1.1-SNAPSHOT</version>
     </dependency>
 
     <dependency>
       <version>${slf4j.version}</version>
       <scope>test</scope>
     </dependency>
+
   </dependencies>
 
   <build>
             <Bundle-Name>${project.groupId}.${project.artifactId}</Bundle-Name>
             <Export-package></Export-package>
             <Private-Package></Private-Package>
+            <Import-Package>!*snappy;!org.jboss.*;*</Import-Package>
+            <Embed-Dependency>
+                !sal*;
+                !*config-api*;
+                !*testkit*;
+                akka*;
+                *leveldb*;
+                *config*;
+                *hawt*;
+                *protobuf*;
+                *netty*;
+                *uncommons*;
+                *scala*;
+            </Embed-Dependency>
+            <Embed-Transitive>true</Embed-Transitive>
           </instructions>
         </configuration>
       </plugin>
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/AbstractUntypedActor.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/AbstractUntypedActor.java
new file mode 100644 (file)
index 0000000..0f10258
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.cluster.datastore;
+
+import akka.actor.UntypedActor;
+import akka.event.Logging;
+import akka.event.LoggingAdapter;
+import org.opendaylight.controller.cluster.datastore.messages.Monitor;
+
+public abstract class AbstractUntypedActor extends UntypedActor {
+    protected final LoggingAdapter LOG =
+        Logging.getLogger(getContext().system(), this);
+
+
+    public AbstractUntypedActor(){
+        LOG.debug("Actor created {}", getSelf());
+        getContext().
+            system().
+            actorSelection("user/termination-monitor").
+            tell(new Monitor(getSelf()), getSelf());
+    }
+
+    @Override public void onReceive(Object message) throws Exception {
+        LOG.debug("Received message {}", message);
+        handleReceive(message);
+        LOG.debug("Done handling message {}", message);
+    }
+
+    protected abstract void handleReceive(Object message) throws Exception;
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ActorSystemFactory.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ActorSystemFactory.java
new file mode 100644 (file)
index 0000000..baf04fe
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.cluster.datastore;
+
+import akka.actor.ActorSystem;
+import akka.actor.Props;
+import com.google.common.base.Function;
+import com.typesafe.config.ConfigFactory;
+
+import javax.annotation.Nullable;
+
+public class ActorSystemFactory {
+    private static final ActorSystem actorSystem = (new Function<Void, ActorSystem>(){
+
+        @Nullable @Override public ActorSystem apply(@Nullable Void aVoid) {
+                ActorSystem system =
+                    ActorSystem.create("opendaylight-cluster", ConfigFactory
+                        .load().getConfig("ODLCluster"));
+                system.actorOf(Props.create(TerminationMonitor.class), "termination-monitor");
+                return system;
+        }
+    }).apply(null);
+
+    public static final ActorSystem getInstance(){
+        return actorSystem;
+    }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListener.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListener.java
new file mode 100644 (file)
index 0000000..fd4f9f7
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.cluster.datastore;
+
+import akka.actor.Props;
+import akka.japi.Creator;
+import org.opendaylight.controller.cluster.datastore.messages.DataChanged;
+import org.opendaylight.controller.cluster.datastore.messages.DataChangedReply;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+public class DataChangeListener extends AbstractUntypedActor {
+    private final AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>> listener;
+
+    public DataChangeListener(
+        AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>> listener) {
+        this.listener = listener;
+    }
+
+    @Override public void handleReceive(Object message) throws Exception {
+        if(message instanceof DataChanged){
+            DataChanged reply = (DataChanged) message;
+            AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>>
+                change = reply.getChange();
+            this.listener.onDataChanged(change);
+
+            if(getSender() != null){
+                getSender().tell(new DataChangedReply(), getSelf());
+            }
+
+        }
+    }
+
+    public static Props props(final AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>> listener) {
+        return Props.create(new Creator<DataChangeListener>() {
+            @Override
+            public DataChangeListener create() throws Exception {
+                return new DataChangeListener(listener);
+            }
+
+        });
+
+    }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerProxy.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerProxy.java
new file mode 100644 (file)
index 0000000..8423b98
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.cluster.datastore;
+
+import akka.actor.ActorSelection;
+import org.opendaylight.controller.cluster.datastore.messages.DataChanged;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+/**
+ * DataChangeListenerProxy represents a single remote DataChangeListener
+ */
+public class DataChangeListenerProxy implements AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>{
+    private final ActorSelection dataChangeListenerActor;
+
+    public DataChangeListenerProxy(ActorSelection dataChangeListenerActor) {
+        this.dataChangeListenerActor = dataChangeListenerActor;
+    }
+
+    @Override public void onDataChanged(
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change) {
+        dataChangeListenerActor.tell(new DataChanged(change), null);
+    }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistration.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistration.java
new file mode 100644 (file)
index 0000000..dca9735
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.cluster.datastore;
+
+import akka.actor.PoisonPill;
+import akka.actor.Props;
+import akka.japi.Creator;
+import org.opendaylight.controller.cluster.datastore.messages.CloseDataChangeListenerRegistration;
+import org.opendaylight.controller.cluster.datastore.messages.CloseDataChangeListenerRegistrationReply;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+public class DataChangeListenerRegistration extends AbstractUntypedActor {
+
+    private final org.opendaylight.yangtools.concepts.ListenerRegistration<AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>>
+        registration;
+
+    public DataChangeListenerRegistration(
+        org.opendaylight.yangtools.concepts.ListenerRegistration<AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>> registration) {
+        this.registration = registration;
+    }
+
+    @Override
+    public void handleReceive(Object message) throws Exception {
+        if (message instanceof CloseDataChangeListenerRegistration) {
+            closeListenerRegistration(
+                (CloseDataChangeListenerRegistration) message);
+        }
+    }
+
+    public static Props props(
+        final org.opendaylight.yangtools.concepts.ListenerRegistration<AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>> registration) {
+        return Props.create(new Creator<DataChangeListenerRegistration>() {
+
+            @Override
+            public DataChangeListenerRegistration create() throws Exception {
+                return new DataChangeListenerRegistration(registration);
+            }
+        });
+    }
+
+    private void closeListenerRegistration(
+        CloseDataChangeListenerRegistration message) {
+        registration.close();
+        getSender()
+            .tell(new CloseDataChangeListenerRegistrationReply(), getSelf());
+        getSelf().tell(PoisonPill.getInstance(), getSelf());
+    }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistrationProxy.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistrationProxy.java
new file mode 100644 (file)
index 0000000..83737cf
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.cluster.datastore;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSelection;
+import akka.actor.PoisonPill;
+import org.opendaylight.controller.cluster.datastore.messages.CloseDataChangeListenerRegistration;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
+import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+/**
+ * ListenerRegistrationProxy acts as a proxy for a ListenerRegistration that was done on a remote shard
+ * <p>
+ * Registering a DataChangeListener on the Data Store creates a new instance of the ListenerRegistrationProxy
+ * The ListenerRegistrationProxy talks to a remote ListenerRegistration actor.
+ * </p>
+ */
+public class DataChangeListenerRegistrationProxy implements ListenerRegistration {
+    private final ActorSelection listenerRegistrationActor;
+    private final AsyncDataChangeListener listener;
+    private final ActorRef dataChangeListenerActor;
+
+    public <L extends AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>>
+    DataChangeListenerRegistrationProxy(
+        ActorSelection listenerRegistrationActor,
+        L listener, ActorRef dataChangeListenerActor) {
+        this.listenerRegistrationActor = listenerRegistrationActor;
+        this.listener = listener;
+        this.dataChangeListenerActor = dataChangeListenerActor;
+    }
+
+    @Override
+    public Object getInstance() {
+        return listener;
+    }
+
+    @Override
+    public void close() {
+        listenerRegistrationActor.tell(new CloseDataChangeListenerRegistration(), null);
+        dataChangeListenerActor.tell(PoisonPill.getInstance(), null);
+    }
+}
index 8d5b0c2f4a65f49d188786ad9f5927f29939166e..4401104a85971c77c1b9a9333c727348f5398656 100644 (file)
@@ -8,6 +8,12 @@
 
 package org.opendaylight.controller.cluster.datastore;
 
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
+import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
+import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
+import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
@@ -18,34 +24,98 @@ import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
 
 /**
  *
  */
-public class DistributedDataStore implements DOMStore {
+public class DistributedDataStore implements DOMStore, SchemaContextListener, AutoCloseable {
+
+    private static final Logger
+        LOG = LoggerFactory.getLogger(DistributedDataStore.class);
+
+
+    private final String type;
+    private final ActorContext actorContext;
+
+
+    /**
+     * Executor used to run FutureTask's
+     *
+     * This is typically used when we need to make a request to an actor and
+     * wait for it's response and the consumer needs to be provided a Future.
+     *
+     * FIXME : Make the thread pool configurable
+     */
+    private final ExecutorService executor =
+        Executors.newFixedThreadPool(10);
+
+    public DistributedDataStore(ActorSystem actorSystem, String type) {
+        this(new ActorContext(actorSystem, actorSystem.actorOf(ShardManager.props(type), "shardmanager-" + type)), type);
+    }
+
+    public DistributedDataStore(ActorContext actorContext, String type) {
+        this.type = type;
+        this.actorContext = actorContext;
+    }
+
 
     @Override
-    public <L extends AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>> ListenerRegistration<L> registerChangeListener(InstanceIdentifier path, L listener, AsyncDataBroker.DataChangeScope scope) {
-        return new ListenerRegistrationProxy();
+    public <L extends AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>> ListenerRegistration<L> registerChangeListener(
+        InstanceIdentifier path, L listener,
+        AsyncDataBroker.DataChangeScope scope) {
+
+        ActorRef dataChangeListenerActor = actorContext.getActorSystem().actorOf(
+            DataChangeListener.props(listener));
+
+        Object result = actorContext.executeShardOperation(Shard.DEFAULT_NAME,
+            new RegisterChangeListener(path, dataChangeListenerActor.path(),
+                AsyncDataBroker.DataChangeScope.BASE),
+            ActorContext.ASK_DURATION
+        );
+
+        RegisterChangeListenerReply reply = (RegisterChangeListenerReply) result;
+        return new DataChangeListenerRegistrationProxy(actorContext.actorSelection(reply.getListenerRegistrationPath()), listener, dataChangeListenerActor);
     }
 
+
+
     @Override
     public DOMStoreTransactionChain createTransactionChain() {
-        return new TransactionChainProxy();
+        return new TransactionChainProxy(actorContext, executor);
     }
 
     @Override
     public DOMStoreReadTransaction newReadOnlyTransaction() {
-        return new TransactionProxy();
+        return new TransactionProxy(actorContext, TransactionProxy.TransactionType.READ_ONLY,
+            executor);
     }
 
     @Override
     public DOMStoreWriteTransaction newWriteOnlyTransaction() {
-        return new TransactionProxy();
+        return new TransactionProxy(actorContext, TransactionProxy.TransactionType.WRITE_ONLY,
+            executor);
     }
 
     @Override
     public DOMStoreReadWriteTransaction newReadWriteTransaction() {
-        return new TransactionProxy();
+        return new TransactionProxy(actorContext, TransactionProxy.TransactionType.READ_WRITE,
+            executor);
+    }
+
+    @Override public void onGlobalContextUpdated(SchemaContext schemaContext) {
+        actorContext.getShardManager().tell(
+            new UpdateSchemaContext(schemaContext), null);
+    }
+
+    @Override public void close() throws Exception {
+        actorContext.shutdown();
+
     }
 }
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreFactory.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreFactory.java
new file mode 100644 (file)
index 0000000..f19cb92
--- /dev/null
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.cluster.datastore;
+
+import org.opendaylight.controller.sal.core.api.model.SchemaService;
+
+public class DistributedDataStoreFactory {
+    public static DistributedDataStore createInstance(String name, SchemaService schemaService){
+        final DistributedDataStore dataStore =
+            new DistributedDataStore(ActorSystemFactory.getInstance(), name);
+        schemaService
+            .registerSchemaServiceListener(dataStore);
+        return dataStore;
+
+    }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ListenerRegistration.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ListenerRegistration.java
deleted file mode 100644 (file)
index fda429f..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.cluster.datastore;
-
-import akka.actor.Props;
-import akka.actor.UntypedActor;
-import akka.japi.Creator;
-import org.opendaylight.controller.cluster.datastore.messages.CloseListenerRegistration;
-import org.opendaylight.controller.cluster.datastore.messages.CloseListenerRegistrationReply;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
-import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-public class ListenerRegistration extends UntypedActor{
-
-  private final org.opendaylight.yangtools.concepts.ListenerRegistration<AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>> registration;
-
-  public ListenerRegistration(org.opendaylight.yangtools.concepts.ListenerRegistration<AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>> registration) {
-    this.registration = registration;
-  }
-
-  @Override
-  public void onReceive(Object message) throws Exception {
-    if(message instanceof CloseListenerRegistration){
-      closeListenerRegistration((CloseListenerRegistration) message);
-    }
-  }
-
-  public static Props props(final org.opendaylight.yangtools.concepts.ListenerRegistration<AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>> registration){
-    return Props.create(new Creator<ListenerRegistration>(){
-
-      @Override
-      public ListenerRegistration create() throws Exception {
-        return new ListenerRegistration(registration);
-      }
-    });
-  }
-
-  private void closeListenerRegistration(CloseListenerRegistration message){
-    registration.close();
-    getSender().tell(new CloseListenerRegistrationReply(), getSelf());
-  }
-}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ListenerRegistrationProxy.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ListenerRegistrationProxy.java
deleted file mode 100644 (file)
index c2fc8c0..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.cluster.datastore;
-
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-
-/**
- * ListenerRegistrationProxy acts as a proxy for a ListenerRegistration that was done on a remote shard
- *
- * Registering a DataChangeListener on the Data Store creates a new instance of the ListenerRegistrationProxy
- * The ListenerRegistrationProxy talks to a remote ListenerRegistration actor.
- */
-public class ListenerRegistrationProxy implements ListenerRegistration {
-    @Override
-    public Object getInstance() {
-        throw new UnsupportedOperationException("getInstance");
-    }
-
-    @Override
-    public void close() {
-        throw new UnsupportedOperationException("close");
-    }
-}
index 8365328669587b5e083c8e53ca819eb63857cd40..3425608d235ddce1555dac19f6bc3e985b65f7f9 100644 (file)
 package org.opendaylight.controller.cluster.datastore;
 
 import akka.actor.ActorRef;
+import akka.actor.ActorSelection;
+import akka.actor.Props;
 import akka.event.Logging;
 import akka.event.LoggingAdapter;
+import akka.japi.Creator;
+import akka.persistence.Persistent;
 import akka.persistence.UntypedProcessor;
+import com.google.common.util.concurrent.ListenableFuture;
 import com.google.common.util.concurrent.ListeningExecutorService;
 import com.google.common.util.concurrent.MoreExecutors;
+import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionChain;
 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionChainReply;
+import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.ForwardedCommitTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.NonPersistent;
 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
+import org.opendaylight.controller.cluster.datastore.modification.Modification;
 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.ExecutionException;
 import java.util.concurrent.Executors;
 
 /**
- * A Shard represents a portion of the logical data tree
- * <p/>
+ * A Shard represents a portion of the logical data tree <br/>
+ * <p>
  * Our Shard uses InMemoryDataStore as it's internal representation and delegates all requests it
- *
+ * </p>
  */
 public class Shard extends UntypedProcessor {
 
-  ListeningExecutorService storeExecutor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(2));
+    public static final String DEFAULT_NAME = "default";
+
+    private final ListeningExecutorService storeExecutor =
+        MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(2));
+
+    private final InMemoryDOMDataStore store;
+
+    private final Map<Modification, DOMStoreThreePhaseCommitCohort>
+        modificationToCohort = new HashMap<>();
+
+    private final LoggingAdapter log =
+        Logging.getLogger(getContext().system(), this);
+
+    // By default persistent will be true and can be turned off using the system
+    // property persistent
+    private final boolean persistent;
+
+    private Shard(String name) {
+
+        String setting = System.getProperty("shard.persistent");
+        this.persistent = !"false".equals(setting);
+
+        log.info("Creating shard : {} persistent : {}", name , persistent);
+
+        store = new InMemoryDOMDataStore(name, storeExecutor);
+    }
+
+    public static Props props(final String name) {
+        return Props.create(new Creator<Shard>() {
+
+            @Override
+            public Shard create() throws Exception {
+                return new Shard(name);
+            }
+
+        });
+    }
+
+
+    @Override
+    public void onReceive(Object message) throws Exception {
+        log.debug("Received message {}", message);
+
+        if (message instanceof CreateTransactionChain) {
+            createTransactionChain();
+        } else if (message instanceof RegisterChangeListener) {
+            registerChangeListener((RegisterChangeListener) message);
+        } else if (message instanceof UpdateSchemaContext) {
+            updateSchemaContext((UpdateSchemaContext) message);
+        } else if (message instanceof ForwardedCommitTransaction) {
+            handleForwardedCommit((ForwardedCommitTransaction) message);
+        } else if (message instanceof Persistent) {
+            commit((Modification) ((Persistent) message).payload());
+        } else if (message instanceof CreateTransaction) {
+            createTransaction((CreateTransaction) message);
+        } else if(message instanceof NonPersistent){
+            commit((Modification) ((NonPersistent) message).payload());
+        }
+    }
+
+    private void createTransaction(CreateTransaction createTransaction) {
+        DOMStoreReadWriteTransaction transaction =
+            store.newReadWriteTransaction();
+        ActorRef transactionActor = getContext().actorOf(
+            ShardTransaction.props(transaction, getSelf()), "shard-" + createTransaction.getTransactionId());
+        getSender()
+            .tell(new CreateTransactionReply(transactionActor.path(), createTransaction.getTransactionId()),
+                getSelf());
+    }
 
-  private final InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER", storeExecutor);
+    private void commit(Modification modification) {
+        DOMStoreThreePhaseCommitCohort cohort =
+            modificationToCohort.remove(modification);
+        if (cohort == null) {
+            log.error(
+                "Could not find cohort for modification : " + modification);
+            return;
+        }
+        final ListenableFuture<Void> future = cohort.commit();
+        final ActorRef sender = getSender();
+        final ActorRef self = getSelf();
+        future.addListener(new Runnable() {
+            @Override
+            public void run() {
+                try {
+                    future.get();
+                    sender.tell(new CommitTransactionReply(), self);
+                } catch (InterruptedException | ExecutionException e) {
+                    // FIXME : Handle this properly
+                    log.error(e, "An exception happened when committing");
+                }
+            }
+        }, getContext().dispatcher());
+    }
 
-  LoggingAdapter log = Logging.getLogger(getContext().system(), this);
+    private void handleForwardedCommit(ForwardedCommitTransaction message) {
+        modificationToCohort
+            .put(message.getModification(), message.getCohort());
+        if(persistent) {
+            getSelf().forward(Persistent.create(message.getModification()),
+                getContext());
+        } else {
+            getSelf().forward(NonPersistent.create(message.getModification()),
+                getContext());
+        }
+    }
+
+    private void updateSchemaContext(UpdateSchemaContext message) {
+        store.onGlobalContextUpdated(message.getSchemaContext());
+    }
+
+    private void registerChangeListener(
+        RegisterChangeListener registerChangeListener) {
+
+        ActorSelection dataChangeListenerPath = getContext()
+            .system().actorSelection(registerChangeListener.getDataChangeListenerPath());
+
+        AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>
+            listener = new DataChangeListenerProxy(dataChangeListenerPath);
+
+        org.opendaylight.yangtools.concepts.ListenerRegistration<AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>>
+            registration =
+            store.registerChangeListener(registerChangeListener.getPath(),
+                listener, registerChangeListener.getScope());
+        ActorRef listenerRegistration =
+            getContext().actorOf(
+                DataChangeListenerRegistration.props(registration));
+        getSender()
+            .tell(new RegisterChangeListenerReply(listenerRegistration.path()),
+                getSelf());
+    }
 
-  @Override
-  public void onReceive(Object message) throws Exception {
-    if (message instanceof CreateTransactionChain) {
-      createTransactionChain();
-    } else if(message instanceof RegisterChangeListener){
-      registerChangeListener((RegisterChangeListener) message);
-    } else if(message instanceof UpdateSchemaContext){
-      updateSchemaContext((UpdateSchemaContext) message);
+    private void createTransactionChain() {
+        DOMStoreTransactionChain chain = store.createTransactionChain();
+        ActorRef transactionChain =
+            getContext().actorOf(ShardTransactionChain.props(chain));
+        getSender()
+            .tell(new CreateTransactionChainReply(transactionChain.path()),
+                getSelf());
     }
-  }
-
-  private void updateSchemaContext(UpdateSchemaContext message) {
-    store.onGlobalContextUpdated(message.getSchemaContext());
-  }
-
-  private void registerChangeListener(RegisterChangeListener registerChangeListener) {
-    org.opendaylight.yangtools.concepts.ListenerRegistration<AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>> registration =
-            store.registerChangeListener(registerChangeListener.getPath(), registerChangeListener.getListener(), registerChangeListener.getScope());
-    ActorRef listenerRegistration = getContext().actorOf(ListenerRegistration.props(registration));
-    getSender().tell(new RegisterChangeListenerReply(listenerRegistration.path()), getSelf());
-  }
-
-  private void createTransactionChain() {
-    DOMStoreTransactionChain chain = store.createTransactionChain();
-    ActorRef transactionChain = getContext().actorOf(ShardTransactionChain.props(chain));
-    getSender().tell(new CreateTransactionChainReply(transactionChain.path()), getSelf());
-  }
 }
index 63266d6308287d2e816724f3f73b192b0d120bce..250ef49e6f0b73ca33ad0a41eb36c661b9560038 100644 (file)
@@ -8,12 +8,17 @@
 
 package org.opendaylight.controller.cluster.datastore;
 
+import akka.actor.ActorPath;
+import akka.actor.ActorRef;
 import akka.actor.Address;
-import akka.actor.UntypedActor;
+import akka.actor.Props;
 import akka.event.Logging;
 import akka.event.LoggingAdapter;
+import akka.japi.Creator;
 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
+import org.opendaylight.controller.cluster.datastore.messages.PrimaryFound;
 import org.opendaylight.controller.cluster.datastore.messages.PrimaryNotFound;
+import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
 
 import java.util.HashMap;
 import java.util.List;
@@ -21,41 +26,77 @@ import java.util.Map;
 
 /**
  * The ShardManager has the following jobs,
- *
- *  - Create all the local shard replicas that belong on this cluster member
- *  - Find the primary replica for any given shard
- *  - Engage in shard replica elections which decide which replica should be the primary
- *
- * Creation of Shard replicas
- * ==========================
- *  When the ShardManager is constructed it reads the cluster configuration to find out which shard replicas
- *  belong on this member. It finds out the name of the current cluster member from the Akka Clustering Service.
- *
- * Replica Elections
- * =================
- *  The Shard Manager uses multiple cues to initiate election.
- *      - When a member of the cluster dies
- *      - When a local shard replica dies
- *      - When a local shard replica comes alive
+ * <p>
+ * <li> Create all the local shard replicas that belong on this cluster member
+ * <li> Find the primary replica for any given shard
+ * <li> Engage in shard replica elections which decide which replica should be the primary
+ * </p>
+ * <p/>
+ * <h3>>Creation of Shard replicas</h3
+ * <p>
+ * When the ShardManager is constructed it reads the cluster configuration to find out which shard replicas
+ * belong on this member. It finds out the name of the current cluster member from the Akka Clustering Service.
+ * </p>
+ * <p/>
+ * <h3> Replica Elections </h3>
+ * <p/>
+ * <p>
+ * The Shard Manager uses multiple cues to initiate election.
+ * <li> When a member of the cluster dies
+ * <li> When a local shard replica dies
+ * <li> When a local shard replica comes alive
+ * </p>
  */
-public class ShardManager extends UntypedActor {
+public class ShardManager extends AbstractUntypedActor {
+
+  // Stores a mapping between a shard name and the address of the current primary
+  private final Map<String, Address> shardNameToPrimaryAddress = new HashMap<>();
+
+  // Stores a mapping between a member name and the address of the member
+  private final Map<String, Address> memberNameToAddress = new HashMap<>();
 
-    // Stores a mapping between a shard name and the address of the current primary
-    private final Map<String, Address> shardNameToPrimaryAddress = new HashMap<>();
+  // Stores a mapping between the shard name and all the members on which a replica of that shard are available
+  private final Map<String, List<String>> shardNameToMembers = new HashMap<>();
 
-    // Stores a mapping between a member name and the address of the member
-    private final Map<String, Address> memberNameToAddress = new HashMap<>();
+  private final LoggingAdapter log = Logging.getLogger(getContext().system(), this);
 
-    // Stores a mapping between the shard name and all the members on which a replica of that shard are available
-    private final Map<String, List<String>> shardNameToMembers = new HashMap<>();
+  private final ActorPath defaultShardPath;
 
-    LoggingAdapter log = Logging.getLogger(getContext().system(), this);
+  /**
+   *
+   * @param type defines the kind of data that goes into shards created by this shard manager. Examples of type would be
+   *             configuration or operational
+   */
+  private ShardManager(String type){
+    ActorRef actor = getContext().actorOf(Shard.props("shard-" + Shard.DEFAULT_NAME + "-" + type), "shard-" + Shard.DEFAULT_NAME + "-" + type);
+    defaultShardPath = actor.path();
+  }
 
-    @Override
-    public void onReceive(Object message) throws Exception {
-        if(message instanceof FindPrimary ){
-            FindPrimary msg = ((FindPrimary) message);
-            getSender().tell(new PrimaryNotFound(msg.getShardName()), getSelf());
-        }
+  public static Props props(final String type){
+    return Props.create(new Creator<ShardManager>(){
+
+      @Override
+      public ShardManager create() throws Exception {
+        return new ShardManager(type);
+      }
+    });
+  }
+
+  @Override
+  public void handleReceive(Object message) throws Exception {
+    if (message instanceof FindPrimary) {
+      FindPrimary msg = ((FindPrimary) message);
+      String shardName = msg.getShardName();
+      if(Shard.DEFAULT_NAME.equals(shardName)){
+        getSender().tell(new PrimaryFound(defaultShardPath.toString()), getSelf());
+      } else {
+        getSender().tell(new PrimaryNotFound(shardName), getSelf());
+      }
+    } else if(message instanceof UpdateSchemaContext){
+        // FIXME : Notify all local shards of a context change
+        getContext().system().actorSelection(defaultShardPath).forward(message, getContext());
     }
+  }
+
+
 }
index b316b9df04966d82faf19ffc0743994dc684ec4a..e3d1e2d9d42e4968f4b81ca0ea33d40c2b7b07f7 100644 (file)
@@ -9,8 +9,8 @@
 package org.opendaylight.controller.cluster.datastore;
 
 import akka.actor.ActorRef;
+import akka.actor.PoisonPill;
 import akka.actor.Props;
-import akka.actor.UntypedActor;
 import akka.event.Logging;
 import akka.event.LoggingAdapter;
 import akka.japi.Creator;
@@ -28,8 +28,15 @@ import org.opendaylight.controller.cluster.datastore.messages.ReadyTransaction;
 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
 import org.opendaylight.controller.cluster.datastore.messages.WriteData;
 import org.opendaylight.controller.cluster.datastore.messages.WriteDataReply;
+import org.opendaylight.controller.cluster.datastore.modification.CompositeModification;
+import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
+import org.opendaylight.controller.cluster.datastore.modification.ImmutableCompositeModification;
+import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
+import org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification;
+import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 
@@ -37,110 +44,184 @@ import java.util.concurrent.ExecutionException;
 
 /**
  * The ShardTransaction Actor represents a remote transaction
- *
+ * <p>
  * The ShardTransaction Actor delegates all actions to DOMDataReadWriteTransaction
- *
+ * </p>
+ * <p>
  * Even though the DOMStore and the DOMStoreTransactionChain implement multiple types of transactions
  * the ShardTransaction Actor only works with read-write transactions. This is just to keep the logic simple. At this
  * time there are no known advantages for creating a read-only or write-only transaction which may change over time
  * at which point we can optimize things in the distributed store as well.
- *
- * Handles Messages
- * ----------------
- * {@link org.opendaylight.controller.cluster.datastore.messages.ReadData}
- * {@link org.opendaylight.controller.cluster.datastore.messages.WriteData}
- * {@link org.opendaylight.controller.cluster.datastore.messages.MergeData}
- * {@link org.opendaylight.controller.cluster.datastore.messages.DeleteData}
- * {@link org.opendaylight.controller.cluster.datastore.messages.ReadyTransaction}
- * {@link org.opendaylight.controller.cluster.datastore.messages.CloseTransaction}
+ * </p>
+ * <p>
+ * Handles Messages <br/>
+ * ---------------- <br/>
+ * <li> {@link org.opendaylight.controller.cluster.datastore.messages.ReadData}
+ * <li> {@link org.opendaylight.controller.cluster.datastore.messages.WriteData}
+ * <li> {@link org.opendaylight.controller.cluster.datastore.messages.MergeData}
+ * <li> {@link org.opendaylight.controller.cluster.datastore.messages.DeleteData}
+ * <li> {@link org.opendaylight.controller.cluster.datastore.messages.ReadyTransaction}
+ * <li> {@link org.opendaylight.controller.cluster.datastore.messages.CloseTransaction}
+ * </p>
  */
-public class ShardTransaction extends UntypedActor {
-
-  private final DOMStoreReadWriteTransaction transaction;
-
-  private final LoggingAdapter log = Logging.getLogger(getContext().system(), this);
-
-  public ShardTransaction(DOMStoreReadWriteTransaction transaction) {
-    this.transaction = transaction;
-  }
-
-
-  public static Props props(final DOMStoreReadWriteTransaction transaction){
-    return Props.create(new Creator<ShardTransaction>(){
-
-      @Override
-      public ShardTransaction create() throws Exception {
-        return new ShardTransaction(transaction);
-      }
-    });
-  }
-
-  @Override
-  public void onReceive(Object message) throws Exception {
-    if(message instanceof ReadData){
-      readData((ReadData) message);
-    } else if(message instanceof WriteData){
-      writeData((WriteData) message);
-    } else if(message instanceof MergeData){
-      mergeData((MergeData) message);
-    } else if(message instanceof DeleteData){
-      deleteData((DeleteData) message);
-    } else if(message instanceof ReadyTransaction){
-      readyTransaction((ReadyTransaction) message);
-    } else if(message instanceof CloseTransaction){
-      closeTransaction((CloseTransaction) message);
+public class ShardTransaction extends AbstractUntypedActor {
+
+    private final ActorRef shardActor;
+
+    // FIXME : see below
+    // If transactionChain is not null then this transaction is part of a
+    // transactionChain. Not really clear as to what that buys us
+    private final DOMStoreTransactionChain transactionChain;
+
+    private final DOMStoreReadWriteTransaction transaction;
+
+    private final MutableCompositeModification modification =
+        new MutableCompositeModification();
+
+    private final LoggingAdapter log =
+        Logging.getLogger(getContext().system(), this);
+
+    public ShardTransaction(DOMStoreReadWriteTransaction transaction,
+        ActorRef shardActor) {
+        this(null, transaction, shardActor);
+    }
+
+    public ShardTransaction(DOMStoreTransactionChain transactionChain, DOMStoreReadWriteTransaction transaction,
+        ActorRef shardActor) {
+        this.transactionChain = transactionChain;
+        this.transaction = transaction;
+        this.shardActor = shardActor;
     }
-  }
-
-  private void readData(ReadData message) {
-    final ActorRef sender = getSender();
-    final ActorRef self = getSelf();
-    final InstanceIdentifier path = message.getPath();
-    final ListenableFuture<Optional<NormalizedNode<?, ?>>> future = transaction.read(path);
-
-    future.addListener(new Runnable() {
-      @Override
-      public void run() {
-        try {
-          Optional<NormalizedNode<?, ?>> optional = future.get();
-          if(optional.isPresent()){
-            sender.tell(new ReadDataReply(optional.get()), self);
-          } else {
-            //TODO : Need to decide what to do here
-          }
-        } catch (InterruptedException | ExecutionException e) {
-          log.error(e, "An exception happened when reading data from path : " + path.toString());
+
+
+
+    public static Props props(final DOMStoreReadWriteTransaction transaction,
+        final ActorRef shardActor) {
+        return Props.create(new Creator<ShardTransaction>() {
+
+            @Override
+            public ShardTransaction create() throws Exception {
+                return new ShardTransaction(transaction, shardActor);
+            }
+        });
+    }
+
+    public static Props props(final DOMStoreTransactionChain transactionChain, final DOMStoreReadWriteTransaction transaction,
+        final ActorRef shardActor) {
+        return Props.create(new Creator<ShardTransaction>() {
+
+            @Override
+            public ShardTransaction create() throws Exception {
+                return new ShardTransaction(transactionChain, transaction, shardActor);
+            }
+        });
+    }
+
+
+    @Override
+    public void handleReceive(Object message) throws Exception {
+        if (message instanceof ReadData) {
+            readData((ReadData) message);
+        } else if (message instanceof WriteData) {
+            writeData((WriteData) message);
+        } else if (message instanceof MergeData) {
+            mergeData((MergeData) message);
+        } else if (message instanceof DeleteData) {
+            deleteData((DeleteData) message);
+        } else if (message instanceof ReadyTransaction) {
+            readyTransaction((ReadyTransaction) message);
+        } else if (message instanceof CloseTransaction) {
+            closeTransaction((CloseTransaction) message);
+        } else if (message instanceof GetCompositedModification) {
+            // This is here for testing only
+            getSender().tell(new GetCompositeModificationReply(
+                new ImmutableCompositeModification(modification)), getSelf());
         }
+    }
 
-      }
-    }, getContext().dispatcher());
-  }
+    private void readData(ReadData message) {
+        final ActorRef sender = getSender();
+        final ActorRef self = getSelf();
+        final InstanceIdentifier path = message.getPath();
+        final ListenableFuture<Optional<NormalizedNode<?, ?>>> future =
+            transaction.read(path);
+
+        future.addListener(new Runnable() {
+            @Override
+            public void run() {
+                try {
+                    Optional<NormalizedNode<?, ?>> optional = future.get();
+                    if (optional.isPresent()) {
+                        sender.tell(new ReadDataReply(optional.get()), self);
+                    } else {
+                        sender.tell(new ReadDataReply(null), self);
+                    }
+                } catch (InterruptedException | ExecutionException e) {
+                    log.error(e,
+                        "An exception happened when reading data from path : "
+                            + path.toString());
+                }
+
+            }
+        }, getContext().dispatcher());
+    }
+
+
+    private void writeData(WriteData message) {
+        modification.addModification(
+            new WriteModification(message.getPath(), message.getData()));
+        transaction.write(message.getPath(), message.getData());
+        getSender().tell(new WriteDataReply(), getSelf());
+    }
 
+    private void mergeData(MergeData message) {
+        modification.addModification(
+            new MergeModification(message.getPath(), message.getData()));
+        transaction.merge(message.getPath(), message.getData());
+        getSender().tell(new MergeDataReply(), getSelf());
+    }
 
-  private void writeData(WriteData message){
-    transaction.write(message.getPath(), message.getData());
-    getSender().tell(new WriteDataReply(), getSelf());
-  }
+    private void deleteData(DeleteData message) {
+        modification.addModification(new DeleteModification(message.getPath()));
+        transaction.delete(message.getPath());
+        getSender().tell(new DeleteDataReply(), getSelf());
+    }
+
+    private void readyTransaction(ReadyTransaction message) {
+        DOMStoreThreePhaseCommitCohort cohort = transaction.ready();
+        ActorRef cohortActor = getContext().actorOf(
+            ThreePhaseCommitCohort.props(cohort, shardActor, modification), "cohort");
+        getSender()
+            .tell(new ReadyTransactionReply(cohortActor.path()), getSelf());
+
+    }
+
+    private void closeTransaction(CloseTransaction message) {
+        transaction.close();
+        getSender().tell(new CloseTransactionReply(), getSelf());
+        getSelf().tell(PoisonPill.getInstance(), getSelf());
+    }
 
-  private void mergeData(MergeData message){
-    transaction.merge(message.getPath(), message.getData());
-    getSender().tell(new MergeDataReply(), getSelf());
-  }
 
-  private void deleteData(DeleteData message){
-    transaction.delete(message.getPath());
-    getSender().tell(new DeleteDataReply(), getSelf());
-  }
+    // These classes are in here for test purposes only
 
-  private void readyTransaction(ReadyTransaction message){
-    DOMStoreThreePhaseCommitCohort cohort = transaction.ready();
-    ActorRef cohortActor = getContext().actorOf(ThreePhaseCommitCohort.props(cohort));
-    getSender().tell(new ReadyTransactionReply(cohortActor.path()), getSelf());
 
-  }
+    static class GetCompositedModification {
 
-  private void closeTransaction(CloseTransaction message){
-    transaction.close();
-    getSender().tell(new CloseTransactionReply(), getSelf());
-  }
+    }
+
+
+    static class GetCompositeModificationReply {
+        private final CompositeModification modification;
+
+
+        GetCompositeModificationReply(CompositeModification modification) {
+            this.modification = modification;
+        }
+
+
+        public CompositeModification getModification() {
+            return modification;
+        }
+    }
 }
index 83913fe416fb766698ce9bd4294819d48276905d..1092e9a793d82443b2bda82eeb81fbebb7360675 100644 (file)
@@ -10,7 +10,6 @@ package org.opendaylight.controller.cluster.datastore;
 
 import akka.actor.ActorRef;
 import akka.actor.Props;
-import akka.actor.UntypedActor;
 import akka.japi.Creator;
 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
 import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChainReply;
@@ -22,33 +21,42 @@ import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
 /**
  * The ShardTransactionChain Actor represents a remote TransactionChain
  */
-public class ShardTransactionChain extends UntypedActor{
-
-  private final DOMStoreTransactionChain chain;
-
-  public ShardTransactionChain(DOMStoreTransactionChain chain) {
-    this.chain = chain;
-  }
-
-  @Override
-  public void onReceive(Object message) throws Exception {
-    if(message instanceof CreateTransaction){
-      DOMStoreReadWriteTransaction transaction = chain.newReadWriteTransaction();
-      ActorRef transactionActor = getContext().actorOf(ShardTransaction.props(transaction));
-      getSender().tell(new CreateTransactionReply(transactionActor.path()), getSelf());
-    } else if (message instanceof CloseTransactionChain){
-      chain.close();
-      getSender().tell(new CloseTransactionChainReply(), getSelf());
+public class ShardTransactionChain extends AbstractUntypedActor {
+
+    private final DOMStoreTransactionChain chain;
+
+    public ShardTransactionChain(DOMStoreTransactionChain chain) {
+        this.chain = chain;
     }
-  }
 
-  public static Props props(final DOMStoreTransactionChain chain){
-    return Props.create(new Creator<ShardTransactionChain>(){
+    @Override
+    public void handleReceive(Object message) throws Exception {
+        if (message instanceof CreateTransaction) {
+            CreateTransaction createTransaction = (CreateTransaction) message;
+            createTransaction(createTransaction);
+        } else if (message instanceof CloseTransactionChain) {
+            chain.close();
+            getSender().tell(new CloseTransactionChainReply(), getSelf());
+        }
+    }
 
-      @Override
-      public ShardTransactionChain create() throws Exception {
-        return new ShardTransactionChain(chain);
-      }
-    });
-  }
+    private void createTransaction(CreateTransaction createTransaction) {
+        DOMStoreReadWriteTransaction transaction =
+            chain.newReadWriteTransaction();
+        ActorRef transactionActor = getContext().actorOf(ShardTransaction
+            .props(chain, transaction, getContext().parent()), "shard-" + createTransaction.getTransactionId());
+        getSender()
+            .tell(new CreateTransactionReply(transactionActor.path(), createTransaction.getTransactionId()),
+                getSelf());
+    }
+
+    public static Props props(final DOMStoreTransactionChain chain) {
+        return Props.create(new Creator<ShardTransactionChain>() {
+
+            @Override
+            public ShardTransactionChain create() throws Exception {
+                return new ShardTransactionChain(chain);
+            }
+        });
+    }
 }
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/TerminationMonitor.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/TerminationMonitor.java
new file mode 100644 (file)
index 0000000..e6ac7f8
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.cluster.datastore;
+
+import akka.actor.Terminated;
+import akka.actor.UntypedActor;
+import akka.event.Logging;
+import akka.event.LoggingAdapter;
+import org.opendaylight.controller.cluster.datastore.messages.Monitor;
+
+public class TerminationMonitor extends UntypedActor{
+    protected final LoggingAdapter LOG =
+        Logging.getLogger(getContext().system(), this);
+
+    public TerminationMonitor(){
+        LOG.info("Created TerminationMonitor");
+    }
+
+    @Override public void onReceive(Object message) throws Exception {
+        if(message instanceof Terminated){
+            Terminated terminated = (Terminated) message;
+            LOG.debug("Actor terminated : {}", terminated.actor());
+        } else if(message instanceof Monitor){
+            Monitor monitor = (Monitor) message;
+            getContext().watch(monitor.getActorRef());
+        }
+    }
+}
index 8e21cb2d86fc846d4923526024b62e0aff332f12..060c9d6b509ab26f481a59c492da753ab70a2400 100644 (file)
 
 package org.opendaylight.controller.cluster.datastore;
 
+import akka.actor.ActorRef;
+import akka.actor.PoisonPill;
 import akka.actor.Props;
-import akka.actor.UntypedActor;
+import akka.event.Logging;
+import akka.event.LoggingAdapter;
 import akka.japi.Creator;
+import com.google.common.util.concurrent.ListenableFuture;
+import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.ForwardedCommitTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.PreCommitTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.PreCommitTransactionReply;
+import org.opendaylight.controller.cluster.datastore.modification.CompositeModification;
 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
 
-public class ThreePhaseCommitCohort extends UntypedActor{
-  private final DOMStoreThreePhaseCommitCohort cohort;
+import java.util.concurrent.ExecutionException;
 
-  public ThreePhaseCommitCohort(DOMStoreThreePhaseCommitCohort cohort) {
+public class ThreePhaseCommitCohort extends AbstractUntypedActor {
+    private final DOMStoreThreePhaseCommitCohort cohort;
+    private final ActorRef shardActor;
+    private final CompositeModification modification;
 
-    this.cohort = cohort;
-  }
+    public ThreePhaseCommitCohort(DOMStoreThreePhaseCommitCohort cohort,
+        ActorRef shardActor, CompositeModification modification) {
 
-  @Override
-  public void onReceive(Object message) throws Exception {
-    throw new UnsupportedOperationException("onReceive");
-  }
+        this.cohort = cohort;
+        this.shardActor = shardActor;
+        this.modification = modification;
+    }
 
-  public static Props props(final DOMStoreThreePhaseCommitCohort cohort) {
-    return Props.create(new Creator<ThreePhaseCommitCohort>(){
-      @Override
-      public ThreePhaseCommitCohort create() throws Exception {
-        return new ThreePhaseCommitCohort(cohort);
-      }
-    });
-  }
+    private final LoggingAdapter log =
+        Logging.getLogger(getContext().system(), this);
+
+    public static Props props(final DOMStoreThreePhaseCommitCohort cohort,
+        final ActorRef shardActor, final CompositeModification modification) {
+        return Props.create(new Creator<ThreePhaseCommitCohort>() {
+            @Override
+            public ThreePhaseCommitCohort create() throws Exception {
+                return new ThreePhaseCommitCohort(cohort, shardActor,
+                    modification);
+            }
+        });
+    }
+
+
+    @Override
+    public void handleReceive(Object message) throws Exception {
+        if (message instanceof CanCommitTransaction) {
+            canCommit((CanCommitTransaction) message);
+        } else if (message instanceof PreCommitTransaction) {
+            preCommit((PreCommitTransaction) message);
+        } else if (message instanceof CommitTransaction) {
+            commit((CommitTransaction) message);
+        } else if (message instanceof AbortTransaction) {
+            abort((AbortTransaction) message);
+        }
+    }
+
+    private void abort(AbortTransaction message) {
+        final ListenableFuture<Void> future = cohort.abort();
+        final ActorRef sender = getSender();
+        final ActorRef self = getSelf();
+
+        future.addListener(new Runnable() {
+            @Override
+            public void run() {
+                try {
+                    future.get();
+                    sender.tell(new AbortTransactionReply(), self);
+                } catch (InterruptedException | ExecutionException e) {
+                    log.error(e, "An exception happened when aborting");
+                }
+            }
+        }, getContext().dispatcher());
+    }
+
+    private void commit(CommitTransaction message) {
+        // Forward the commit to the shard
+        log.debug("Forward commit transaction to Shard {} ", shardActor);
+        shardActor.forward(new ForwardedCommitTransaction(cohort, modification),
+            getContext());
+
+        getContext().parent().tell(PoisonPill.getInstance(), getSelf());
+
+    }
+
+    private void preCommit(PreCommitTransaction message) {
+        final ListenableFuture<Void> future = cohort.preCommit();
+        final ActorRef sender = getSender();
+        final ActorRef self = getSelf();
+
+        future.addListener(new Runnable() {
+            @Override
+            public void run() {
+                try {
+                    future.get();
+                    sender.tell(new PreCommitTransactionReply(), self);
+                } catch (InterruptedException | ExecutionException e) {
+                    log.error(e, "An exception happened when preCommitting");
+                }
+            }
+        }, getContext().dispatcher());
+
+    }
+
+    private void canCommit(CanCommitTransaction message) {
+        final ListenableFuture<Boolean> future = cohort.canCommit();
+        final ActorRef sender = getSender();
+        final ActorRef self = getSelf();
+
+        future.addListener(new Runnable() {
+            @Override
+            public void run() {
+                try {
+                    Boolean canCommit = future.get();
+                    sender.tell(new CanCommitTransactionReply(canCommit), self);
+                } catch (InterruptedException | ExecutionException e) {
+                    log.error(e, "An exception happened when aborting");
+                }
+            }
+        }, getContext().dispatcher());
+
+    }
 }
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ThreePhaseCommitCohortProxy.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/ThreePhaseCommitCohortProxy.java
new file mode 100644 (file)
index 0000000..279ecba
--- /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.datastore;
+
+import akka.actor.ActorPath;
+import akka.actor.ActorSelection;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListenableFutureTask;
+import org.opendaylight.controller.cluster.datastore.exceptions.TimeoutException;
+import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.PreCommitTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.PreCommitTransactionReply;
+import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+
+/**
+ * ThreePhaseCommitCohortProxy represents a set of remote cohort proxies
+ */
+public class ThreePhaseCommitCohortProxy implements
+    DOMStoreThreePhaseCommitCohort{
+
+    private static final Logger
+        LOG = LoggerFactory.getLogger(DistributedDataStore.class);
+
+    private final ActorContext actorContext;
+    private final List<ActorPath> cohortPaths;
+    private final ExecutorService executor;
+    private final String transactionId;
+
+
+    public ThreePhaseCommitCohortProxy(ActorContext actorContext,
+        List<ActorPath> cohortPaths,
+        String transactionId,
+        ExecutorService executor) {
+
+        this.actorContext = actorContext;
+        this.cohortPaths = cohortPaths;
+        this.transactionId = transactionId;
+        this.executor = executor;
+    }
+
+    @Override public ListenableFuture<Boolean> canCommit() {
+        Callable<Boolean> call = new Callable() {
+
+            @Override public Boolean call() throws Exception {
+            for(ActorPath actorPath : cohortPaths){
+                ActorSelection cohort = actorContext.actorSelection(actorPath);
+
+                try {
+                    Object response =
+                        actorContext.executeRemoteOperation(cohort,
+                            new CanCommitTransaction(),
+                            ActorContext.ASK_DURATION);
+
+                    if (response instanceof CanCommitTransactionReply) {
+                        CanCommitTransactionReply reply =
+                            (CanCommitTransactionReply) response;
+                        if (!reply.getCanCommit()) {
+                            return false;
+                        }
+                    }
+                } catch(RuntimeException e){
+                    LOG.error("Unexpected Exception", e);
+                    return false;
+                }
+
+
+            }
+            return true;
+            }
+        };
+
+        ListenableFutureTask<Boolean>
+            future = ListenableFutureTask.create(call);
+
+        executor.submit(future);
+
+        return future;
+    }
+
+    @Override public ListenableFuture<Void> preCommit() {
+        return voidOperation(new PreCommitTransaction(), PreCommitTransactionReply.class);
+    }
+
+    @Override public ListenableFuture<Void> abort() {
+        return voidOperation(new AbortTransaction(), AbortTransactionReply.class);
+    }
+
+    @Override public ListenableFuture<Void> commit() {
+        return voidOperation(new CommitTransaction(), CommitTransactionReply.class);
+    }
+
+    private ListenableFuture<Void> voidOperation(final Object message, final Class expectedResponseClass){
+        Callable<Void> call = new Callable<Void>() {
+
+            @Override public Void call() throws Exception {
+                for(ActorPath actorPath : cohortPaths){
+                    ActorSelection cohort = actorContext.actorSelection(actorPath);
+
+                    try {
+                        Object response =
+                            actorContext.executeRemoteOperation(cohort,
+                                message,
+                                ActorContext.ASK_DURATION);
+
+                        if (response != null && !response.getClass()
+                            .equals(expectedResponseClass)) {
+                            throw new RuntimeException(
+                                String.format(
+                                    "did not get the expected response \n\t\t expected : %s \n\t\t actual   : %s",
+                                    expectedResponseClass.toString(),
+                                    response.getClass().toString())
+                            );
+                        }
+                    } catch(TimeoutException e){
+                        LOG.error(String.format("A timeout occurred when processing operation : %s", message));
+                    }
+                }
+                return null;
+            }
+        };
+
+        ListenableFutureTask<Void>
+            future = ListenableFutureTask.create(call);
+
+        executor.submit(future);
+
+        return future;
+
+    }
+
+    public List<ActorPath> getCohortPaths() {
+        return Collections.unmodifiableList(this.cohortPaths);
+    }
+}
index 1ee0d89e6116837a1733848aae5f85e1cf02cd34..71b61ffaa0bbfd81121b87ee616e3cce2e71ac07 100644 (file)
@@ -8,32 +8,47 @@
 
 package org.opendaylight.controller.cluster.datastore;
 
+import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
 import org.opendaylight.controller.sal.core.spi.data.DOMStoreTransactionChain;
 import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
 
+import java.util.concurrent.ExecutorService;
+
 /**
  * TransactionChainProxy acts as a proxy for a DOMStoreTransactionChain created on a remote shard
  */
 public class TransactionChainProxy implements DOMStoreTransactionChain{
+    private final ActorContext actorContext;
+    private final ExecutorService transactionExecutor;
+
+    public TransactionChainProxy(ActorContext actorContext, ExecutorService transactionExecutor) {
+        this.actorContext = actorContext;
+        this.transactionExecutor = transactionExecutor;
+    }
+
     @Override
     public DOMStoreReadTransaction newReadOnlyTransaction() {
-        throw new UnsupportedOperationException("newReadOnlyTransaction");
+        return new TransactionProxy(actorContext,
+            TransactionProxy.TransactionType.READ_ONLY, transactionExecutor);
     }
 
     @Override
     public DOMStoreReadWriteTransaction newReadWriteTransaction() {
-        throw new UnsupportedOperationException("newReadWriteTransaction");
+        return new TransactionProxy(actorContext,
+            TransactionProxy.TransactionType.WRITE_ONLY, transactionExecutor);
     }
 
     @Override
     public DOMStoreWriteTransaction newWriteOnlyTransaction() {
-        throw new UnsupportedOperationException("newWriteOnlyTransaction");
+        return new TransactionProxy(actorContext,
+            TransactionProxy.TransactionType.READ_WRITE, transactionExecutor);
     }
 
     @Override
     public void close() {
-        throw new UnsupportedOperationException("close");
+        // FIXME : The problem here is don't know which shard the transaction chain is to be created on ???
+        throw new UnsupportedOperationException("close - not sure what to do here?");
     }
 }
index 609dea0b360819ebc576e636e2237b8cb9868172..74245c42592ca3d6743d0aef3b48bb2e6ace2b45 100644 (file)
 
 package org.opendaylight.controller.cluster.datastore;
 
+import akka.actor.ActorPath;
+import akka.actor.ActorSelection;
 import com.google.common.base.Optional;
 import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListenableFutureTask;
+import org.opendaylight.controller.cluster.datastore.messages.CloseTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.DeleteData;
+import org.opendaylight.controller.cluster.datastore.messages.MergeData;
+import org.opendaylight.controller.cluster.datastore.messages.ReadData;
+import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
+import org.opendaylight.controller.cluster.datastore.messages.ReadyTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.WriteData;
+import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.atomic.AtomicLong;
+
 /**
  * TransactionProxy acts as a proxy for one or more transactions that were created on a remote shard
- *
+ * <p>
  * Creating a transaction on the consumer side will create one instance of a transaction proxy. If during
  * the transaction reads and writes are done on data that belongs to different shards then a separate transaction will
  * be created on each of those shards by the TransactionProxy
- *
+ *</p>
+ * <p>
  * The TransactionProxy does not make any guarantees about atomicity or order in which the transactions on the various
  * shards will be executed.
- *
+ * </p>
  */
 public class TransactionProxy implements DOMStoreReadWriteTransaction {
+    public enum TransactionType {
+        READ_ONLY,
+        WRITE_ONLY,
+        READ_WRITE
+    }
+
+    private static final AtomicLong counter = new AtomicLong();
+
+    private final TransactionType transactionType;
+    private final ActorContext actorContext;
+    private final Map<String, ActorSelection> remoteTransactionPaths = new HashMap<>();
+    private final String identifier;
+    private final ExecutorService executor;
+
+    public TransactionProxy(
+        ActorContext actorContext,
+        TransactionType transactionType,
+        ExecutorService executor
+        ) {
+
+        this.identifier = "txn-" + counter.getAndIncrement();
+        this.transactionType = transactionType;
+        this.actorContext = actorContext;
+        this.executor = executor;
+
+        Object response = actorContext.executeShardOperation(Shard.DEFAULT_NAME, new CreateTransaction(identifier), ActorContext.ASK_DURATION);
+        if(response instanceof CreateTransactionReply){
+            CreateTransactionReply reply = (CreateTransactionReply) response;
+            remoteTransactionPaths.put(Shard.DEFAULT_NAME, actorContext.actorSelection(reply.getTransactionPath()));
+        }
+    }
+
     @Override
-    public ListenableFuture<Optional<NormalizedNode<?, ?>>> read(InstanceIdentifier path) {
-        throw new UnsupportedOperationException("read");
+    public ListenableFuture<Optional<NormalizedNode<?, ?>>> read(final InstanceIdentifier path) {
+        final ActorSelection remoteTransaction = remoteTransactionFromIdentifier(path);
+
+        Callable<Optional<NormalizedNode<?,?>>> call = new Callable() {
+
+            @Override public Optional<NormalizedNode<?,?>> call() throws Exception {
+                Object response = actorContext
+                    .executeRemoteOperation(remoteTransaction, new ReadData(path),
+                        ActorContext.ASK_DURATION);
+                if(response instanceof ReadDataReply){
+                    ReadDataReply reply = (ReadDataReply) response;
+                    if(reply.getNormalizedNode() == null){
+                        return Optional.absent();
+                    }
+                    //FIXME : A cast should not be required here ???
+                    return (Optional<NormalizedNode<?, ?>>) Optional.of(reply.getNormalizedNode());
+                }
+
+                return Optional.absent();
+            }
+        };
+
+        ListenableFutureTask<Optional<NormalizedNode<?, ?>>>
+            future = ListenableFutureTask.create(call);
+
+        executor.submit(future);
+
+        return future;
     }
 
     @Override
     public void write(InstanceIdentifier path, NormalizedNode<?, ?> data) {
-        throw new UnsupportedOperationException("write");
+        final ActorSelection remoteTransaction = remoteTransactionFromIdentifier(path);
+        remoteTransaction.tell(new WriteData(path, data), null);
     }
 
     @Override
     public void merge(InstanceIdentifier path, NormalizedNode<?, ?> data) {
-        throw new UnsupportedOperationException("merge");
+        final ActorSelection remoteTransaction = remoteTransactionFromIdentifier(path);
+        remoteTransaction.tell(new MergeData(path, data), null);
     }
 
     @Override
     public void delete(InstanceIdentifier path) {
-        throw new UnsupportedOperationException("delete");
+        final ActorSelection remoteTransaction = remoteTransactionFromIdentifier(path);
+        remoteTransaction.tell(new DeleteData(path), null);
     }
 
     @Override
     public DOMStoreThreePhaseCommitCohort ready() {
-        throw new UnsupportedOperationException("ready");
+        List<ActorPath> cohortPaths = new ArrayList<>();
+
+        for(ActorSelection remoteTransaction : remoteTransactionPaths.values()) {
+            Object result = actorContext.executeRemoteOperation(remoteTransaction,
+                new ReadyTransaction(),
+                ActorContext.ASK_DURATION
+            );
+
+            if(result instanceof ReadyTransactionReply){
+                ReadyTransactionReply reply = (ReadyTransactionReply) result;
+                cohortPaths.add(reply.getCohortPath());
+            }
+        }
+
+        return new ThreePhaseCommitCohortProxy(actorContext, cohortPaths, identifier, executor);
     }
 
     @Override
     public Object getIdentifier() {
-        throw new UnsupportedOperationException("getIdentifier");
+        return this.identifier;
     }
 
     @Override
     public void close() {
-        throw new UnsupportedOperationException("close");
+        for(ActorSelection remoteTransaction : remoteTransactionPaths.values()) {
+            remoteTransaction.tell(new CloseTransaction(), null);
+        }
+    }
+
+    private ActorSelection remoteTransactionFromIdentifier(InstanceIdentifier path){
+        String shardName = shardNameFromIdentifier(path);
+        return remoteTransactionPaths.get(shardName);
+    }
+
+    private String shardNameFromIdentifier(InstanceIdentifier path){
+        return Shard.DEFAULT_NAME;
     }
 }
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/PrimaryNotFoundException.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/PrimaryNotFoundException.java
new file mode 100644 (file)
index 0000000..5a131ad
--- /dev/null
@@ -0,0 +1,12 @@
+/*
+ * 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.exceptions;
+
+public class PrimaryNotFoundException extends RuntimeException {
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/TimeoutException.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/exceptions/TimeoutException.java
new file mode 100644 (file)
index 0000000..4780aac
--- /dev/null
@@ -0,0 +1,15 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.cluster.datastore.exceptions;
+
+public class TimeoutException extends RuntimeException {
+    public TimeoutException(Exception e){
+        super(e);
+    }
+}
@@ -5,8 +5,8 @@
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
-package org.opendaylight.controller.sal.binding.impl.connect.dom;
 
-public class CompositeNodeUtils {
+package org.opendaylight.controller.cluster.datastore.messages;
 
+public class CanCommitTransaction {
 }
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CanCommitTransactionReply.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CanCommitTransactionReply.java
new file mode 100644 (file)
index 0000000..d143c14
--- /dev/null
@@ -0,0 +1,21 @@
+/*
+ * 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.messages;
+
+public class CanCommitTransactionReply {
+  private final Boolean canCommit;
+
+  public CanCommitTransactionReply(Boolean canCommit) {
+    this.canCommit = canCommit;
+  }
+
+  public Boolean getCanCommit() {
+    return canCommit;
+  }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseDataChangeListenerRegistration.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseDataChangeListenerRegistration.java
new file mode 100644 (file)
index 0000000..c3cb00c
--- /dev/null
@@ -0,0 +1,12 @@
+/*
+ * 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.messages;
+
+public class CloseDataChangeListenerRegistration {
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseDataChangeListenerRegistrationReply.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CloseDataChangeListenerRegistrationReply.java
new file mode 100644 (file)
index 0000000..d5c75eb
--- /dev/null
@@ -0,0 +1,12 @@
+/*
+ * 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.messages;
+
+public class CloseDataChangeListenerRegistrationReply {
+}
@@ -5,11 +5,8 @@
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
-package org.opendaylight.controller.sal.binding.test.bugfix;
-
-public class RpcRegistrationNullPointer {
-
-
 
+package org.opendaylight.controller.cluster.datastore.messages;
 
+public class CommitTransaction {
 }
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CommitTransactionReply.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/CommitTransactionReply.java
new file mode 100644 (file)
index 0000000..a0e5e89
--- /dev/null
@@ -0,0 +1,12 @@
+/*
+ * 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.messages;
+
+public class CommitTransactionReply {
+}
index e0cdd3cc2b6876ff1e34a155b9e4f18336f0de7a..611064169655185fe0423bfc879b751d625a538b 100644 (file)
@@ -9,5 +9,14 @@
 package org.opendaylight.controller.cluster.datastore.messages;
 
 public class CreateTransaction {
+    private final String transactionId;
 
+    public CreateTransaction(String transactionId){
+
+        this.transactionId = transactionId;
+    }
+
+    public String getTransactionId() {
+        return transactionId;
+    }
 }
index 4faf9d370d56a4dc4bb3edf97de469fb33f95362..46b7194c84c1f13b9503623d43ad1e2aef7a50aa 100644 (file)
@@ -11,13 +11,20 @@ package org.opendaylight.controller.cluster.datastore.messages;
 import akka.actor.ActorPath;
 
 public class CreateTransactionReply {
-  private final ActorPath transactionPath;
+    private final ActorPath transactionPath;
+    private final String transactionId;
 
-  public CreateTransactionReply(ActorPath transactionPath) {
-    this.transactionPath = transactionPath;
-  }
+    public CreateTransactionReply(ActorPath transactionPath,
+        String transactionId) {
+        this.transactionPath = transactionPath;
+        this.transactionId = transactionId;
+    }
 
-  public ActorPath getTransactionPath() {
-    return transactionPath;
-  }
+    public ActorPath getTransactionPath() {
+        return transactionPath;
+    }
+
+    public String getTransactionId() {
+        return transactionId;
+    }
 }
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DataChanged.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DataChanged.java
new file mode 100644 (file)
index 0000000..c55dae5
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * 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.messages;
+
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+public class DataChanged {
+    private final AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>>
+        change;
+
+    public DataChanged(
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change) {
+        this.change = change;
+    }
+
+    public AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> getChange() {
+        return change;
+    }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DataChangedReply.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/DataChangedReply.java
new file mode 100644 (file)
index 0000000..3531021
--- /dev/null
@@ -0,0 +1,12 @@
+/*
+ * 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.messages;
+
+public class DataChangedReply {
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ForwardedCommitTransaction.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/ForwardedCommitTransaction.java
new file mode 100644 (file)
index 0000000..0104993
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * 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.messages;
+
+import org.opendaylight.controller.cluster.datastore.modification.Modification;
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
+
+public class ForwardedCommitTransaction {
+  private final DOMStoreThreePhaseCommitCohort cohort;
+  private final Modification modification;
+
+  public ForwardedCommitTransaction(DOMStoreThreePhaseCommitCohort cohort, Modification modification){
+    this.cohort = cohort;
+    this.modification = modification;
+  }
+
+  public DOMStoreThreePhaseCommitCohort getCohort() {
+    return cohort;
+  }
+
+  public Modification getModification() {
+    return modification;
+  }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/Monitor.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/Monitor.java
new file mode 100644 (file)
index 0000000..567f14a
--- /dev/null
@@ -0,0 +1,24 @@
+/*
+ * 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.messages;
+
+import akka.actor.ActorRef;
+
+public class Monitor {
+    private final ActorRef actorRef;
+
+    public Monitor(ActorRef actorRef){
+
+        this.actorRef = actorRef;
+    }
+
+    public ActorRef getActorRef() {
+        return actorRef;
+    }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/NonPersistent.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/NonPersistent.java
new file mode 100644 (file)
index 0000000..a779ed0
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * 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.messages;
+
+/**
+ * A NonPersistent message is to be used when we want to trigger state update
+ * for an actor without actually persisting the data to disk. This could be
+ * useful for test purposes.
+ */
+public class NonPersistent {
+    private final Object payload;
+
+    public NonPersistent(Object payload){
+        this.payload = payload;
+    }
+
+    public Object payload() {
+        return payload;
+    }
+
+    public static NonPersistent create(Object payload){
+        return new NonPersistent(payload);
+    }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PreCommitTransaction.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PreCommitTransaction.java
new file mode 100644 (file)
index 0000000..87a9c77
--- /dev/null
@@ -0,0 +1,12 @@
+/*
+ * 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.messages;
+
+public class PreCommitTransaction {
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PreCommitTransactionReply.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/messages/PreCommitTransactionReply.java
new file mode 100644 (file)
index 0000000..f499c72
--- /dev/null
@@ -0,0 +1,12 @@
+/*
+ * 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.messages;
+
+public class PreCommitTransactionReply {
+}
index 1326898b0f4059ef215c34d8b175306a1b2a8c9a..d6aae3786fc3e4f1e08eda17c168345c83073dc9 100644 (file)
@@ -9,4 +9,39 @@
 package org.opendaylight.controller.cluster.datastore.messages;
 
 public class PrimaryFound {
+  private final String primaryPath;
+
+  public PrimaryFound(String primaryPath) {
+    this.primaryPath = primaryPath;
+  }
+
+  public String getPrimaryPath() {
+    return primaryPath;
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) return true;
+    if (o == null || getClass() != o.getClass()) return false;
+
+    PrimaryFound that = (PrimaryFound) o;
+
+    if (!primaryPath.equals(that.primaryPath)) return false;
+
+    return true;
+  }
+
+  @Override
+  public int hashCode() {
+    return primaryPath.hashCode();
+  }
+
+  @Override
+  public String toString() {
+    return "PrimaryFound{" +
+            "primaryPath='" + primaryPath + '\'' +
+            '}';
+  }
+
+
 }
index 48565d4fbb5b8847b1c90beea6ce7ca964b00256..32d31bf84db44e87a4ebbbd6328c97c3898fd9ae 100644 (file)
@@ -11,14 +11,14 @@ package org.opendaylight.controller.cluster.datastore.messages;
 import akka.actor.ActorPath;
 
 public class ReadyTransactionReply {
-  private final ActorPath path;
+  private final ActorPath cohortPath;
 
-  public ReadyTransactionReply(ActorPath path) {
+  public ReadyTransactionReply(ActorPath cohortPath) {
 
-    this.path = path;
+    this.cohortPath = cohortPath;
   }
 
-  public ActorPath getPath() {
-    return path;
+  public ActorPath getCohortPath() {
+    return cohortPath;
   }
 }
index 0123a701471e29ef5a81ad41dc3fb2304e4cbf62..7c9e4f0665a2710e2ed4b28f4792e6a043a48800 100644 (file)
@@ -8,32 +8,34 @@
 
 package org.opendaylight.controller.cluster.datastore.messages;
 
+import akka.actor.ActorPath;
 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
-import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 
 public class RegisterChangeListener {
-  private final InstanceIdentifier path;
-  private final AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>> listener;
-  private final AsyncDataBroker.DataChangeScope scope;
+    private final InstanceIdentifier path;
+    private final ActorPath dataChangeListenerPath;
+    private final AsyncDataBroker.DataChangeScope scope;
 
 
-  public RegisterChangeListener(InstanceIdentifier path, AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>> listener, AsyncDataBroker.DataChangeScope scope) {
-    this.path = path;
-    this.listener = listener;
-    this.scope = scope;
-  }
+    public RegisterChangeListener(InstanceIdentifier path,
+        ActorPath dataChangeListenerPath,
+        AsyncDataBroker.DataChangeScope scope) {
+        this.path = path;
+        this.dataChangeListenerPath = dataChangeListenerPath;
+        this.scope = scope;
+    }
 
-  public InstanceIdentifier getPath() {
-    return path;
-  }
+    public InstanceIdentifier getPath() {
+        return path;
+    }
 
-  public AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>> getListener() {
-    return listener;
-  }
 
-  public AsyncDataBroker.DataChangeScope getScope() {
-    return scope;
-  }
+    public AsyncDataBroker.DataChangeScope getScope() {
+        return scope;
+    }
+
+    public ActorPath getDataChangeListenerPath() {
+        return dataChangeListenerPath;
+    }
 }
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/AbstractModification.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/AbstractModification.java
new file mode 100644 (file)
index 0000000..5d9f962
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.cluster.datastore.modification;
+
+
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+
+import java.io.Serializable;
+
+/**
+ * Base class to be used for all simple modifications that can be applied to a DOMStoreTransaction
+ */
+public abstract class AbstractModification implements Modification,
+    Serializable {
+
+    private static final long serialVersionUID = 1638042650152084457L;
+
+    protected final InstanceIdentifier path;
+
+    protected AbstractModification(InstanceIdentifier path) {
+        this.path = path;
+    }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/CompositeModification.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/CompositeModification.java
new file mode 100644 (file)
index 0000000..4c856d3
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ * 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.modification;
+
+import java.util.List;
+
+/**
+ * CompositeModification contains a list of modifications that need to be applied to the DOMStore
+ * <p>
+ * A CompositeModification gets stored in the transaction log for a Shard. During recovery when the transaction log
+ * is being replayed a DOMStoreWriteTransaction could be created and a CompositeModification could be applied to it.
+ * </p>
+ */
+public interface CompositeModification extends Modification {
+    /**
+     * Get a list of Modifications contained by this Composite
+     * @return
+     */
+    List<Modification> getModifications();
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/DeleteModification.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/DeleteModification.java
new file mode 100644 (file)
index 0000000..063ec3e
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ * 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.modification;
+
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+
+/**
+ * DeleteModification store all the parameters required to delete a path from the data tree
+ */
+public class DeleteModification extends AbstractModification {
+  public DeleteModification(InstanceIdentifier path) {
+    super(path);
+  }
+
+  @Override
+  public void apply(DOMStoreWriteTransaction transaction) {
+    transaction.delete(path);
+  }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/ImmutableCompositeModification.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/ImmutableCompositeModification.java
new file mode 100644 (file)
index 0000000..5a15d76
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * 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.modification;
+
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
+
+import java.util.List;
+
+public class ImmutableCompositeModification implements CompositeModification{
+
+  private final CompositeModification modification;
+
+  public ImmutableCompositeModification(CompositeModification modification){
+    this.modification = modification;
+  }
+
+  @Override
+  public List<Modification> getModifications() {
+    return modification.getModifications();
+  }
+
+  @Override
+  public void apply(DOMStoreWriteTransaction transaction) {
+    modification.apply(transaction);
+  }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/MergeModification.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/MergeModification.java
new file mode 100644 (file)
index 0000000..0457a78
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * 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.modification;
+
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+/**
+ * MergeModification stores all the parameters required to merge data into the specified path
+ */
+public class MergeModification extends AbstractModification{
+  private final NormalizedNode data;
+
+
+  public MergeModification(InstanceIdentifier path, NormalizedNode data) {
+    super(path);
+    this.data = data;
+  }
+
+  @Override
+  public void apply(DOMStoreWriteTransaction transaction) {
+    transaction.merge(path, data);
+  }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/Modification.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/Modification.java
new file mode 100644 (file)
index 0000000..60dbf0f
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * 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.modification;
+
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
+
+/**
+ * Represents a modification to the data store.
+ * <p>
+ * Simple modifications can be of type,
+ * <li> {@link org.opendaylight.controller.cluster.datastore.modification.WriteModification}
+ * <li> {@link org.opendaylight.controller.cluster.datastore.modification.MergeModification}
+ * <li> {@link org.opendaylight.controller.cluster.datastore.modification.DeleteModification}
+ * </p>
+ *
+ * <p>
+ * Modifications can in turn be lumped into a single {@link org.opendaylight.controller.cluster.datastore.modification.CompositeModification}
+ * which can then be applied to a write transaction
+ * </p>
+ */
+public interface Modification {
+  /**
+   * Apply the modification to the specified transaction
+   * @param transaction
+   */
+  void apply(DOMStoreWriteTransaction transaction);
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/MutableCompositeModification.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/MutableCompositeModification.java
new file mode 100644 (file)
index 0000000..9f37ba4
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * 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.modification;
+
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * MutableCompositeModification is just a mutable version of a
+ * CompositeModification {@link org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification#addModification(Modification)}
+ */
+public class MutableCompositeModification
+    implements CompositeModification, Serializable {
+
+    private static final long serialVersionUID = 1163377899140186790L;
+
+    private final List<Modification> modifications = new ArrayList<>();
+
+    @Override
+    public void apply(DOMStoreWriteTransaction transaction) {
+        for (Modification modification : modifications) {
+            modification.apply(transaction);
+        }
+    }
+
+    /**
+     * Add a new Modification to the list of Modifications represented by this
+     * composite
+     *
+     * @param modification
+     */
+    public void addModification(Modification modification) {
+        modifications.add(modification);
+    }
+
+    public List<Modification> getModifications() {
+        return Collections.unmodifiableList(modifications);
+    }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/WriteModification.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/modification/WriteModification.java
new file mode 100644 (file)
index 0000000..1b2a87f
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * 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.modification;
+
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+/**
+ * WriteModification stores all the parameters required to write data to the specified path
+ */
+public class WriteModification extends AbstractModification {
+
+  private final NormalizedNode data;
+
+  public WriteModification(InstanceIdentifier path, NormalizedNode data) {
+    super(path);
+    this.data = data;
+  }
+
+  @Override
+  public void apply(DOMStoreWriteTransaction transaction) {
+    transaction.write(path, data);
+  }
+
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/utils/ActorContext.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/cluster/datastore/utils/ActorContext.java
new file mode 100644 (file)
index 0000000..c97e07d
--- /dev/null
@@ -0,0 +1,152 @@
+/*
+ * 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.utils;
+
+import akka.actor.ActorPath;
+import akka.actor.ActorRef;
+import akka.actor.ActorSelection;
+import akka.actor.ActorSystem;
+import akka.actor.PoisonPill;
+import akka.util.Timeout;
+import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
+import org.opendaylight.controller.cluster.datastore.exceptions.TimeoutException;
+import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
+import org.opendaylight.controller.cluster.datastore.messages.PrimaryFound;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.concurrent.Await;
+import scala.concurrent.Future;
+import scala.concurrent.duration.Duration;
+import scala.concurrent.duration.FiniteDuration;
+
+import java.util.concurrent.TimeUnit;
+
+import static akka.pattern.Patterns.ask;
+
+/**
+ * The ActorContext class contains utility methods which could be used by
+ * non-actors (like DistributedDataStore) to work with actors a little more
+ * easily. An ActorContext can be freely passed around to local object instances
+ * but should not be passed to actors especially remote actors
+ */
+public class ActorContext {
+    private static final Logger
+        LOG = LoggerFactory.getLogger(ActorContext.class);
+
+    public static final FiniteDuration ASK_DURATION = Duration.create(5, TimeUnit.SECONDS);
+    public static final Duration AWAIT_DURATION = Duration.create(5, TimeUnit.SECONDS);
+
+    private final ActorSystem actorSystem;
+    private final ActorRef shardManager;
+
+    public ActorContext(ActorSystem actorSystem, ActorRef shardManager){
+        this.actorSystem = actorSystem;
+        this.shardManager = shardManager;
+    }
+
+    public ActorSystem getActorSystem() {
+        return actorSystem;
+    }
+
+    public ActorRef getShardManager() {
+        return shardManager;
+    }
+
+    public ActorSelection actorSelection(String actorPath){
+        return actorSystem.actorSelection(actorPath);
+    }
+
+    public ActorSelection actorSelection(ActorPath actorPath){
+        return actorSystem.actorSelection(actorPath);
+    }
+
+
+    /**
+     * Finds the primary for a given shard
+     *
+     * @param shardName
+     * @return
+     */
+    public ActorSelection findPrimary(String shardName) {
+        Object result = executeLocalOperation(shardManager,
+            new FindPrimary(shardName), ASK_DURATION);
+
+        if(result instanceof PrimaryFound){
+            PrimaryFound found = (PrimaryFound) result;
+
+            LOG.error("Primary found {}", found.getPrimaryPath());
+
+            return actorSystem.actorSelection(found.getPrimaryPath());
+        }
+        throw new PrimaryNotFoundException();
+    }
+
+    /**
+     * Executes an operation on a local actor and wait for it's response
+     * @param actor
+     * @param message
+     * @param duration
+     * @return The response of the operation
+     */
+    public Object executeLocalOperation(ActorRef actor, Object message,
+        FiniteDuration duration){
+        Future<Object> future =
+            ask(actor, message, new Timeout(duration));
+
+        try {
+            return Await.result(future, AWAIT_DURATION);
+        } catch (Exception e) {
+            throw new TimeoutException(e);
+        }
+    }
+
+    /**
+     * Execute an operation on a remote actor and wait for it's response
+     * @param actor
+     * @param message
+     * @param duration
+     * @return
+     */
+    public Object executeRemoteOperation(ActorSelection actor, Object message,
+        FiniteDuration duration){
+        Future<Object> future =
+            ask(actor, message, new Timeout(duration));
+
+        try {
+            return Await.result(future, AWAIT_DURATION);
+        } catch (Exception e) {
+            throw new TimeoutException(e);
+        }
+    }
+
+    /**
+     * Execute an operation on the primary for a given shard
+     * <p>
+     *     This method first finds the primary for a given shard ,then sends
+     *     the message to the remote shard and waits for a response
+     * </p>
+     * @param shardName
+     * @param message
+     * @param duration
+     * @throws org.opendaylight.controller.cluster.datastore.exceptions.TimeoutException if the message to the remote shard times out
+     * @throws org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException if the primary shard is not found
+     *
+     * @return
+     */
+    public Object executeShardOperation(String shardName, Object message, FiniteDuration duration){
+        ActorSelection primary = findPrimary(shardName);
+
+        return executeRemoteOperation(primary, message, duration);
+    }
+
+    public void shutdown() {
+        shardManager.tell(PoisonPill.getInstance(), null);
+        actorSystem.shutdown();
+    }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedConfigDataStoreProviderModule.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedConfigDataStoreProviderModule.java
new file mode 100644 (file)
index 0000000..039446b
--- /dev/null
@@ -0,0 +1,32 @@
+package org.opendaylight.controller.config.yang.config.distributed_datastore_provider;
+
+import org.opendaylight.controller.cluster.datastore.DistributedDataStoreFactory;
+
+public class DistributedConfigDataStoreProviderModule extends
+    org.opendaylight.controller.config.yang.config.distributed_datastore_provider.AbstractDistributedConfigDataStoreProviderModule {
+    public DistributedConfigDataStoreProviderModule(
+        org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+        org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
+        super(identifier, dependencyResolver);
+    }
+
+    public DistributedConfigDataStoreProviderModule(
+        org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+        org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,
+        org.opendaylight.controller.config.yang.config.distributed_datastore_provider.DistributedConfigDataStoreProviderModule oldModule,
+        java.lang.AutoCloseable oldInstance) {
+        super(identifier, dependencyResolver, oldModule, oldInstance);
+    }
+
+    @Override
+    public void customValidation() {
+        // add custom validation form module attributes here.
+    }
+
+    @Override
+    public java.lang.AutoCloseable createInstance() {
+        return DistributedDataStoreFactory
+            .createInstance("config", getSchemaServiceDependency());
+    }
+
+}
@@ -1,13 +1,13 @@
 /*
 * Generated file
 *
-* Generated from: yang module name: distributed-datastore-provider yang module local name: distributed-datastore-provider
+* Generated from: yang module name: distributed-datastore-provider yang module local name: distributed-config-datastore-provider
 * Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator
-* Generated at: Thu Jun 12 15:23:43 PDT 2014
+* Generated at: Tue Jun 24 17:14:50 PDT 2014
 *
 * Do not modify this file unless it is present under src/main directory
 */
 package org.opendaylight.controller.config.yang.config.distributed_datastore_provider;
-public class DistributedDataStoreProviderModuleFactory extends org.opendaylight.controller.config.yang.config.distributed_datastore_provider.AbstractDistributedDataStoreProviderModuleFactory {
+public class DistributedConfigDataStoreProviderModuleFactory extends org.opendaylight.controller.config.yang.config.distributed_datastore_provider.AbstractDistributedConfigDataStoreProviderModuleFactory {
 
 }
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedDataStoreProviderModule.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedDataStoreProviderModule.java
deleted file mode 100644 (file)
index 241bcb0..0000000
+++ /dev/null
@@ -1,34 +0,0 @@
-package org.opendaylight.controller.config.yang.config.distributed_datastore_provider;
-
-import org.opendaylight.controller.cluster.datastore.DistributedDataStore;
-
-public class DistributedDataStoreProviderModule extends org.opendaylight.controller.config.yang.config.distributed_datastore_provider.AbstractDistributedDataStoreProviderModule {
-    public DistributedDataStoreProviderModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
-        super(identifier, dependencyResolver);
-    }
-
-    public DistributedDataStoreProviderModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.controller.config.yang.config.distributed_datastore_provider.DistributedDataStoreProviderModule oldModule, java.lang.AutoCloseable oldInstance) {
-        super(identifier, dependencyResolver, oldModule, oldInstance);
-    }
-
-    @Override
-    public void customValidation() {
-        // add custom validation form module attributes here.
-    }
-
-    @Override
-    public java.lang.AutoCloseable createInstance() {
-        new DistributedDataStore();
-
-        final class AutoCloseableDistributedDataStore implements AutoCloseable {
-
-            @Override
-            public void close() throws Exception {
-
-            }
-        }
-
-        return new AutoCloseableDistributedDataStore();
-    }
-
-}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedOperationalDataStoreProviderModule.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedOperationalDataStoreProviderModule.java
new file mode 100644 (file)
index 0000000..1a06629
--- /dev/null
@@ -0,0 +1,32 @@
+package org.opendaylight.controller.config.yang.config.distributed_datastore_provider;
+
+import org.opendaylight.controller.cluster.datastore.DistributedDataStoreFactory;
+
+public class DistributedOperationalDataStoreProviderModule extends
+    org.opendaylight.controller.config.yang.config.distributed_datastore_provider.AbstractDistributedOperationalDataStoreProviderModule {
+    public DistributedOperationalDataStoreProviderModule(
+        org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+        org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
+        super(identifier, dependencyResolver);
+    }
+
+    public DistributedOperationalDataStoreProviderModule(
+        org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+        org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,
+        org.opendaylight.controller.config.yang.config.distributed_datastore_provider.DistributedOperationalDataStoreProviderModule oldModule,
+        java.lang.AutoCloseable oldInstance) {
+        super(identifier, dependencyResolver, oldModule, oldInstance);
+    }
+
+    @Override
+    public void customValidation() {
+        // add custom validation form module attributes here.
+    }
+
+    @Override
+    public java.lang.AutoCloseable createInstance() {
+        return DistributedDataStoreFactory
+            .createInstance("operational", getSchemaServiceDependency());
+    }
+
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedOperationalDataStoreProviderModuleFactory.java b/opendaylight/md-sal/sal-distributed-datastore/src/main/java/org/opendaylight/controller/config/yang/config/distributed_datastore_provider/DistributedOperationalDataStoreProviderModuleFactory.java
new file mode 100644 (file)
index 0000000..c9965fe
--- /dev/null
@@ -0,0 +1,13 @@
+/*
+* Generated file
+*
+* Generated from: yang module name: distributed-datastore-provider yang module local name: distributed-operational-datastore-provider
+* Generated by: org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator
+* Generated at: Tue Jun 24 17:14:50 PDT 2014
+*
+* Do not modify this file unless it is present under src/main directory
+*/
+package org.opendaylight.controller.config.yang.config.distributed_datastore_provider;
+public class DistributedOperationalDataStoreProviderModuleFactory extends org.opendaylight.controller.config.yang.config.distributed_datastore_provider.AbstractDistributedOperationalDataStoreProviderModuleFactory {
+
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/main/resources/application.conf b/opendaylight/md-sal/sal-distributed-datastore/src/main/resources/application.conf
new file mode 100644 (file)
index 0000000..b56c26b
--- /dev/null
@@ -0,0 +1,3 @@
+ODLCluster{
+
+}
\ No newline at end of file
index 0471bc806e00d65e973432b4faa7dea90e593516..5d3758986c40fc8858005aad29cf74f85c9af857 100644 (file)
@@ -7,6 +7,9 @@ module distributed-datastore-provider {
 
     import config { prefix config; revision-date 2013-04-05; }
     import rpc-context { prefix rpcx; revision-date 2013-06-17; }
+    import opendaylight-config-dom-datastore {prefix config-dom-store-spi;}
+    import opendaylight-operational-dom-datastore {prefix operational-dom-store-spi;}
+    import opendaylight-md-sal-dom {prefix sal;}
 
     description
         "This module contains the base YANG definitions for
@@ -18,17 +21,48 @@ module distributed-datastore-provider {
     }
 
     // This is the definition of the service implementation as a module identity.
-    identity distributed-datastore-provider {
+    identity distributed-config-datastore-provider {
             base config:module-type;
-
+            config:provided-service config-dom-store-spi:config-dom-datastore;
             // Specifies the prefix for generated java classes.
-            config:java-name-prefix DistributedDataStoreProvider;
+            config:java-name-prefix DistributedConfigDataStoreProvider;
     }
 
+     // This is the definition of the service implementation as a module identity.
+     identity distributed-operational-datastore-provider {
+                base config:module-type;
+                config:provided-service operational-dom-store-spi:operational-dom-datastore;
+                // Specifies the prefix for generated java classes.
+                config:java-name-prefix DistributedOperationalDataStoreProvider;
+     }
+
     // Augments the 'configuration' choice node under modules/module.
     augment "/config:modules/config:module/config:configuration" {
-        case distributed-datastore-provider {
-            when "/config:modules/config:module/config:type = 'distributed-datastore-provider'";
+        case distributed-config-datastore-provider {
+            when "/config:modules/config:module/config:type = 'distributed-config-datastore-provider'";
+            container schema-service {
+                          uses config:service-ref {
+                               refine type {
+                                      mandatory false;
+                                      config:required-identity sal:schema-service;
+                                }
+                          }
+                        }
         }
     }
+
+    // Augments the 'configuration' choice node under modules/module.
+        augment "/config:modules/config:module/config:configuration" {
+            case distributed-operational-datastore-provider {
+                when "/config:modules/config:module/config:type = 'distributed-operational-datastore-provider'";
+                container schema-service {
+                              uses config:service-ref {
+                                   refine type {
+                                          mandatory false;
+                                          config:required-identity sal:schema-service;
+                                    }
+                              }
+                            }
+            }
+        }
 }
index 2fe7b69cc9b349548f9b44ea36f5d9a9adf1bc2c..214b3e9d3d989d73d0cd618db937a0fa6bcfdcb6 100644 (file)
@@ -14,21 +14,22 @@ import org.junit.AfterClass;
 import org.junit.BeforeClass;
 
 public abstract class AbstractActorTest {
-  private static ActorSystem system;
+    private static ActorSystem system;
 
-  @BeforeClass
-  public static void setUp(){
-    system = ActorSystem.create("test");
-  }
+    @BeforeClass
+    public static void setUpClass() {
+        System.setProperty("shard.persistent", "false");
+        system = ActorSystem.create("test");
+    }
 
-  @AfterClass
-  public static void tearDown(){
-    JavaTestKit.shutdownActorSystem(system);
-    system = null;
-  }
+    @AfterClass
+    public static void tearDownClass() {
+        JavaTestKit.shutdownActorSystem(system);
+        system = null;
+    }
 
-  protected ActorSystem getSystem(){
-    return system;
-  }
+    protected ActorSystem getSystem() {
+        return system;
+    }
 
 }
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/BasicIntegrationTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/BasicIntegrationTest.java
new file mode 100644 (file)
index 0000000..dfefc5e
--- /dev/null
@@ -0,0 +1,227 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.cluster.datastore;
+
+import akka.actor.ActorPath;
+import akka.actor.ActorRef;
+import akka.actor.ActorSelection;
+import akka.actor.Props;
+import akka.actor.Terminated;
+import akka.testkit.JavaTestKit;
+import junit.framework.Assert;
+import org.junit.Test;
+import org.opendaylight.controller.cluster.datastore.messages.CommitTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionChain;
+import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionChainReply;
+import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.PreCommitTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.PreCommitTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.ReadyTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
+import org.opendaylight.controller.cluster.datastore.messages.WriteData;
+import org.opendaylight.controller.cluster.datastore.messages.WriteDataReply;
+import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
+import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import scala.concurrent.Await;
+import scala.concurrent.Future;
+import scala.concurrent.duration.FiniteDuration;
+
+public class BasicIntegrationTest extends AbstractActorTest {
+
+    @Test
+    public void integrationTest() throws Exception{
+        // This test will
+        // - create a Shard
+        // - initiate a transaction
+        // - write something
+        // - read the transaction for commit
+        // - commit the transaction
+
+
+        new JavaTestKit(getSystem()) {{
+            final Props props = Shard.props("config");
+            final ActorRef shard = getSystem().actorOf(props);
+
+            new Within(duration("5 seconds")) {
+                protected void run() {
+
+                    shard.tell(
+                        new UpdateSchemaContext(TestModel.createTestContext()),
+                        getRef());
+
+                    shard.tell(new CreateTransactionChain(), getRef());
+
+                    final ActorSelection transactionChain =
+                        new ExpectMsg<ActorSelection>("CreateTransactionChainReply") {
+                            protected ActorSelection match(Object in) {
+                                if (in instanceof CreateTransactionChainReply) {
+                                    ActorPath transactionChainPath =
+                                        ((CreateTransactionChainReply) in)
+                                            .getTransactionChainPath();
+                                    return getSystem()
+                                        .actorSelection(transactionChainPath);
+                                } else {
+                                    throw noMatch();
+                                }
+                            }
+                        }.get(); // this extracts the received message
+
+                    Assert.assertNotNull(transactionChain);
+
+                    transactionChain.tell(new CreateTransaction("txn-1"), getRef());
+
+                    final ActorSelection transaction =
+                        new ExpectMsg<ActorSelection>("CreateTransactionReply") {
+                            protected ActorSelection match(Object in) {
+                                if (in instanceof CreateTransactionReply) {
+                                    ActorPath transactionPath =
+                                        ((CreateTransactionReply) in)
+                                            .getTransactionPath();
+                                    return getSystem()
+                                        .actorSelection(transactionPath);
+                                } else {
+                                    throw noMatch();
+                                }
+                            }
+                        }.get(); // this extracts the received message
+
+                    Assert.assertNotNull(transaction);
+
+                    // Add a watch on the transaction actor so that we are notified when it dies
+                    final ActorRef transactionActorRef = watchActor(transaction);
+
+                    transaction.tell(new WriteData(TestModel.TEST_PATH,
+                        ImmutableNodes.containerNode(TestModel.TEST_QNAME)),
+                        getRef());
+
+                    Boolean writeDone = new ExpectMsg<Boolean>("WriteDataReply") {
+                        protected Boolean match(Object in) {
+                            if (in instanceof WriteDataReply) {
+                                return true;
+                            } else {
+                                throw noMatch();
+                            }
+                        }
+                    }.get(); // this extracts the received message
+
+                    Assert.assertTrue(writeDone);
+
+                    transaction.tell(new ReadyTransaction(), getRef());
+
+                    final ActorSelection cohort =
+                        new ExpectMsg<ActorSelection>("ReadyTransactionReply") {
+                            protected ActorSelection match(Object in) {
+                                if (in instanceof ReadyTransactionReply) {
+                                    ActorPath cohortPath =
+                                        ((ReadyTransactionReply) in)
+                                            .getCohortPath();
+                                    return getSystem()
+                                        .actorSelection(cohortPath);
+                                } else {
+                                    throw noMatch();
+                                }
+                            }
+                        }.get(); // this extracts the received message
+
+                    Assert.assertNotNull(cohort);
+
+                    // Add a watch on the transaction actor so that we are notified when it dies
+                    final ActorRef cohorActorRef = watchActor(cohort);
+
+                    cohort.tell(new PreCommitTransaction(), getRef());
+
+                    Boolean preCommitDone =
+                        new ExpectMsg<Boolean>("PreCommitTransactionReply") {
+                            protected Boolean match(Object in) {
+                                if (in instanceof PreCommitTransactionReply) {
+                                    return true;
+                                } else {
+                                    throw noMatch();
+                                }
+                            }
+                        }.get(); // this extracts the received message
+
+                    Assert.assertTrue(preCommitDone);
+
+                    // FIXME : When we commit on the cohort it "kills" the Transaction.
+                    // This in turn kills the child of Transaction as well.
+                    // The order in which we receive the terminated event for both
+                    // these actors is not fixed which may cause this test to fail
+                    cohort.tell(new CommitTransaction(), getRef());
+
+                    final Boolean terminatedCohort =
+                        new ExpectMsg<Boolean>("Terminated Cohort") {
+                            protected Boolean match(Object in) {
+                                if (in instanceof Terminated) {
+                                    return cohorActorRef.equals(((Terminated) in).actor());
+                                } else {
+                                    throw noMatch();
+                                }
+                            }
+                        }.get(); // this extracts the received message
+
+                    Assert.assertTrue(terminatedCohort);
+
+
+                    final Boolean terminatedTransaction =
+                        new ExpectMsg<Boolean>("Terminated Transaction") {
+                            protected Boolean match(Object in) {
+                                if (in instanceof Terminated) {
+                                    return transactionActorRef.equals(((Terminated) in).actor());
+                                } else {
+                                    throw noMatch();
+                                }
+                            }
+                        }.get(); // this extracts the received message
+
+                    Assert.assertTrue(terminatedTransaction);
+
+                    final Boolean commitDone =
+                        new ExpectMsg<Boolean>("CommitTransactionReply") {
+                            protected Boolean match(Object in) {
+                                if (in instanceof CommitTransactionReply) {
+                                    return true;
+                                } else {
+                                    throw noMatch();
+                                }
+                            }
+                        }.get(); // this extracts the received message
+
+                    Assert.assertTrue(commitDone);
+
+                }
+
+
+            };
+        }
+
+            private ActorRef watchActor(ActorSelection actor) {
+                Future<ActorRef> future = actor
+                    .resolveOne(FiniteDuration.apply(100, "milliseconds"));
+
+                try {
+                    ActorRef actorRef = Await.result(future,
+                        FiniteDuration.apply(100, "milliseconds"));
+
+                    watch(actorRef);
+
+                    return actorRef;
+                } catch (Exception e) {
+                    throw new RuntimeException(e);
+                }
+
+            }
+        };
+
+
+    }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerProxyTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerProxyTest.java
new file mode 100644 (file)
index 0000000..a8409a6
--- /dev/null
@@ -0,0 +1,81 @@
+package org.opendaylight.controller.cluster.datastore;
+
+import akka.actor.ActorRef;
+import akka.actor.Props;
+import junit.framework.Assert;
+import org.junit.Test;
+import org.opendaylight.controller.cluster.datastore.messages.DataChanged;
+import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
+import org.opendaylight.controller.cluster.datastore.utils.DoNothingActor;
+import org.opendaylight.controller.cluster.datastore.utils.MessageCollectorActor;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+public class DataChangeListenerProxyTest extends AbstractActorTest {
+
+    private static class MockDataChangeEvent implements
+        AsyncDataChangeEvent<InstanceIdentifier,NormalizedNode<?,?>> {
+
+        @Override
+        public Map<InstanceIdentifier, NormalizedNode<?, ?>> getCreatedData() {
+            throw new UnsupportedOperationException("getCreatedData");
+        }
+
+        @Override
+        public Map<InstanceIdentifier, NormalizedNode<?, ?>> getUpdatedData() {
+            throw new UnsupportedOperationException("getUpdatedData");
+        }
+
+        @Override public Set<InstanceIdentifier> getRemovedPaths() {
+            throw new UnsupportedOperationException("getRemovedPaths");
+        }
+
+        @Override
+        public Map<InstanceIdentifier, ? extends NormalizedNode<?, ?>> getOriginalData() {
+            throw new UnsupportedOperationException("getOriginalData");
+        }
+
+        @Override public NormalizedNode<?, ?> getOriginalSubtree() {
+            throw new UnsupportedOperationException("getOriginalSubtree");
+        }
+
+        @Override public NormalizedNode<?, ?> getUpdatedSubtree() {
+            throw new UnsupportedOperationException("getUpdatedSubtree");
+        }
+    }
+
+    @Test
+    public void testOnDataChanged() throws Exception {
+        final Props props = Props.create(MessageCollectorActor.class);
+        final ActorRef actorRef = getSystem().actorOf(props);
+
+        DataChangeListenerProxy dataChangeListenerProxy =
+            new DataChangeListenerProxy(
+                getSystem().actorSelection(actorRef.path()));
+
+        dataChangeListenerProxy.onDataChanged(new MockDataChangeEvent());
+
+        //Check if it was received by the remote actor
+        ActorContext
+            testContext = new ActorContext(getSystem(), getSystem().actorOf(Props.create(DoNothingActor.class)));
+        Object messages = testContext
+            .executeLocalOperation(actorRef, "messages",
+                ActorContext.ASK_DURATION);
+
+        Assert.assertNotNull(messages);
+
+        Assert.assertTrue(messages instanceof List);
+
+        List<Object> listMessages = (List<Object>) messages;
+
+        Assert.assertEquals(1, listMessages.size());
+
+        Assert.assertTrue(listMessages.get(0) instanceof DataChanged);
+
+    }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistrationProxyTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerRegistrationProxyTest.java
new file mode 100644 (file)
index 0000000..33b5d95
--- /dev/null
@@ -0,0 +1,76 @@
+package org.opendaylight.controller.cluster.datastore;
+
+import akka.actor.ActorRef;
+import akka.actor.Props;
+import junit.framework.Assert;
+import org.junit.Test;
+import org.opendaylight.controller.cluster.datastore.messages.CloseDataChangeListenerRegistration;
+import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
+import org.opendaylight.controller.cluster.datastore.utils.DoNothingActor;
+import org.opendaylight.controller.cluster.datastore.utils.MessageCollectorActor;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+import java.util.List;
+
+public class DataChangeListenerRegistrationProxyTest extends AbstractActorTest{
+
+    private ActorRef dataChangeListenerActor = getSystem().actorOf(Props.create(DoNothingActor.class));
+
+    private static class MockDataChangeListener implements
+        AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>> {
+
+        @Override public void onDataChanged(
+            AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change) {
+            throw new UnsupportedOperationException("onDataChanged");
+        }
+    }
+
+    @Test
+    public void testGetInstance() throws Exception {
+        final Props props = Props.create(MessageCollectorActor.class);
+        final ActorRef actorRef = getSystem().actorOf(props);
+
+        MockDataChangeListener listener =
+            new MockDataChangeListener();
+        DataChangeListenerRegistrationProxy proxy =
+            new DataChangeListenerRegistrationProxy(
+                getSystem().actorSelection(actorRef.path()),
+                listener, dataChangeListenerActor);
+
+        Assert.assertEquals(listener, proxy.getInstance());
+
+    }
+
+    @Test
+    public void testClose() throws Exception {
+        final Props props = Props.create(MessageCollectorActor.class);
+        final ActorRef actorRef = getSystem().actorOf(props);
+
+        DataChangeListenerRegistrationProxy proxy =
+            new DataChangeListenerRegistrationProxy(
+                getSystem().actorSelection(actorRef.path()),
+                new MockDataChangeListener(), dataChangeListenerActor);
+
+        proxy.close();
+
+        //Check if it was received by the remote actor
+        ActorContext
+            testContext = new ActorContext(getSystem(), getSystem().actorOf(Props.create(DoNothingActor.class)));
+        Object messages = testContext
+            .executeLocalOperation(actorRef, "messages",
+                ActorContext.ASK_DURATION);
+
+        Assert.assertNotNull(messages);
+
+        Assert.assertTrue(messages instanceof List);
+
+        List<Object> listMessages = (List<Object>) messages;
+
+        Assert.assertEquals(1, listMessages.size());
+
+        Assert.assertTrue(listMessages.get(0) instanceof CloseDataChangeListenerRegistration);
+    }
+}
@@ -6,8 +6,8 @@ import akka.testkit.JavaTestKit;
 import com.google.common.util.concurrent.ListeningExecutorService;
 import com.google.common.util.concurrent.MoreExecutors;
 import org.junit.Test;
-import org.opendaylight.controller.cluster.datastore.messages.CloseListenerRegistration;
-import org.opendaylight.controller.cluster.datastore.messages.CloseListenerRegistrationReply;
+import org.opendaylight.controller.cluster.datastore.messages.CloseDataChangeListenerRegistration;
+import org.opendaylight.controller.cluster.datastore.messages.CloseDataChangeListenerRegistrationReply;
 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
@@ -18,7 +18,7 @@ import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 
 import static org.junit.Assert.assertEquals;
 
-public class ListenerRegistrationTest extends AbstractActorTest {
+public class DataChangeListenerRegistrationTest extends AbstractActorTest {
   private static ListeningExecutorService storeExecutor = MoreExecutors.listeningDecorator(MoreExecutors.sameThreadExecutor());
 
   private static final InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER", storeExecutor);
@@ -31,18 +31,20 @@ public class ListenerRegistrationTest extends AbstractActorTest {
   @Test
   public void testOnReceiveCloseListenerRegistration() throws Exception {
     new JavaTestKit(getSystem()) {{
-      final Props props = ListenerRegistration.props(store.registerChangeListener(TestModel.TEST_PATH, noOpDataChangeListener(), AsyncDataBroker.DataChangeScope.BASE));
+      final Props props = DataChangeListenerRegistration.props(store
+          .registerChangeListener(TestModel.TEST_PATH, noOpDataChangeListener(),
+              AsyncDataBroker.DataChangeScope.BASE));
       final ActorRef subject = getSystem().actorOf(props, "testCloseListenerRegistration");
 
       new Within(duration("1 seconds")) {
         protected void run() {
 
-          subject.tell(new CloseListenerRegistration(), getRef());
+          subject.tell(new CloseDataChangeListenerRegistration(), getRef());
 
           final String out = new ExpectMsg<String>("match hint") {
             // do not put code outside this method, will run afterwards
             protected String match(Object in) {
-              if (in instanceof CloseListenerRegistrationReply) {
+              if (in instanceof CloseDataChangeListenerRegistrationReply) {
                 return "match";
               } else {
                 throw noMatch();
@@ -69,4 +71,4 @@ public class ListenerRegistrationTest extends AbstractActorTest {
     };
   }
 
-}
\ No newline at end of file
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DataChangeListenerTest.java
new file mode 100644 (file)
index 0000000..6f0816b
--- /dev/null
@@ -0,0 +1,102 @@
+package org.opendaylight.controller.cluster.datastore;
+
+import akka.actor.ActorRef;
+import akka.actor.Props;
+import akka.testkit.JavaTestKit;
+import org.junit.Test;
+import org.opendaylight.controller.cluster.datastore.messages.DataChanged;
+import org.opendaylight.controller.cluster.datastore.messages.DataChangedReply;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+import java.util.Map;
+import java.util.Set;
+
+import static org.junit.Assert.assertTrue;
+
+public class DataChangeListenerTest extends AbstractActorTest {
+
+    private static class MockDataChangedEvent implements AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> {
+
+        @Override
+        public Map<InstanceIdentifier, NormalizedNode<?, ?>> getCreatedData() {
+            throw new UnsupportedOperationException("getCreatedData");
+        }
+
+        @Override
+        public Map<InstanceIdentifier, NormalizedNode<?, ?>> getUpdatedData() {
+            throw new UnsupportedOperationException("getUpdatedData");
+        }
+
+        @Override public Set<InstanceIdentifier> getRemovedPaths() {
+            throw new UnsupportedOperationException("getRemovedPaths");
+        }
+
+        @Override
+        public Map<InstanceIdentifier, ? extends NormalizedNode<?, ?>> getOriginalData() {
+            throw new UnsupportedOperationException("getOriginalData");
+        }
+
+        @Override public NormalizedNode<?, ?> getOriginalSubtree() {
+            throw new UnsupportedOperationException("getOriginalSubtree");
+        }
+
+        @Override public NormalizedNode<?, ?> getUpdatedSubtree() {
+            throw new UnsupportedOperationException("getUpdatedSubtree");
+        }
+    }
+
+    private class MockDataChangeListener implements AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>> {
+        private boolean gotIt = false;
+
+        @Override public void onDataChanged(
+            AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change) {
+            gotIt = true;
+        }
+
+        public boolean gotIt() {
+            return gotIt;
+        }
+    }
+
+    @Test
+    public void testDataChanged(){
+        new JavaTestKit(getSystem()) {{
+            final MockDataChangeListener listener = new MockDataChangeListener();
+            final Props props = DataChangeListener.props(listener);
+            final ActorRef subject =
+                getSystem().actorOf(props, "testDataChanged");
+
+            new Within(duration("1 seconds")) {
+                protected void run() {
+
+                    subject.tell(
+                        new DataChanged(new MockDataChangedEvent()),
+                        getRef());
+
+                    final Boolean out = new ExpectMsg<Boolean>("dataChanged") {
+                        // do not put code outside this method, will run afterwards
+                        protected Boolean match(Object in) {
+                            if (in instanceof DataChangedReply) {
+                                DataChangedReply reply =
+                                    (DataChangedReply) in;
+                                return true;
+                            } else {
+                                throw noMatch();
+                            }
+                        }
+                    }.get(); // this extracts the received message
+
+                    assertTrue(out);
+                    assertTrue(listener.gotIt());
+                    // Will wait for the rest of the 3 seconds
+                    expectNoMsg();
+                }
+
+
+            };
+        }};
+    }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreIntegrationTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/DistributedDataStoreIntegrationTest.java
new file mode 100644 (file)
index 0000000..f400e74
--- /dev/null
@@ -0,0 +1,54 @@
+package org.opendaylight.controller.cluster.datastore;
+
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.ListenableFuture;
+import org.junit.Test;
+import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertTrue;
+
+public class DistributedDataStoreIntegrationTest extends AbstractActorTest {
+
+    @Test
+    public void integrationTest() throws Exception {
+        DistributedDataStore distributedDataStore =
+            new DistributedDataStore(getSystem(), "config");
+
+        distributedDataStore.onGlobalContextUpdated(TestModel.createTestContext());
+
+        DOMStoreReadWriteTransaction transaction =
+            distributedDataStore.newReadWriteTransaction();
+
+        transaction.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
+
+        ListenableFuture<Optional<NormalizedNode<?, ?>>> future =
+            transaction.read(TestModel.TEST_PATH);
+
+        Optional<NormalizedNode<?, ?>> optional = future.get();
+
+        NormalizedNode<?, ?> normalizedNode = optional.get();
+
+        assertEquals(TestModel.TEST_QNAME, normalizedNode.getNodeType());
+
+        DOMStoreThreePhaseCommitCohort ready = transaction.ready();
+
+        ListenableFuture<Boolean> canCommit = ready.canCommit();
+
+        assertTrue(canCommit.get());
+
+        ListenableFuture<Void> preCommit = ready.preCommit();
+
+        preCommit.get();
+
+        ListenableFuture<Void> commit = ready.commit();
+
+        commit.get();
+
+    }
+
+}
index 6544f3303022b698580d24f350073e5a79fa7b55..5f82b40140eb11074c03419121ebd511c08d59e4 100644 (file)
@@ -1,6 +1,13 @@
 package org.opendaylight.controller.cluster.datastore;
 
+import akka.actor.ActorRef;
+import akka.actor.Props;
 import junit.framework.Assert;
+import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
+import org.opendaylight.controller.cluster.datastore.utils.DoNothingActor;
+import org.opendaylight.controller.cluster.datastore.utils.MockActorContext;
+import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker;
 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
@@ -12,13 +19,27 @@ import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 
-public class DistributedDataStoreTest {
+public class DistributedDataStoreTest extends AbstractActorTest{
 
     private DistributedDataStore distributedDataStore;
+    private MockActorContext mockActorContext;
+    private ActorRef doNothingActorRef;
 
     @org.junit.Before
     public void setUp() throws Exception {
-        distributedDataStore = new DistributedDataStore();
+        final Props props = Props.create(DoNothingActor.class);
+
+        doNothingActorRef = getSystem().actorOf(props);
+
+        mockActorContext = new MockActorContext(getSystem(), doNothingActorRef);
+        distributedDataStore = new DistributedDataStore(mockActorContext, "config");
+        distributedDataStore.onGlobalContextUpdated(
+            TestModel.createTestContext());
+
+        // Make CreateTransactionReply as the default response. Will need to be
+        // tuned if a specific test requires some other response
+        mockActorContext.setExecuteShardOperationResponse(
+            new CreateTransactionReply(doNothingActorRef.path(), "txn-1 "));
     }
 
     @org.junit.After
@@ -28,8 +49,9 @@ public class DistributedDataStoreTest {
 
     @org.junit.Test
     public void testRegisterChangeListener() throws Exception {
+        mockActorContext.setExecuteShardOperationResponse(new RegisterChangeListenerReply(doNothingActorRef.path()));
         ListenerRegistration registration =
-                distributedDataStore.registerChangeListener(InstanceIdentifier.builder().build(), new AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>() {
+                distributedDataStore.registerChangeListener(TestModel.TEST_PATH, new AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>() {
             @Override
             public void onDataChanged(AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change) {
                 throw new UnsupportedOperationException("onDataChanged");
index 9c1ea70fdbc93a86e91b7ef2764392e23265aeba..fa436c16053bc42ad9835e7ecbccd1cb202fc4b8 100644 (file)
@@ -8,6 +8,7 @@ import org.junit.AfterClass;
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.cluster.datastore.messages.FindPrimary;
+import org.opendaylight.controller.cluster.datastore.messages.PrimaryFound;
 import org.opendaylight.controller.cluster.datastore.messages.PrimaryNotFound;
 import scala.concurrent.duration.Duration;
 
@@ -26,17 +27,13 @@ public class ShardManagerTest {
     }
 
     @Test
-    public void testOnReceiveFindPrimary() throws Exception {
+    public void testOnReceiveFindPrimaryForNonExistentShard() throws Exception {
 
         new JavaTestKit(system) {{
-            final Props props = Props.create(ShardManager.class);
-            final TestActorRef<ShardManager> subject = TestActorRef.create(system, props, "test");
+            final Props props = ShardManager.props("config");
+            final TestActorRef<ShardManager> subject = TestActorRef.create(system, props);
 
-            // can also use JavaTestKit “from the outside”
-            final JavaTestKit probe = new JavaTestKit(system);
-
-            // the run() method needs to finish within 3 seconds
-            new Within(duration("3 seconds")) {
+            new Within(duration("1 seconds")) {
                 protected void run() {
 
                     subject.tell(new FindPrimary("inventory"), getRef());
@@ -49,4 +46,25 @@ public class ShardManagerTest {
             };
         }};
     }
+
+  @Test
+  public void testOnReceiveFindPrimaryForExistentShard() throws Exception {
+
+    new JavaTestKit(system) {{
+      final Props props = ShardManager.props("config");
+      final TestActorRef<ShardManager> subject = TestActorRef.create(system, props);
+
+      // the run() method needs to finish within 3 seconds
+      new Within(duration("1 seconds")) {
+        protected void run() {
+
+          subject.tell(new FindPrimary(Shard.DEFAULT_NAME), getRef());
+
+          expectMsgClass(PrimaryFound.class);
+
+          expectNoMsg();
+        }
+      };
+    }};
+  }
 }
\ No newline at end of file
index b5a341d95c950dd859e755d135be2c3354388dbc..ed447e004fd9b91a7ad7da1561fdb83bf3cbb2d7 100644 (file)
@@ -4,8 +4,10 @@ import akka.actor.ActorRef;
 import akka.actor.Props;
 import akka.testkit.JavaTestKit;
 import org.junit.Test;
+import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionChain;
 import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionChainReply;
+import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListener;
 import org.opendaylight.controller.cluster.datastore.messages.RegisterChangeListenerReply;
 import org.opendaylight.controller.cluster.datastore.messages.UpdateSchemaContext;
@@ -16,83 +18,142 @@ import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListene
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 
+import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 
-public class ShardTest extends AbstractActorTest{
-  @Test
-  public void testOnReceiveCreateTransactionChain() throws Exception {
-    new JavaTestKit(getSystem()) {{
-      final Props props = Props.create(Shard.class);
-      final ActorRef subject = getSystem().actorOf(props, "testCreateTransactionChain");
-
-      new Within(duration("1 seconds")) {
-        protected void run() {
-
-          subject.tell(new CreateTransactionChain(), getRef());
-
-          final String out = new ExpectMsg<String>("match hint") {
-            // do not put code outside this method, will run afterwards
-            protected String match(Object in) {
-              if (in instanceof CreateTransactionChainReply) {
-                CreateTransactionChainReply reply = (CreateTransactionChainReply) in;
-                return reply.getTransactionChainPath().toString();
-              } else {
-                throw noMatch();
-              }
-            }
-          }.get(); // this extracts the received message
-
-          assertTrue(out.matches("akka:\\/\\/test\\/user\\/testCreateTransactionChain\\/\\$.*"));
-          // Will wait for the rest of the 3 seconds
-          expectNoMsg();
-        }
-
-
-      };
-    }};
-  }
-
-  @Test
-  public void testOnReceiveRegisterListener() throws Exception {
-    new JavaTestKit(getSystem()) {{
-      final Props props = Props.create(Shard.class);
-      final ActorRef subject = getSystem().actorOf(props, "testRegisterChangeListener");
-
-      new Within(duration("1 seconds")) {
-        protected void run() {
-
-          subject.tell(new UpdateSchemaContext(TestModel.createTestContext()), getRef());
+public class ShardTest extends AbstractActorTest {
+    @Test
+    public void testOnReceiveCreateTransactionChain() throws Exception {
+        new JavaTestKit(getSystem()) {{
+            final Props props = Shard.props("config");
+            final ActorRef subject =
+                getSystem().actorOf(props, "testCreateTransactionChain");
+
+            new Within(duration("1 seconds")) {
+                protected void run() {
+
+                    subject.tell(new CreateTransactionChain(), getRef());
+
+                    final String out = new ExpectMsg<String>("match hint") {
+                        // do not put code outside this method, will run afterwards
+                        protected String match(Object in) {
+                            if (in instanceof CreateTransactionChainReply) {
+                                CreateTransactionChainReply reply =
+                                    (CreateTransactionChainReply) in;
+                                return reply.getTransactionChainPath()
+                                    .toString();
+                            } else {
+                                throw noMatch();
+                            }
+                        }
+                    }.get(); // this extracts the received message
+
+                    assertEquals("Unexpected transaction path " + out,
+                        "akka://test/user/testCreateTransactionChain/$a",
+                        out);
+
+                    expectNoMsg();
+                }
+
+
+            };
+        }};
+    }
+
+    @Test
+    public void testOnReceiveRegisterListener() throws Exception {
+        new JavaTestKit(getSystem()) {{
+            final Props props = Shard.props("config");
+            final ActorRef subject =
+                getSystem().actorOf(props, "testRegisterChangeListener");
+
+            new Within(duration("1 seconds")) {
+                protected void run() {
+
+                    subject.tell(
+                        new UpdateSchemaContext(TestModel.createTestContext()),
+                        getRef());
+
+                    subject.tell(new RegisterChangeListener(TestModel.TEST_PATH,
+                        getRef().path(), AsyncDataBroker.DataChangeScope.BASE),
+                        getRef());
+
+                    final String out = new ExpectMsg<String>("match hint") {
+                        // do not put code outside this method, will run afterwards
+                        protected String match(Object in) {
+                            if (in instanceof RegisterChangeListenerReply) {
+                                RegisterChangeListenerReply reply =
+                                    (RegisterChangeListenerReply) in;
+                                return reply.getListenerRegistrationPath()
+                                    .toString();
+                            } else {
+                                throw noMatch();
+                            }
+                        }
+                    }.get(); // this extracts the received message
+
+                    assertTrue(out.matches(
+                        "akka:\\/\\/test\\/user\\/testRegisterChangeListener\\/\\$.*"));
+                    // Will wait for the rest of the 3 seconds
+                    expectNoMsg();
+                }
+
+
+            };
+        }};
+    }
+
+    @Test
+    public void testCreateTransaction(){
+        new JavaTestKit(getSystem()) {{
+            final Props props = Shard.props("config");
+            final ActorRef subject =
+                getSystem().actorOf(props, "testCreateTransaction");
+
+            new Within(duration("1 seconds")) {
+                protected void run() {
+
+                    subject.tell(
+                        new UpdateSchemaContext(TestModel.createTestContext()),
+                        getRef());
+
+                    subject.tell(new CreateTransaction("txn-1"),
+                        getRef());
+
+                    final String out = new ExpectMsg<String>("match hint") {
+                        // do not put code outside this method, will run afterwards
+                        protected String match(Object in) {
+                            if (in instanceof CreateTransactionReply) {
+                                CreateTransactionReply reply =
+                                    (CreateTransactionReply) in;
+                                return reply.getTransactionPath()
+                                    .toString();
+                            } else {
+                                throw noMatch();
+                            }
+                        }
+                    }.get(); // this extracts the received message
+
+                    assertEquals("Unexpected transaction path " + out,
+                        "akka://test/user/testCreateTransaction/shard-txn-1",
+                        out);
+                    expectNoMsg();
+                }
+
+
+            };
+        }};
+    }
+
+
+
+    private AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>> noOpDataChangeListener() {
+        return new AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>() {
+            @Override
+            public void onDataChanged(
+                AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change) {
 
-          subject.tell(new RegisterChangeListener(InstanceIdentifier.builder().build(), noOpDataChangeListener() , AsyncDataBroker.DataChangeScope.BASE), getRef());
-
-          final String out = new ExpectMsg<String>("match hint") {
-            // do not put code outside this method, will run afterwards
-            protected String match(Object in) {
-              if (in instanceof RegisterChangeListenerReply) {
-                RegisterChangeListenerReply reply = (RegisterChangeListenerReply) in;
-                return reply.getListenerRegistrationPath().toString();
-              } else {
-                throw noMatch();
-              }
             }
-          }.get(); // this extracts the received message
-
-          assertTrue(out.matches("akka:\\/\\/test\\/user\\/testRegisterChangeListener\\/\\$.*"));
-          // Will wait for the rest of the 3 seconds
-          expectNoMsg();
-        }
-
-
-      };
-    }};
-  }
-
-  private  AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>> noOpDataChangeListener(){
-    return new AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>>() {
-      @Override
-      public void onDataChanged(AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change) {
-
-      }
-    };
-  }
-}
\ No newline at end of file
+        };
+    }
+}
index bc3a1046566b2259012916c85e70ae933d921b3d..b07cbfd87ce268e3707064d81c2c5596af683af5 100644 (file)
@@ -14,7 +14,6 @@ import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
 
 import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
 
 public class ShardTransactionChainTest extends AbstractActorTest {
 
@@ -34,7 +33,7 @@ public class ShardTransactionChainTest extends AbstractActorTest {
       new Within(duration("1 seconds")) {
         protected void run() {
 
-          subject.tell(new CreateTransaction(), getRef());
+          subject.tell(new CreateTransaction("txn-1"), getRef());
 
           final String out = new ExpectMsg<String>("match hint") {
             // do not put code outside this method, will run afterwards
@@ -47,8 +46,11 @@ public class ShardTransactionChainTest extends AbstractActorTest {
             }
           }.get(); // this extracts the received message
 
-          assertTrue(out.matches("akka:\\/\\/test\\/user\\/testCreateTransaction\\/\\$.*"));
-          // Will wait for the rest of the 3 seconds
+            assertEquals("Unexpected transaction path " + out,
+                "akka://test/user/testCreateTransaction/shard-txn-1",
+                out);
+
+            // Will wait for the rest of the 3 seconds
           expectNoMsg();
         }
 
@@ -88,4 +90,4 @@ public class ShardTransactionChainTest extends AbstractActorTest {
       };
     }};
   }
-}
\ No newline at end of file
+}
index 36633c55d590c023651a39e82feef8ba48d780d5..2d9ae93d9ee1d044b2809996b88d1183c16672f8 100644 (file)
@@ -2,6 +2,7 @@ package org.opendaylight.controller.cluster.datastore;
 
 import akka.actor.ActorRef;
 import akka.actor.Props;
+import akka.actor.Terminated;
 import akka.testkit.JavaTestKit;
 import com.google.common.util.concurrent.ListeningExecutorService;
 import com.google.common.util.concurrent.MoreExecutors;
@@ -18,219 +19,340 @@ import org.opendaylight.controller.cluster.datastore.messages.ReadyTransaction;
 import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
 import org.opendaylight.controller.cluster.datastore.messages.WriteData;
 import org.opendaylight.controller.cluster.datastore.messages.WriteDataReply;
+import org.opendaylight.controller.cluster.datastore.modification.CompositeModification;
+import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
+import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
+import org.opendaylight.controller.cluster.datastore.modification.Modification;
+import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
 import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
 
 public class ShardTransactionTest extends AbstractActorTest {
-  private static ListeningExecutorService storeExecutor = MoreExecutors.listeningDecorator(MoreExecutors.sameThreadExecutor());
-
-  private static final InMemoryDOMDataStore store = new InMemoryDOMDataStore("OPER", storeExecutor);
-
-  static {
-    store.onGlobalContextUpdated(TestModel.createTestContext());
-  }
-
-  @Test
-  public void testOnReceiveReadData() throws Exception {
-    new JavaTestKit(getSystem()) {{
-      final Props props = ShardTransaction.props(store.newReadWriteTransaction());
-      final ActorRef subject = getSystem().actorOf(props, "testReadData");
-
-      new Within(duration("1 seconds")) {
-        protected void run() {
-
-          subject.tell(new ReadData(InstanceIdentifier.builder().build()), getRef());
-
-          final String out = new ExpectMsg<String>("match hint") {
-            // do not put code outside this method, will run afterwards
-            protected String match(Object in) {
-              if (in instanceof ReadDataReply) {
-                if (((ReadDataReply) in).getNormalizedNode() != null) {
-                  return "match";
+    private static ListeningExecutorService storeExecutor =
+        MoreExecutors.listeningDecorator(MoreExecutors.sameThreadExecutor());
+
+    private static final InMemoryDOMDataStore store =
+        new InMemoryDOMDataStore("OPER", storeExecutor);
+
+    static {
+        store.onGlobalContextUpdated(TestModel.createTestContext());
+    }
+
+    @Test
+    public void testOnReceiveReadData() throws Exception {
+        new JavaTestKit(getSystem()) {{
+            final ActorRef shard = getSystem().actorOf(Shard.props("config"));
+            final Props props =
+                ShardTransaction.props(store.newReadWriteTransaction(), shard);
+            final ActorRef subject = getSystem().actorOf(props, "testReadData");
+
+            new Within(duration("1 seconds")) {
+                protected void run() {
+
+                    subject.tell(
+                        new ReadData(InstanceIdentifier.builder().build()),
+                        getRef());
+
+                    final String out = new ExpectMsg<String>("match hint") {
+                        // do not put code outside this method, will run afterwards
+                        protected String match(Object in) {
+                            if (in instanceof ReadDataReply) {
+                                if (((ReadDataReply) in).getNormalizedNode()
+                                    != null) {
+                                    return "match";
+                                }
+                                return null;
+                            } else {
+                                throw noMatch();
+                            }
+                        }
+                    }.get(); // this extracts the received message
+
+                    assertEquals("match", out);
+
+                    expectNoMsg();
                 }
-                return null;
-              } else {
-                throw noMatch();
-              }
-            }
-          }.get(); // this extracts the received message
-
-          assertEquals("match", out);
-
-          expectNoMsg();
-        }
 
 
-      };
-    }};
-  }
-
-  @Test
-  public void testOnReceiveWriteData() throws Exception {
-    new JavaTestKit(getSystem()) {{
-      final Props props = ShardTransaction.props(store.newReadWriteTransaction());
-      final ActorRef subject = getSystem().actorOf(props, "testWriteData");
+            };
+        }};
+    }
+
+    @Test
+    public void testOnReceiveReadDataWhenDataNotFound() throws Exception {
+        new JavaTestKit(getSystem()) {{
+            final ActorRef shard = getSystem().actorOf(Shard.props("config"));
+            final Props props =
+                ShardTransaction.props(store.newReadWriteTransaction(), shard);
+            final ActorRef subject = getSystem().actorOf(props, "testReadDataWhenDataNotFound");
+
+            new Within(duration("1 seconds")) {
+                protected void run() {
+
+                    subject.tell(
+                        new ReadData(TestModel.TEST_PATH),
+                        getRef());
+
+                    final String out = new ExpectMsg<String>("match hint") {
+                        // do not put code outside this method, will run afterwards
+                        protected String match(Object in) {
+                            if (in instanceof ReadDataReply) {
+                                if (((ReadDataReply) in).getNormalizedNode()
+                                    == null) {
+                                    return "match";
+                                }
+                                return null;
+                            } else {
+                                throw noMatch();
+                            }
+                        }
+                    }.get(); // this extracts the received message
+
+                    assertEquals("match", out);
+
+                    expectNoMsg();
+                }
 
-      new Within(duration("1 seconds")) {
-        protected void run() {
 
-          subject.tell(new WriteData(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME)), getRef());
+            };
+        }};
+    }
+
+    private void assertModification(final ActorRef subject,
+        final Class<? extends Modification> modificationType) {
+        new JavaTestKit(getSystem()) {{
+            new Within(duration("1 seconds")) {
+                protected void run() {
+                    subject
+                        .tell(new ShardTransaction.GetCompositedModification(),
+                            getRef());
+
+                    final CompositeModification compositeModification =
+                        new ExpectMsg<CompositeModification>("match hint") {
+                            // do not put code outside this method, will run afterwards
+                            protected CompositeModification match(Object in) {
+                                if (in instanceof ShardTransaction.GetCompositeModificationReply) {
+                                    return ((ShardTransaction.GetCompositeModificationReply) in)
+                                        .getModification();
+                                } else {
+                                    throw noMatch();
+                                }
+                            }
+                        }.get(); // this extracts the received message
+
+                    assertTrue(
+                        compositeModification.getModifications().size() == 1);
+                    assertEquals(modificationType,
+                        compositeModification.getModifications().get(0)
+                            .getClass());
 
-          final String out = new ExpectMsg<String>("match hint") {
-            // do not put code outside this method, will run afterwards
-            protected String match(Object in) {
-              if (in instanceof WriteDataReply) {
-                return "match";
-              } else {
-                throw noMatch();
-              }
-            }
-          }.get(); // this extracts the received message
+                }
+            };
+        }};
+    }
+
+    @Test
+    public void testOnReceiveWriteData() throws Exception {
+        new JavaTestKit(getSystem()) {{
+            final ActorRef shard = getSystem().actorOf(Shard.props("config"));
+            final Props props =
+                ShardTransaction.props(store.newReadWriteTransaction(), shard);
+            final ActorRef subject =
+                getSystem().actorOf(props, "testWriteData");
+
+            new Within(duration("1 seconds")) {
+                protected void run() {
+
+                    subject.tell(new WriteData(TestModel.TEST_PATH,
+                        ImmutableNodes.containerNode(TestModel.TEST_QNAME)),
+                        getRef());
+
+                    final String out = new ExpectMsg<String>("match hint") {
+                        // do not put code outside this method, will run afterwards
+                        protected String match(Object in) {
+                            if (in instanceof WriteDataReply) {
+                                return "match";
+                            } else {
+                                throw noMatch();
+                            }
+                        }
+                    }.get(); // this extracts the received message
+
+                    assertEquals("match", out);
+
+                    assertModification(subject, WriteModification.class);
+                    expectNoMsg();
+                }
 
-          assertEquals("match", out);
 
-          expectNoMsg();
-        }
+            };
+        }};
+    }
 
+    @Test
+    public void testOnReceiveMergeData() throws Exception {
+        new JavaTestKit(getSystem()) {{
+            final ActorRef shard = getSystem().actorOf(Shard.props("config"));
+            final Props props =
+                ShardTransaction.props(store.newReadWriteTransaction(), shard);
+            final ActorRef subject =
+                getSystem().actorOf(props, "testMergeData");
 
-      };
-    }};
-  }
+            new Within(duration("1 seconds")) {
+                protected void run() {
 
-  @Test
-  public void testOnReceiveMergeData() throws Exception {
-    new JavaTestKit(getSystem()) {{
-      final Props props = ShardTransaction.props(store.newReadWriteTransaction());
-      final ActorRef subject = getSystem().actorOf(props, "testMergeData");
+                    subject.tell(new MergeData(TestModel.TEST_PATH,
+                        ImmutableNodes.containerNode(TestModel.TEST_QNAME)),
+                        getRef());
 
-      new Within(duration("1 seconds")) {
-        protected void run() {
+                    final String out = new ExpectMsg<String>("match hint") {
+                        // do not put code outside this method, will run afterwards
+                        protected String match(Object in) {
+                            if (in instanceof MergeDataReply) {
+                                return "match";
+                            } else {
+                                throw noMatch();
+                            }
+                        }
+                    }.get(); // this extracts the received message
 
-          subject.tell(new MergeData(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME)), getRef());
+                    assertEquals("match", out);
 
-          final String out = new ExpectMsg<String>("match hint") {
-            // do not put code outside this method, will run afterwards
-            protected String match(Object in) {
-              if (in instanceof MergeDataReply) {
-                return "match";
-              } else {
-                throw noMatch();
-              }
-            }
-          }.get(); // this extracts the received message
+                    assertModification(subject, MergeModification.class);
 
-          assertEquals("match", out);
+                    expectNoMsg();
+                }
 
-          expectNoMsg();
-        }
 
+            };
+        }};
+    }
 
-      };
-    }};
-  }
+    @Test
+    public void testOnReceiveDeleteData() throws Exception {
+        new JavaTestKit(getSystem()) {{
+            final ActorRef shard = getSystem().actorOf(Shard.props("config"));
+            final Props props =
+                ShardTransaction.props(store.newReadWriteTransaction(), shard);
+            final ActorRef subject =
+                getSystem().actorOf(props, "testDeleteData");
 
-  @Test
-  public void testOnReceiveDeleteData() throws Exception {
-    new JavaTestKit(getSystem()) {{
-      final Props props = ShardTransaction.props(store.newReadWriteTransaction());
-      final ActorRef subject = getSystem().actorOf(props, "testDeleteData");
+            new Within(duration("1 seconds")) {
+                protected void run() {
 
-      new Within(duration("1 seconds")) {
-        protected void run() {
+                    subject.tell(new DeleteData(TestModel.TEST_PATH), getRef());
 
-          subject.tell(new DeleteData(TestModel.TEST_PATH), getRef());
+                    final String out = new ExpectMsg<String>("match hint") {
+                        // do not put code outside this method, will run afterwards
+                        protected String match(Object in) {
+                            if (in instanceof DeleteDataReply) {
+                                return "match";
+                            } else {
+                                throw noMatch();
+                            }
+                        }
+                    }.get(); // this extracts the received message
 
-          final String out = new ExpectMsg<String>("match hint") {
-            // do not put code outside this method, will run afterwards
-            protected String match(Object in) {
-              if (in instanceof DeleteDataReply) {
-                return "match";
-              } else {
-                throw noMatch();
-              }
-            }
-          }.get(); // this extracts the received message
+                    assertEquals("match", out);
 
-          assertEquals("match", out);
+                    assertModification(subject, DeleteModification.class);
+                    expectNoMsg();
+                }
 
-          expectNoMsg();
-        }
 
+            };
+        }};
+    }
 
-      };
-    }};
-  }
 
+    @Test
+    public void testOnReceiveReadyTransaction() throws Exception {
+        new JavaTestKit(getSystem()) {{
+            final ActorRef shard = getSystem().actorOf(Shard.props("config"));
+            final Props props =
+                ShardTransaction.props(store.newReadWriteTransaction(), shard);
+            final ActorRef subject =
+                getSystem().actorOf(props, "testReadyTransaction");
 
-  @Test
-  public void testOnReceiveReadyTransaction() throws Exception {
-    new JavaTestKit(getSystem()) {{
-      final Props props = ShardTransaction.props(store.newReadWriteTransaction());
-      final ActorRef subject = getSystem().actorOf(props, "testReadyTransaction");
+            new Within(duration("1 seconds")) {
+                protected void run() {
 
-      new Within(duration("1 seconds")) {
-        protected void run() {
+                    subject.tell(new ReadyTransaction(), getRef());
 
-          subject.tell(new ReadyTransaction(), getRef());
+                    final String out = new ExpectMsg<String>("match hint") {
+                        // do not put code outside this method, will run afterwards
+                        protected String match(Object in) {
+                            if (in instanceof ReadyTransactionReply) {
+                                return "match";
+                            } else {
+                                throw noMatch();
+                            }
+                        }
+                    }.get(); // this extracts the received message
 
-          final String out = new ExpectMsg<String>("match hint") {
-            // do not put code outside this method, will run afterwards
-            protected String match(Object in) {
-              if (in instanceof ReadyTransactionReply) {
-                return "match";
-              } else {
-                throw noMatch();
-              }
-            }
-          }.get(); // this extracts the received message
+                    assertEquals("match", out);
 
-          assertEquals("match", out);
+                    expectNoMsg();
+                }
 
-          expectNoMsg();
-        }
 
+            };
+        }};
 
-      };
-    }};
+    }
 
-  }
+    @Test
+    public void testOnReceiveCloseTransaction() throws Exception {
+        new JavaTestKit(getSystem()) {{
+            final ActorRef shard = getSystem().actorOf(Shard.props("config"));
+            final Props props =
+                ShardTransaction.props(store.newReadWriteTransaction(), shard);
+            final ActorRef subject =
+                getSystem().actorOf(props, "testCloseTransaction");
 
-  @Test
-  public void testOnReceiveCloseTransaction() throws Exception {
-    new JavaTestKit(getSystem()) {{
-      final Props props = ShardTransaction.props(store.newReadWriteTransaction());
-      final ActorRef subject = getSystem().actorOf(props, "testCloseTransaction");
+            watch(subject);
 
-      new Within(duration("1 seconds")) {
-        protected void run() {
+            new Within(duration("2 seconds")) {
+                protected void run() {
 
-          subject.tell(new CloseTransaction(), getRef());
+                    subject.tell(new CloseTransaction(), getRef());
 
-          final String out = new ExpectMsg<String>("match hint") {
-            // do not put code outside this method, will run afterwards
-            protected String match(Object in) {
-              if (in instanceof CloseTransactionReply) {
-                return "match";
-              } else {
-                throw noMatch();
-              }
-            }
-          }.get(); // this extracts the received message
+                    final String out = new ExpectMsg<String>("match hint") {
+                        // do not put code outside this method, will run afterwards
+                        protected String match(Object in) {
+                            if (in instanceof CloseTransactionReply) {
+                                return "match";
+                            } else {
+                                throw noMatch();
+                            }
+                        }
+                    }.get(); // this extracts the received message
 
-          assertEquals("match", out);
+                    assertEquals("match", out);
 
-          expectNoMsg();
-        }
+                    final String termination = new ExpectMsg<String>("match hint") {
+                        // do not put code outside this method, will run afterwards
+                        protected String match(Object in) {
+                            if (in instanceof Terminated) {
+                                return "match";
+                            } else {
+                                throw noMatch();
+                            }
+                        }
+                    }.get(); // this extracts the received message
 
 
-      };
-    }};
+                    expectNoMsg();
+                }
 
-  }
 
+            };
+        }};
 
-}
\ No newline at end of file
+    }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ThreePhaseCommitCohortProxyTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/ThreePhaseCommitCohortProxyTest.java
new file mode 100644 (file)
index 0000000..8ff785c
--- /dev/null
@@ -0,0 +1,85 @@
+package org.opendaylight.controller.cluster.datastore;
+
+import akka.actor.ActorRef;
+import akka.actor.Props;
+import com.google.common.util.concurrent.ListenableFuture;
+import junit.framework.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.CanCommitTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.PreCommitTransactionReply;
+import org.opendaylight.controller.cluster.datastore.utils.MessageCollectorActor;
+import org.opendaylight.controller.cluster.datastore.utils.MockActorContext;
+
+import java.util.Arrays;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+import static org.junit.Assert.assertNotNull;
+
+public class ThreePhaseCommitCohortProxyTest extends AbstractActorTest {
+
+    private ThreePhaseCommitCohortProxy proxy;
+    private Props props;
+    private ActorRef actorRef;
+    private MockActorContext actorContext;
+    private ExecutorService executor = Executors.newSingleThreadExecutor();
+
+    @Before
+    public void setUp(){
+        props = Props.create(MessageCollectorActor.class);
+        actorRef = getSystem().actorOf(props);
+        actorContext = new MockActorContext(this.getSystem());
+
+        proxy =
+            new ThreePhaseCommitCohortProxy(actorContext,
+                Arrays.asList(actorRef.path()), "txn-1", executor);
+
+    }
+
+    @Test
+    public void testCanCommit() throws Exception {
+        actorContext.setExecuteRemoteOperationResponse(new CanCommitTransactionReply(true));
+
+        ListenableFuture<Boolean> future = proxy.canCommit();
+
+        Assert.assertTrue(future.get().booleanValue());
+
+    }
+
+    @Test
+    public void testPreCommit() throws Exception {
+        actorContext.setExecuteRemoteOperationResponse(new PreCommitTransactionReply());
+
+        ListenableFuture<Void> future = proxy.preCommit();
+
+        future.get();
+
+    }
+
+    @Test
+    public void testAbort() throws Exception {
+        actorContext.setExecuteRemoteOperationResponse(new AbortTransactionReply());
+
+        ListenableFuture<Void> future = proxy.abort();
+
+        future.get();
+
+    }
+
+    @Test
+    public void testCommit() throws Exception {
+        actorContext.setExecuteRemoteOperationResponse(new CommitTransactionReply());
+
+        ListenableFuture<Void> future = proxy.commit();
+
+        future.get();
+    }
+
+    @Test
+    public void testGetCohortPaths() throws Exception {
+        assertNotNull(proxy.getCohortPaths());
+    }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/TransactionProxyTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/TransactionProxyTest.java
new file mode 100644 (file)
index 0000000..a8df49f
--- /dev/null
@@ -0,0 +1,264 @@
+package org.opendaylight.controller.cluster.datastore;
+
+import akka.actor.ActorRef;
+import akka.actor.Props;
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.ListenableFuture;
+import junit.framework.Assert;
+import org.junit.Test;
+import org.opendaylight.controller.cluster.datastore.messages.CloseTransaction;
+import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.DeleteData;
+import org.opendaylight.controller.cluster.datastore.messages.MergeData;
+import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
+import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
+import org.opendaylight.controller.cluster.datastore.messages.WriteData;
+import org.opendaylight.controller.cluster.datastore.utils.ActorContext;
+import org.opendaylight.controller.cluster.datastore.utils.DoNothingActor;
+import org.opendaylight.controller.cluster.datastore.utils.MessageCollectorActor;
+import org.opendaylight.controller.cluster.datastore.utils.MockActorContext;
+import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+
+import java.util.List;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+public class TransactionProxyTest extends AbstractActorTest {
+
+    private ExecutorService transactionExecutor =
+        Executors.newSingleThreadExecutor();
+
+    @Test
+    public void testRead() throws Exception {
+        final Props props = Props.create(DoNothingActor.class);
+        final ActorRef actorRef = getSystem().actorOf(props);
+
+        final MockActorContext actorContext = new MockActorContext(this.getSystem());
+        actorContext.setExecuteShardOperationResponse(createTransactionReply(actorRef));
+        actorContext.setExecuteRemoteOperationResponse("message");
+
+        TransactionProxy transactionProxy =
+            new TransactionProxy(actorContext,
+                TransactionProxy.TransactionType.READ_ONLY, transactionExecutor);
+
+
+        ListenableFuture<Optional<NormalizedNode<?, ?>>> read =
+            transactionProxy.read(TestModel.TEST_PATH);
+
+        Optional<NormalizedNode<?, ?>> normalizedNodeOptional = read.get();
+
+        Assert.assertFalse(normalizedNodeOptional.isPresent());
+
+        actorContext.setExecuteRemoteOperationResponse(new ReadDataReply(
+            ImmutableNodes.containerNode(TestModel.TEST_QNAME)));
+
+        read = transactionProxy.read(TestModel.TEST_PATH);
+
+        normalizedNodeOptional = read.get();
+
+        Assert.assertTrue(normalizedNodeOptional.isPresent());
+    }
+
+    @Test
+    public void testReadWhenANullIsReturned() throws Exception {
+        final Props props = Props.create(DoNothingActor.class);
+        final ActorRef actorRef = getSystem().actorOf(props);
+
+        final MockActorContext actorContext = new MockActorContext(this.getSystem());
+        actorContext.setExecuteShardOperationResponse(createTransactionReply(actorRef));
+        actorContext.setExecuteRemoteOperationResponse("message");
+
+        TransactionProxy transactionProxy =
+            new TransactionProxy(actorContext,
+                TransactionProxy.TransactionType.READ_ONLY, transactionExecutor);
+
+
+        ListenableFuture<Optional<NormalizedNode<?, ?>>> read =
+            transactionProxy.read(TestModel.TEST_PATH);
+
+        Optional<NormalizedNode<?, ?>> normalizedNodeOptional = read.get();
+
+        Assert.assertFalse(normalizedNodeOptional.isPresent());
+
+        actorContext.setExecuteRemoteOperationResponse(new ReadDataReply(
+            null));
+
+        read = transactionProxy.read(TestModel.TEST_PATH);
+
+        normalizedNodeOptional = read.get();
+
+        Assert.assertFalse(normalizedNodeOptional.isPresent());
+    }
+
+    @Test
+    public void testWrite() throws Exception {
+        final Props props = Props.create(MessageCollectorActor.class);
+        final ActorRef actorRef = getSystem().actorOf(props);
+
+        final MockActorContext actorContext = new MockActorContext(this.getSystem());
+        actorContext.setExecuteShardOperationResponse(createTransactionReply(actorRef));
+        actorContext.setExecuteRemoteOperationResponse("message");
+
+        TransactionProxy transactionProxy =
+            new TransactionProxy(actorContext,
+                TransactionProxy.TransactionType.READ_ONLY, transactionExecutor);
+
+        transactionProxy.write(TestModel.TEST_PATH,
+            ImmutableNodes.containerNode(TestModel.NAME_QNAME));
+
+        ActorContext testContext = new ActorContext(getSystem(), getSystem().actorOf(Props.create(DoNothingActor.class)));
+        Object messages = testContext
+            .executeLocalOperation(actorRef, "messages",
+                ActorContext.ASK_DURATION);
+
+        Assert.assertNotNull(messages);
+
+        Assert.assertTrue(messages instanceof List);
+
+        List<Object> listMessages = (List<Object>) messages;
+
+        Assert.assertEquals(1, listMessages.size());
+
+        Assert.assertTrue(listMessages.get(0) instanceof WriteData);
+    }
+
+    @Test
+    public void testMerge() throws Exception {
+        final Props props = Props.create(MessageCollectorActor.class);
+        final ActorRef actorRef = getSystem().actorOf(props);
+
+        final MockActorContext actorContext = new MockActorContext(this.getSystem());
+        actorContext.setExecuteShardOperationResponse(createTransactionReply(actorRef));
+        actorContext.setExecuteRemoteOperationResponse("message");
+
+        TransactionProxy transactionProxy =
+            new TransactionProxy(actorContext,
+                TransactionProxy.TransactionType.READ_ONLY, transactionExecutor);
+
+        transactionProxy.merge(TestModel.TEST_PATH,
+            ImmutableNodes.containerNode(TestModel.NAME_QNAME));
+
+        ActorContext testContext = new ActorContext(getSystem(), getSystem().actorOf(Props.create(DoNothingActor.class)));
+        Object messages = testContext
+            .executeLocalOperation(actorRef, "messages",
+                ActorContext.ASK_DURATION);
+
+        Assert.assertNotNull(messages);
+
+        Assert.assertTrue(messages instanceof List);
+
+        List<Object> listMessages = (List<Object>) messages;
+
+        Assert.assertEquals(1, listMessages.size());
+
+        Assert.assertTrue(listMessages.get(0) instanceof MergeData);
+    }
+
+    @Test
+    public void testDelete() throws Exception {
+        final Props props = Props.create(MessageCollectorActor.class);
+        final ActorRef actorRef = getSystem().actorOf(props);
+
+        final MockActorContext actorContext = new MockActorContext(this.getSystem());
+        actorContext.setExecuteShardOperationResponse(createTransactionReply(actorRef));
+        actorContext.setExecuteRemoteOperationResponse("message");
+
+        TransactionProxy transactionProxy =
+            new TransactionProxy(actorContext,
+                TransactionProxy.TransactionType.READ_ONLY, transactionExecutor);
+
+        transactionProxy.delete(TestModel.TEST_PATH);
+
+        ActorContext testContext = new ActorContext(getSystem(), getSystem().actorOf(Props.create(DoNothingActor.class)));
+        Object messages = testContext
+            .executeLocalOperation(actorRef, "messages",
+                ActorContext.ASK_DURATION);
+
+        Assert.assertNotNull(messages);
+
+        Assert.assertTrue(messages instanceof List);
+
+        List<Object> listMessages = (List<Object>) messages;
+
+        Assert.assertEquals(1, listMessages.size());
+
+        Assert.assertTrue(listMessages.get(0) instanceof DeleteData);
+    }
+
+    @Test
+    public void testReady() throws Exception {
+        final Props props = Props.create(DoNothingActor.class);
+        final ActorRef doNothingActorRef = getSystem().actorOf(props);
+
+        final MockActorContext actorContext = new MockActorContext(this.getSystem());
+        actorContext.setExecuteShardOperationResponse(createTransactionReply(doNothingActorRef));
+        actorContext.setExecuteRemoteOperationResponse(new ReadyTransactionReply(doNothingActorRef.path()));
+
+        TransactionProxy transactionProxy =
+            new TransactionProxy(actorContext,
+                TransactionProxy.TransactionType.READ_ONLY, transactionExecutor);
+
+
+        DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
+
+        Assert.assertTrue(ready instanceof ThreePhaseCommitCohortProxy);
+
+        ThreePhaseCommitCohortProxy proxy = (ThreePhaseCommitCohortProxy) ready;
+
+        Assert.assertTrue("No cohort paths returned", proxy.getCohortPaths().size() > 0);
+
+    }
+
+    @Test
+    public void testGetIdentifier(){
+        final Props props = Props.create(DoNothingActor.class);
+        final ActorRef doNothingActorRef = getSystem().actorOf(props);
+
+        final MockActorContext actorContext = new MockActorContext(this.getSystem());
+        actorContext.setExecuteShardOperationResponse( createTransactionReply(doNothingActorRef) );
+
+        TransactionProxy transactionProxy =
+            new TransactionProxy(actorContext,
+                TransactionProxy.TransactionType.READ_ONLY, transactionExecutor);
+
+        Assert.assertNotNull(transactionProxy.getIdentifier());
+    }
+
+    @Test
+    public void testClose(){
+        final Props props = Props.create(MessageCollectorActor.class);
+        final ActorRef actorRef = getSystem().actorOf(props);
+
+        final MockActorContext actorContext = new MockActorContext(this.getSystem());
+        actorContext.setExecuteShardOperationResponse(createTransactionReply(actorRef));
+        actorContext.setExecuteRemoteOperationResponse("message");
+
+        TransactionProxy transactionProxy =
+            new TransactionProxy(actorContext,
+                TransactionProxy.TransactionType.READ_ONLY, transactionExecutor);
+
+        transactionProxy.close();
+
+        ActorContext testContext = new ActorContext(getSystem(), getSystem().actorOf(Props.create(DoNothingActor.class)));
+        Object messages = testContext
+            .executeLocalOperation(actorRef, "messages",
+                ActorContext.ASK_DURATION);
+
+        Assert.assertNotNull(messages);
+
+        Assert.assertTrue(messages instanceof List);
+
+        List<Object> listMessages = (List<Object>) messages;
+
+        Assert.assertEquals(1, listMessages.size());
+
+        Assert.assertTrue(listMessages.get(0) instanceof CloseTransaction);
+    }
+
+    private CreateTransactionReply createTransactionReply(ActorRef actorRef){
+        return new CreateTransactionReply(actorRef.path(), "txn-1");
+    }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/modification/AbstractModificationTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/modification/AbstractModificationTest.java
new file mode 100644 (file)
index 0000000..efaca5d
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.cluster.datastore.modification;
+
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.MoreExecutors;
+import org.junit.Before;
+import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
+import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+public abstract class AbstractModificationTest {
+
+  protected InMemoryDOMDataStore store;
+
+  @Before
+  public void setUp(){
+    store = new InMemoryDOMDataStore("test", MoreExecutors.sameThreadExecutor());
+    store.onGlobalContextUpdated(TestModel.createTestContext());
+  }
+
+  protected void commitTransaction(DOMStoreWriteTransaction transaction){
+    DOMStoreThreePhaseCommitCohort cohort = transaction.ready();
+    cohort.preCommit();
+    cohort.commit();
+  }
+
+  protected Optional<NormalizedNode<?,?>> readData(InstanceIdentifier path) throws Exception{
+    DOMStoreReadTransaction transaction = store.newReadOnlyTransaction();
+    ListenableFuture<Optional<NormalizedNode<?, ?>>> future = transaction.read(path);
+    return future.get();
+  }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/modification/DeleteModificationTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/modification/DeleteModificationTest.java
new file mode 100644 (file)
index 0000000..c1f9f3a
--- /dev/null
@@ -0,0 +1,35 @@
+package org.opendaylight.controller.cluster.datastore.modification;
+
+import com.google.common.base.Optional;
+import org.junit.Assert;
+import org.junit.Test;
+import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreWriteTransaction;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+
+public class DeleteModificationTest extends AbstractModificationTest{
+
+  @Test
+  public void testApply() throws Exception {
+    //Write something into the datastore
+    DOMStoreReadWriteTransaction writeTransaction = store.newReadWriteTransaction();
+    WriteModification writeModification = new WriteModification(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
+    writeModification.apply(writeTransaction);
+    commitTransaction(writeTransaction);
+
+    //Check if it's in the datastore
+    Optional<NormalizedNode<?,?>> data = readData(TestModel.TEST_PATH);
+    Assert.assertTrue(data.isPresent());
+
+    //Delete stuff from the datastore
+    DOMStoreWriteTransaction deleteTransaction = store.newWriteOnlyTransaction();
+    DeleteModification deleteModification = new DeleteModification(TestModel.TEST_PATH);
+    deleteModification.apply(deleteTransaction);
+    commitTransaction(deleteTransaction);
+
+    data = readData(TestModel.TEST_PATH);
+    Assert.assertFalse(data.isPresent());
+  }
+}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/modification/MergeModificationTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/modification/MergeModificationTest.java
new file mode 100644 (file)
index 0000000..fd125fb
--- /dev/null
@@ -0,0 +1,28 @@
+package org.opendaylight.controller.cluster.datastore.modification;
+
+import com.google.common.base.Optional;
+import org.junit.Assert;
+import org.junit.Test;
+import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+
+public class MergeModificationTest extends AbstractModificationTest{
+
+  @Test
+  public void testApply() throws Exception {
+    //TODO : Need to write a better test for this
+
+    //Write something into the datastore
+    DOMStoreReadWriteTransaction writeTransaction = store.newReadWriteTransaction();
+    MergeModification writeModification = new MergeModification(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
+    writeModification.apply(writeTransaction);
+    commitTransaction(writeTransaction);
+
+    //Check if it's in the datastore
+    Optional<NormalizedNode<?,?>> data = readData(TestModel.TEST_PATH);
+    Assert.assertTrue(data.isPresent());
+
+  }
+}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/modification/MutableCompositeModificationTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/modification/MutableCompositeModificationTest.java
new file mode 100644 (file)
index 0000000..e30936b
--- /dev/null
@@ -0,0 +1,28 @@
+package org.opendaylight.controller.cluster.datastore.modification;
+
+import com.google.common.base.Optional;
+import junit.framework.Assert;
+import org.junit.Test;
+import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+
+public class MutableCompositeModificationTest extends AbstractModificationTest {
+
+  @Test
+  public void testApply() throws Exception {
+
+    MutableCompositeModification compositeModification = new MutableCompositeModification();
+    compositeModification.addModification(new WriteModification(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME)));
+
+    DOMStoreReadWriteTransaction transaction = store.newReadWriteTransaction();
+    compositeModification.apply(transaction);
+    commitTransaction(transaction);
+
+    Optional<NormalizedNode<?,?>> data = readData(TestModel.TEST_PATH);
+
+    Assert.assertNotNull(data.get());
+    Assert.assertEquals(TestModel.TEST_QNAME, data.get().getNodeType());
+  }
+}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/modification/WriteModificationTest.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/modification/WriteModificationTest.java
new file mode 100644 (file)
index 0000000..e206bf8
--- /dev/null
@@ -0,0 +1,26 @@
+package org.opendaylight.controller.cluster.datastore.modification;
+
+import com.google.common.base.Optional;
+import org.junit.Assert;
+import org.junit.Test;
+import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+
+public class WriteModificationTest extends AbstractModificationTest{
+
+  @Test
+  public void testApply() throws Exception {
+    //Write something into the datastore
+    DOMStoreReadWriteTransaction writeTransaction = store.newReadWriteTransaction();
+    WriteModification writeModification = new WriteModification(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
+    writeModification.apply(writeTransaction);
+    commitTransaction(writeTransaction);
+
+    //Check if it's in the datastore
+    Optional<NormalizedNode<?,?>> data = readData(TestModel.TEST_PATH);
+    Assert.assertTrue(data.isPresent());
+
+  }
+}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/DoNothingActor.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/DoNothingActor.java
new file mode 100644 (file)
index 0000000..819cfd0
--- /dev/null
@@ -0,0 +1,17 @@
+/*
+ * 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.utils;
+
+import akka.actor.UntypedActor;
+
+public class DoNothingActor extends UntypedActor {
+
+    @Override public void onReceive(Object message) throws Exception {
+    }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/MessageCollectorActor.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/MessageCollectorActor.java
new file mode 100644 (file)
index 0000000..f75aa54
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * 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.utils;
+
+import akka.actor.UntypedActor;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * MessageCollectorActor collects messages as it receives them. It can send
+ * those collected messages to any sender which sends it the "messages" message
+ * <p>
+ *     This class would be useful as a mock to test whether messages were sent
+ *     to a remote actor or not.
+ * </p>
+ */
+public class MessageCollectorActor extends UntypedActor {
+    private List<Object> messages = new ArrayList<>();
+
+    @Override public void onReceive(Object message) throws Exception {
+        if(message instanceof String){
+            if("messages".equals(message)){
+                getSender().tell(messages, getSelf());
+            }
+        } else {
+            messages.add(message);
+        }
+    }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/MockActorContext.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/MockActorContext.java
new file mode 100644 (file)
index 0000000..fe62516
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * 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.utils;
+
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSelection;
+import akka.actor.ActorSystem;
+import scala.concurrent.duration.FiniteDuration;
+
+public class MockActorContext extends ActorContext {
+
+    private Object executeShardOperationResponse;
+    private Object executeRemoteOperationResponse;
+    private Object executeLocalOperationResponse;
+
+    public MockActorContext(ActorSystem actorSystem) {
+        super(actorSystem, null);
+    }
+
+    public MockActorContext(ActorSystem actorSystem, ActorRef shardManager) {
+        super(actorSystem, shardManager);
+    }
+
+
+    @Override public Object executeShardOperation(String shardName,
+        Object message, FiniteDuration duration) {
+        return executeShardOperationResponse;
+    }
+
+    @Override public Object executeRemoteOperation(ActorSelection actor,
+        Object message, FiniteDuration duration) {
+        return executeRemoteOperationResponse;
+    }
+
+    @Override public ActorSelection findPrimary(String shardName) {
+        return null;
+    }
+
+    public void setExecuteShardOperationResponse(Object response){
+        executeShardOperationResponse = response;
+    }
+
+    public void setExecuteRemoteOperationResponse(Object response){
+        executeRemoteOperationResponse = response;
+    }
+
+    public void setExecuteLocalOperationResponse(
+        Object executeLocalOperationResponse) {
+        this.executeLocalOperationResponse = executeLocalOperationResponse;
+    }
+
+
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/TestUtils.java b/opendaylight/md-sal/sal-distributed-datastore/src/test/java/org/opendaylight/controller/cluster/datastore/utils/TestUtils.java
new file mode 100644 (file)
index 0000000..bb881d5
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * 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.utils;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.actor.Props;
+import junit.framework.Assert;
+
+import java.util.List;
+
+public class TestUtils {
+
+    public static void assertFirstSentMessage(ActorSystem actorSystem, ActorRef actorRef, Class clazz){
+        ActorContext testContext = new ActorContext(actorSystem, actorSystem.actorOf(
+            Props.create(DoNothingActor.class)));
+        Object messages = testContext
+            .executeLocalOperation(actorRef, "messages",
+                ActorContext.ASK_DURATION);
+
+        Assert.assertNotNull(messages);
+
+        Assert.assertTrue(messages instanceof List);
+
+        List<Object> listMessages = (List<Object>) messages;
+
+        Assert.assertEquals(1, listMessages.size());
+
+        Assert.assertTrue(listMessages.get(0).getClass().equals(clazz));
+    }
+}
diff --git a/opendaylight/md-sal/sal-distributed-datastore/src/test/resources/application.conf b/opendaylight/md-sal/sal-distributed-datastore/src/test/resources/application.conf
new file mode 100644 (file)
index 0000000..2647850
--- /dev/null
@@ -0,0 +1,11 @@
+akka {
+    actor {
+        serializers {
+          java = "akka.serialization.JavaSerializer"
+        }
+
+        serialization-bindings {
+            "org.opendaylight.controller.cluster.datastore.modification.MutableCompositeModification" = java
+        }
+    }
+}
\ No newline at end of file
index c120508f875acfc0f5710aaced9d699204307fbc..613cf1bfe24e1b31cf854d978c35c48ef11d96f3 100644 (file)
@@ -29,7 +29,7 @@ public interface DOMDataBroker extends
      * {@inheritDoc}
      */
     @Override
-    DOMDataReadTransaction newReadOnlyTransaction();
+    DOMDataReadOnlyTransaction newReadOnlyTransaction();
 
     /**
      * {@inheritDoc}
diff --git a/opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMDataReadOnlyTransaction.java b/opendaylight/md-sal/sal-dom-api/src/main/java/org/opendaylight/controller/md/sal/dom/api/DOMDataReadOnlyTransaction.java
new file mode 100644 (file)
index 0000000..18fb988
--- /dev/null
@@ -0,0 +1,9 @@
+package org.opendaylight.controller.md.sal.dom.api;
+
+import org.opendaylight.controller.md.sal.common.api.data.AsyncReadOnlyTransaction;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+public interface DOMDataReadOnlyTransaction extends DOMDataReadTransaction, AsyncReadOnlyTransaction<InstanceIdentifier, NormalizedNode<?, ?>> {
+
+}
index 5baa5e72d31e8fe0bbd8444c9d86444ca79e594c..0d5e47faee198b95f453a07c99bcfaa3181ded3d 100644 (file)
@@ -8,9 +8,39 @@
 package org.opendaylight.controller.md.sal.dom.api;
 
 import org.opendaylight.controller.md.sal.common.api.data.AsyncReadTransaction;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.ListenableFuture;
+
+/**
+ * A transaction that provides read access to a logical data store.
+ * <p>
+ * For more information on usage and examples, please see the documentation in {@link AsyncReadTransaction}.
+ */
 public interface DOMDataReadTransaction extends AsyncReadTransaction<InstanceIdentifier, NormalizedNode<?, ?>> {
 
+    /**
+     * Reads data from provided logical data store located at the provided path.
+     *<p>
+     * If the target is a subtree, then the whole subtree is read (and will be
+     * accessible from the returned data object).
+     *
+     * @param store
+     *            Logical data store from which read should occur.
+     * @param path
+     *            Path which uniquely identifies subtree which client want to
+     *            read
+     * @return Listenable Future which contains read result
+     *         <ul>
+     *         <li>If data at supplied path exists the
+     *         {@link ListeblaFuture#get()} returns Optional object containing
+     *         data once read is done.
+     *         <li>If data at supplied path does not exists the
+     *         {@link ListenbleFuture#get()} returns {@link Optional#absent()}.
+     *         </ul>
+     */
+    ListenableFuture<Optional<NormalizedNode<?,?>>> read(LogicalDatastoreType store,InstanceIdentifier path);
 }
index b894911ffad8fcac128f38f743df5a3a6819ea30..73a0c28465108e951ddafdd6fa2639bd088f9ff1 100644 (file)
@@ -24,7 +24,7 @@ import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 public interface DOMTransactionChain extends TransactionChain<InstanceIdentifier, NormalizedNode<?, ?>> {
 
     @Override
-    DOMDataReadTransaction newReadOnlyTransaction();
+    DOMDataReadOnlyTransaction newReadOnlyTransaction();
 
     @Override
     DOMDataReadWriteTransaction newReadWriteTransaction();
index 266b6976afbde367ecca294a90023253d903b0ff..9c7deaf406fb955bcb43339a784f1b17748579cf 100644 (file)
@@ -21,8 +21,10 @@ import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
  *
  *
  * @see DataProviderService
+ * @deprecated Replaced by {@link org.opendaylight.controller.md.sal.dom.api.DOMDataBroker}
  *
  */
+@Deprecated
 public interface DataBrokerService extends
     BrokerService, //
     DataReader<InstanceIdentifier, CompositeNode>, //
@@ -36,5 +38,6 @@ public interface DataBrokerService extends
     @Override
     public CompositeNode readOperationalData(InstanceIdentifier path);
 
+    @Override
     DataModificationTransaction beginTransaction();
 }
index 944ccc5b33a120f5ad3ef2eeb3e347dd5881621c..2bf949d208b9bf563c9b7d41e39826bbd853339a 100644 (file)
@@ -11,6 +11,11 @@ import org.opendaylight.controller.md.sal.common.api.data.DataChangeEvent;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 
+/**
+ *
+ * @deprecated Replaced by {@link org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener}
+ */
+@Deprecated
 public interface DataChangeListener
         extends
         org.opendaylight.controller.md.sal.common.api.data.DataChangeListener<InstanceIdentifier, CompositeNode> {
index 9706bbacdbdbee3b22c3a8b163b069617b452347..82e62255c3ba465c86ef665038f362b6cad1f0fe 100644 (file)
@@ -17,7 +17,17 @@ import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 
-public interface DataModificationTransaction extends DataModification<InstanceIdentifier, CompositeNode>{
+/**
+ *
+ * @deprecated Replaced by more specific
+ *             {@link org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction}
+ *             ,
+ *             {@link org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction}
+ *             or {@link org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction}
+ *
+ */
+@Deprecated
+public interface DataModificationTransaction extends DataModification<InstanceIdentifier, CompositeNode> {
 
     /**
      * Returns transaction identifier
@@ -34,8 +44,8 @@ public interface DataModificationTransaction extends DataModification<InstanceId
      * Commits transaction to be stored in global data repository.
      *
      *
-     * @return  Future object which returns RpcResult with TransactionStatus
-     *          when transaction is processed by store.
+     * @return Future object which returns RpcResult with TransactionStatus when
+     *         transaction is processed by store.
      */
     @Override
     Future<RpcResult<TransactionStatus>> commit();
@@ -43,6 +53,6 @@ public interface DataModificationTransaction extends DataModification<InstanceId
     ListenerRegistration<DataTransactionListener> registerListener(DataTransactionListener listener);
 
     public interface DataTransactionListener extends EventListener {
-        void onStatusUpdated(DataModificationTransaction transaction,TransactionStatus status);
+        void onStatusUpdated(DataModificationTransaction transaction, TransactionStatus status);
     }
 }
index 0538660fd79eea473d705ae588ce83035683941e..0810fa3e98ab9041c51b0febb83184ec14f6463d 100644 (file)
@@ -8,13 +8,19 @@
 package org.opendaylight.controller.sal.core.api.data;
 
 import org.opendaylight.controller.md.sal.common.api.data.DataProvisionService;
+import org.opendaylight.controller.md.sal.common.api.data.DataReader;
 import org.opendaylight.controller.sal.common.DataStoreIdentifier;
 import org.opendaylight.controller.sal.core.api.Provider;
 import org.opendaylight.yangtools.concepts.Registration;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
-import org.opendaylight.controller.md.sal.common.api.data.DataReader;;
 
+/**
+ *
+ * @deprecated Replaced by {@link org.opendaylight.controller.md.sal.dom.api.DOMDataBroker}
+ *
+ */
+@Deprecated
 public interface DataProviderService extends
     DataBrokerService, //
     DataProvisionService<InstanceIdentifier, CompositeNode>
index 58ffb38365c0d6673fa10ef9f1ccd229cdb26bcd..56d2e87c2c1007954c7560f01132298bf37f2387 100644 (file)
@@ -12,6 +12,12 @@ import org.opendaylight.controller.md.sal.common.api.data.DataReader;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 
+/**
+ *
+ * @deprecated Replaced by org.opendaylight.controller.sal.core.spi.data.DOMStore.
+ *
+ */
+@Deprecated
 public interface DataStore extends //
     DataReader<InstanceIdentifier, CompositeNode>,
     DataCommitHandler<InstanceIdentifier, CompositeNode> {
index 286770b0482d36d600f9f2eeebe5ed24cf928a43..e4e6e2f26df00fb1baf8035649143e87afe95a96 100644 (file)
@@ -28,7 +28,10 @@ import org.opendaylight.yangtools.yang.data.api.CompositeNode;
  * {@link DataProviderService#addValidator(DataStoreIdentifier, DataValidator)}
  * </ul>
  *
+ * @deprecated Replaced by {@link org.opendaylight.controller.md.sal.common.api.data.AsyncConfigurationCommitHandler}
+ *
  **/
+@Deprecated
 public interface DataValidator extends Provider.ProviderFunctionality {
 
     /**
index 767785dbf13c1dac1231b46e2339f044ebe0cb97..998d884b0cde71cd2fe774352229a61afd98761d 100644 (file)
@@ -8,10 +8,26 @@
 package org.opendaylight.controller.config.yang.md.sal.dom.impl;
 
 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
+import org.opendaylight.controller.md.sal.dom.broker.impl.compat.BackwardsCompatibleDataBroker;
+import org.opendaylight.controller.sal.core.api.BrokerService;
+import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
+import org.opendaylight.controller.sal.core.api.data.DataBrokerService;
+import org.opendaylight.controller.sal.core.api.data.DataProviderService;
 import org.opendaylight.controller.sal.core.api.data.DataStore;
-import org.opendaylight.controller.sal.dom.broker.BrokerConfigActivator;
+import org.opendaylight.controller.sal.core.api.model.SchemaService;
+import org.opendaylight.controller.sal.core.api.mount.MountProvisionService;
+import org.opendaylight.controller.sal.core.api.mount.MountService;
 import org.opendaylight.controller.sal.dom.broker.BrokerImpl;
-import org.osgi.framework.BundleContext;
+import org.opendaylight.controller.sal.dom.broker.DataBrokerImpl;
+import org.opendaylight.controller.sal.dom.broker.GlobalBundleScanningSchemaServiceImpl;
+import org.opendaylight.controller.sal.dom.broker.MountPointManagerImpl;
+import org.opendaylight.controller.sal.dom.broker.impl.SchemaAwareDataStoreAdapter;
+import org.opendaylight.controller.sal.dom.broker.impl.SchemaAwareRpcBroker;
+import org.opendaylight.controller.sal.dom.broker.impl.SchemaContextProviders;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+
+import com.google.common.collect.ClassToInstanceMap;
+import com.google.common.collect.MutableClassToInstanceMap;
 
 /**
 *
@@ -19,8 +35,6 @@ import org.osgi.framework.BundleContext;
 public final class DomBrokerImplModule extends org.opendaylight.controller.config.yang.md.sal.dom.impl.AbstractDomBrokerImplModule
 {
 
-    private BundleContext bundleContext;
-
     public DomBrokerImplModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
         super(identifier, dependencyResolver);
     }
@@ -36,23 +50,58 @@ public final class DomBrokerImplModule extends org.opendaylight.controller.confi
 
     @Override
     public java.lang.AutoCloseable createInstance() {
-        final BrokerImpl broker = new BrokerImpl();
-        final BrokerConfigActivator activator = new BrokerConfigActivator();
-        final DataStore store = getDataStoreDependency();
+        final DataStore legacyStore = getDataStoreDependency();
         final DOMDataBroker asyncBroker= getAsyncDataBrokerDependency();
 
-        activator.start(broker, store, asyncBroker,getBundleContext());
+        ClassToInstanceMap<BrokerService> services = MutableClassToInstanceMap.create();
+
+
+        SchemaService schemaService = getSchemaServiceImpl();
+        services.putInstance(SchemaService.class, schemaService);
+        SchemaAwareRpcBroker router = new SchemaAwareRpcBroker("/", SchemaContextProviders
+                .fromSchemaService(schemaService));
+        services.putInstance(RpcProvisionRegistry.class, router);
+
+        final DataProviderService legacyData;
+        if(asyncBroker != null) {
+            services.putInstance(DOMDataBroker.class, asyncBroker);
+            legacyData = new BackwardsCompatibleDataBroker(asyncBroker,schemaService);
+        } else {
+            legacyData = createLegacyDataService(legacyStore,schemaService);
+        }
+        services.putInstance(DataProviderService.class,legacyData);
+        services.putInstance(DataBrokerService.class, legacyData);
 
-//        final DomBrokerImplRuntimeMXBean domBrokerRuntimeMXBean = new DomBrokerRuntimeMXBeanImpl(activator.getDataService());
-//        getRootRuntimeBeanRegistratorWrapper().register(domBrokerRuntimeMXBean);
-        return broker;
+
+        MountPointManagerImpl mountService = new MountPointManagerImpl();
+        services.putInstance(MountService.class, mountService);
+        services.putInstance(MountProvisionService.class, mountService);
+
+        return new BrokerImpl(router, services);
     }
 
-    private BundleContext getBundleContext() {
-        return this.bundleContext;
+    private DataProviderService createLegacyDataService(final DataStore legacyStore, final SchemaService schemaService) {
+        InstanceIdentifier rootPath = InstanceIdentifier.builder().toInstance();
+        DataBrokerImpl dataService = new DataBrokerImpl();
+        SchemaAwareDataStoreAdapter wrappedStore = new SchemaAwareDataStoreAdapter();
+        wrappedStore.changeDelegate(legacyStore);
+        wrappedStore.setValidationEnabled(false);
+
+        schemaService.registerSchemaServiceListener(wrappedStore);
+
+        dataService.registerConfigurationReader(rootPath, wrappedStore);
+        dataService.registerCommitHandler(rootPath, wrappedStore);
+        dataService.registerOperationalReader(rootPath, wrappedStore);
+        return dataService;
     }
 
-    public void setBundleContext(final BundleContext bundleContext) {
-        this.bundleContext = bundleContext;
+    private SchemaService getSchemaServiceImpl() {
+        final SchemaService schemaService;
+        if(getRootSchemaService() != null) {
+            schemaService = getRootSchemaServiceDependency();
+        } else {
+            schemaService = GlobalBundleScanningSchemaServiceImpl.getInstance();
+        }
+        return schemaService;
     }
 }
index 38f5009feb85e14376755f71008425d137c8cd00..f1fcb495aace6a38ade530efa34b32eba817772f 100644 (file)
@@ -7,10 +7,6 @@
  */
 package org.opendaylight.controller.config.yang.md.sal.dom.impl;
 
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.spi.Module;
-import org.osgi.framework.BundleContext;
 
 /**
 *
@@ -18,19 +14,4 @@ import org.osgi.framework.BundleContext;
 public class DomBrokerImplModuleFactory extends
         org.opendaylight.controller.config.yang.md.sal.dom.impl.AbstractDomBrokerImplModuleFactory {
 
-    @Override
-    public Module createModule(String instanceName, DependencyResolver dependencyResolver, BundleContext bundleContext) {
-        DomBrokerImplModule module = (DomBrokerImplModule) super.createModule(instanceName, dependencyResolver, bundleContext);
-        module.setBundleContext(bundleContext);
-        return module;
-    }
-
-    @Override
-    public Module createModule(String instanceName, DependencyResolver dependencyResolver,
-            DynamicMBeanWithInstance old, BundleContext bundleContext) throws Exception {
-        DomBrokerImplModule module = (DomBrokerImplModule) super.createModule(instanceName, dependencyResolver, old, bundleContext);
-        module.setBundleContext(bundleContext);
-        return module;
-    }
-
 }
index d3852d28c5ba1ff9d6191f135cbcaba0c88ad2b4..69b17ee3c48aeb5aae64dc8c4b02e36abdfce7a7 100644 (file)
@@ -7,18 +7,16 @@
  */
 package org.opendaylight.controller.config.yang.md.sal.dom.impl;
 
-import com.google.common.collect.ImmutableMap;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
+import java.util.concurrent.Executors;
+
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
 import org.opendaylight.controller.md.sal.dom.broker.impl.DOMDataBrokerImpl;
 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
 import org.opendaylight.controller.sal.core.spi.data.DOMStore;
-import org.osgi.framework.BundleContext;
 
-import java.util.Hashtable;
-import java.util.concurrent.Executors;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
 
 /**
 *
@@ -26,8 +24,6 @@ import java.util.concurrent.Executors;
 public final class DomInmemoryDataBrokerModule extends
         org.opendaylight.controller.config.yang.md.sal.dom.impl.AbstractDomInmemoryDataBrokerModule {
 
-    private BundleContext bundleContext;
-
     public DomInmemoryDataBrokerModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
             final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
         super(identifier, dependencyResolver);
@@ -70,17 +66,6 @@ public final class DomInmemoryDataBrokerModule extends
 
         DOMDataBrokerImpl newDataBroker = new DOMDataBrokerImpl(datastores, MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()));
 
-        getBundleContext().registerService(DOMDataBroker.class, newDataBroker, new Hashtable<String, String>());
-
-
         return newDataBroker;
     }
-
-    private BundleContext getBundleContext() {
-        return bundleContext;
-    }
-
-    void setBundleContext(final BundleContext ctx) {
-        bundleContext = ctx;
-    }
 }
index 91d42c48c13577853ecbc7d3a618bf0b2de93f4e..56a51ed45e75588d40adca6b9613348e3e1c8d9a 100644 (file)
@@ -7,10 +7,6 @@
  */
 package org.opendaylight.controller.config.yang.md.sal.dom.impl;
 
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.spi.Module;
-import org.osgi.framework.BundleContext;
 
 /**
 *
@@ -19,19 +15,4 @@ public class DomInmemoryDataBrokerModuleFactory extends org.opendaylight.control
 {
 
 
-
-    @Override
-    public Module createModule(final String instanceName, final DependencyResolver dependencyResolver, final BundleContext bundleContext) {
-        DomInmemoryDataBrokerModule module = (DomInmemoryDataBrokerModule) super.createModule(instanceName, dependencyResolver, bundleContext);
-        module.setBundleContext(bundleContext);
-        return module;
-    }
-
-    @Override
-    public Module createModule(final String instanceName, final DependencyResolver dependencyResolver,
-            final DynamicMBeanWithInstance old, final BundleContext bundleContext) throws Exception {
-        DomInmemoryDataBrokerModule module = (DomInmemoryDataBrokerModule)  super.createModule(instanceName, dependencyResolver, old, bundleContext);
-        module.setBundleContext(bundleContext);
-        return module;
-    }
 }
index fd24944018c69b3b9480a7018e0fea1c23986719..fbc418dc2aec0203d4f52ad6b7ace8cc083ca019 100644 (file)
@@ -15,7 +15,6 @@ 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.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -57,43 +56,21 @@ org.opendaylight.controller.config.yang.md.sal.dom.impl.AbstractSchemaServiceImp
 
     @Override
     public java.lang.AutoCloseable createInstance() {
-        ServiceReference<SchemaService> ref = getBundleContext().getServiceReference(SchemaService.class);
-        if (ref != null) {
-            return new GlobalSchemaServiceProxy(getBundleContext(), ref);
-        }
-
-        GlobalBundleScanningSchemaServiceImpl newInstance = new GlobalBundleScanningSchemaServiceImpl(getBundleContext());
-        newInstance.start();
-        return newInstance;
+        return GlobalBundleScanningSchemaServiceImpl.getInstance();
     }
 
     public class GlobalSchemaServiceProxy implements AutoCloseable, SchemaService, Delegator<SchemaService> {
 
-        private BundleContext bundleContext;
-        private ServiceReference<SchemaService> reference;
         private SchemaService delegate;
 
-        public GlobalSchemaServiceProxy(final BundleContext bundleContext, final ServiceReference<SchemaService> ref) {
-            this.bundleContext = bundleContext;
-            this.reference = ref;
-            this.delegate = bundleContext.getService(reference);
+        public GlobalSchemaServiceProxy() {
+            this.delegate = GlobalBundleScanningSchemaServiceImpl.getInstance();
         }
 
         @Override
         public void close() throws Exception {
             if (delegate != null) {
                 delegate = null;
-
-                try {
-                    bundleContext.ungetService(reference);
-                } catch (IllegalStateException e) {
-                    // Indicates the service was already unregistered which can happen normally
-                    // on shutdown.
-                    LOG.debug( "Error unregistering service", e );
-                }
-
-                reference = null;
-                bundleContext = null;
             }
         }
 
index 0c07b0684c9b9291344c8f55daadd7d3846ee4da..0be4327f7ae06231cd86814c62c724ddb16fd937 100644 (file)
@@ -75,8 +75,7 @@ abstract class AbstractDOMForwardedCompositeTransaction<K, T extends DOMStoreTra
         return identifier;
     }
 
-    @Override
-    public void close() {
+    protected void closeSubtransactions() {
         /*
          *  We share one exception for all failures, which are added
          *  as supressedExceptions to it.
index 2203087c997ce536485f5359b03ee85c56c1c568..5694d0bca9a68fccd5f31557418a8824b35d7a5a 100644 (file)
@@ -13,7 +13,7 @@ import java.util.Map.Entry;
 import javax.annotation.concurrent.GuardedBy;
 
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
@@ -66,7 +66,7 @@ public abstract class AbstractDOMForwardedTransactionFactory<T extends DOMStoreT
      *
      * Subtransaction for reading is selected by supplied
      * {@link LogicalDatastoreType} as parameter for
-     * {@link DOMDataReadTransaction#read(LogicalDatastoreType,org.opendaylight.yangtools.yang.data.api.InstanceIdentifier)}
+     * {@link DOMDataReadOnlyTransaction#read(LogicalDatastoreType,org.opendaylight.yangtools.yang.data.api.InstanceIdentifier)}
      * .
      *
      * Id of returned transaction is retrieved via
@@ -74,7 +74,7 @@ public abstract class AbstractDOMForwardedTransactionFactory<T extends DOMStoreT
      *
      * @return New composite read-only transaction.
      */
-    public DOMDataReadTransaction newReadOnlyTransaction() {
+    public DOMDataReadOnlyTransaction newReadOnlyTransaction() {
         checkNotClosed();
         ImmutableMap.Builder<LogicalDatastoreType, DOMStoreReadTransaction> builder = ImmutableMap.builder();
         for (Entry<LogicalDatastoreType, T> store : storeTxFactories.entrySet()) {
index 540e2fe20ce52208ffd4a659b5e21c70eafe4b10..13a0093d340b7ef3bc496cf6950d1118ad309ab5 100644 (file)
@@ -6,7 +6,6 @@
  */
 package org.opendaylight.controller.md.sal.dom.broker.impl;
 
-import java.util.Collections;
 import java.util.List;
 import java.util.concurrent.Callable;
 import java.util.concurrent.ExecutionException;
@@ -16,10 +15,9 @@ import javax.annotation.concurrent.GuardedBy;
 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
-import org.opendaylight.controller.sal.common.util.Rpcs;
 import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
-import org.opendaylight.yangtools.yang.common.RpcError;
 import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -221,7 +219,7 @@ public class DOMDataCommitCoordinatorImpl implements DOMDataCommitExecutor {
          */
         private RpcResult<TransactionStatus> commitBlocking() throws TransactionCommitFailedException {
             commitAll().checkedGet();
-            return Rpcs.getRpcResult(true, TransactionStatus.COMMITED, Collections.<RpcError> emptySet());
+            return RpcResultBuilder.<TransactionStatus>success(TransactionStatus.COMMITED).build();
         }
 
         /**
index d2543f02bc548be0430584d926a0ed372c6ccf55..f207783c29f7820e5e472b13359d90f8b92f39db 100644 (file)
@@ -8,7 +8,7 @@
 package org.opendaylight.controller.md.sal.dom.broker.impl;
 
 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
-import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
 import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
@@ -26,7 +26,7 @@ import com.google.common.util.concurrent.ListenableFuture;
  */
 class DOMForwardedReadOnlyTransaction extends
         AbstractDOMForwardedCompositeTransaction<LogicalDatastoreType, DOMStoreReadTransaction> implements
-        DOMDataReadTransaction {
+        DOMDataReadOnlyTransaction {
 
     protected DOMForwardedReadOnlyTransaction(final Object identifier,
             final ImmutableMap<LogicalDatastoreType, DOMStoreReadTransaction> backingTxs) {
@@ -39,4 +39,9 @@ class DOMForwardedReadOnlyTransaction extends
         return getSubtransaction(store).read(path);
     }
 
+    @Override
+    public void close() {
+        closeSubtransactions();
+    }
+
 }
index eeb345e9ce663e7340300f779ab789805be86a7f..f791522a2a77214e9a233f966801fac096948618 100644 (file)
@@ -50,13 +50,31 @@ import com.google.common.util.concurrent.ListenableFuture;
 class DOMForwardedWriteTransaction<T extends DOMStoreWriteTransaction> extends
         AbstractDOMForwardedCompositeTransaction<LogicalDatastoreType, T> implements DOMDataWriteTransaction {
 
+    /**
+     *  Implementation of real commit.
+     *
+     *  Transaction can not be commited if commitImpl is null,
+     *  so this seting this property to null is also used to
+     *  prevent write to
+     *  already commited / canceled transaction {@link #checkNotCanceled()
+     *
+     *
+     */
     @GuardedBy("this")
-    private DOMDataCommitImplementation commitImpl;
-
-    @GuardedBy("this")
-    private boolean canceled;
+    private volatile DOMDataCommitImplementation commitImpl;
+
+    /**
+     *
+     * Future task of transaction commit.
+     *
+     * This value is initially null, and is once updated if transaction
+     * is commited {@link #commit()}.
+     * If this future exists, transaction MUST not be commited again
+     * and all modifications should fail. See {@link #checkNotCommited()}.
+     *
+     */
     @GuardedBy("this")
-    private ListenableFuture<RpcResult<TransactionStatus>> commitFuture;
+    private volatile ListenableFuture<RpcResult<TransactionStatus>> commitFuture;
 
     protected DOMForwardedWriteTransaction(final Object identifier,
             final ImmutableMap<LogicalDatastoreType, T> backingTxs, final DOMDataCommitImplementation commitImpl) {
@@ -83,15 +101,19 @@ class DOMForwardedWriteTransaction<T extends DOMStoreWriteTransaction> extends
     }
 
     @Override
-    public synchronized void cancel() {
-        checkState(!canceled, "Transaction was canceled.");
-        if (commitFuture != null) {
-            // FIXME: Implement cancelation of commit future
-            // when Broker impl will support cancelation.
-            throw new UnsupportedOperationException("Not implemented yet.");
+    public synchronized boolean cancel() {
+        // Transaction is already canceled, we are safe to return true
+        final boolean cancelationResult;
+        if (commitImpl == null && commitFuture != null) {
+            // Transaction is submitted, we try to cancel future.
+            cancelationResult = commitFuture.cancel(false);
+        } else if(commitImpl == null) {
+            return true;
+        } else {
+            cancelationResult = true;
+            commitImpl = null;
         }
-        canceled = true;
-        commitImpl = null;
+        return cancelationResult;
 
     }
 
@@ -105,20 +127,26 @@ class DOMForwardedWriteTransaction<T extends DOMStoreWriteTransaction> extends
         }
         ImmutableList<DOMStoreThreePhaseCommitCohort> cohorts = cohortsBuilder.build();
         commitFuture = commitImpl.commit(this, cohorts);
+
+        /*
+         *We remove reference to Commit Implementation in order
+         *to prevent memory leak
+         */
+        commitImpl = null;
         return commitFuture;
     }
 
     private void checkNotReady() {
-        checkNotCanceled();
         checkNotCommited();
+        checkNotCanceled();
     }
 
     private void checkNotCanceled() {
-        Preconditions.checkState(!canceled, "Transaction was canceled.");
+        Preconditions.checkState(commitImpl != null, "Transaction was canceled.");
     }
 
     private void checkNotCommited() {
-        checkState(commitFuture == null, "Transaction was already commited.");
+        checkState(commitFuture == null, "Transaction was already submited.");
     }
 
 }
\ No newline at end of file
index 5b34fba69ac1b0eaebabaf8a82c801082eacc864..f361af948cb1c600a1c778fe97958cbcef1643d0 100644 (file)
@@ -1,5 +1,7 @@
 package org.opendaylight.controller.md.sal.dom.broker.impl.compat;
 
+import javax.annotation.concurrent.ThreadSafe;
+
 import org.opendaylight.controller.md.sal.common.api.RegistrationListener;
 import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler;
 import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandlerRegistration;
@@ -11,6 +13,7 @@ import org.opendaylight.controller.sal.core.api.data.DataChangeListener;
 import org.opendaylight.controller.sal.core.api.data.DataModificationTransaction;
 import org.opendaylight.controller.sal.core.api.data.DataProviderService;
 import org.opendaylight.controller.sal.core.api.data.DataValidator;
+import org.opendaylight.controller.sal.core.api.model.SchemaService;
 import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.concepts.Registration;
@@ -18,19 +21,18 @@ import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
 
-public class BackwardsCompatibleDataBroker implements DataProviderService, SchemaContextListener {
+@ThreadSafe
+public class BackwardsCompatibleDataBroker implements DataProviderService {
 
     private final DOMDataBroker backingBroker;
-    private DataNormalizer normalizer;
+    private volatile DataNormalizer normalizer;
+    private final ListenerRegistration<SchemaServiceListener> schemaReg;
 
-    public BackwardsCompatibleDataBroker(final DOMDataBroker newBiDataImpl) {
+    public BackwardsCompatibleDataBroker(final DOMDataBroker newBiDataImpl, final SchemaService schemaService) {
         backingBroker = newBiDataImpl;
-    }
-
-    @Override
-    public void onGlobalContextUpdated(final SchemaContext ctx) {
-        normalizer = new DataNormalizer(ctx);
+        schemaReg = schemaService.registerSchemaServiceListener(new SchemaListener());
     }
 
     @Override
@@ -148,4 +150,13 @@ public class BackwardsCompatibleDataBroker implements DataProviderService, Schem
             return listener;
         }
     }
+
+    private class SchemaListener implements SchemaContextListener {
+
+        @Override
+        public void onGlobalContextUpdated(final SchemaContext ctx) {
+            normalizer = new DataNormalizer(ctx);
+        }
+
+    }
 }
index 29f2af511e8b8bb03ab0921837b8acae80aa59a7..27e322f23baf265a046d04317f2bfbf78ab2f74c 100644 (file)
@@ -24,6 +24,7 @@ import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationException;
 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation;
 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
 import org.opendaylight.controller.sal.core.api.data.DataModificationTransaction;
@@ -42,7 +43,7 @@ import com.google.common.base.Preconditions;
 import com.google.common.util.concurrent.ListenableFuture;
 
 public abstract class BackwardsCompatibleTransaction<T extends DOMDataReadTransaction> implements
-        DataModificationTransaction, Delegator<T> {
+DataModificationTransaction, Delegator<T> {
 
     private static final Logger LOG = LoggerFactory.getLogger(BackwardsCompatibleTransaction.class);
 
@@ -55,10 +56,10 @@ public abstract class BackwardsCompatibleTransaction<T extends DOMDataReadTransa
         this.normalizer = normalizer;
     }
 
-    public static BackwardsCompatibleTransaction<?> readOnlyTransaction(final DOMDataReadTransaction readTx,
+    public static BackwardsCompatibleTransaction<?> readOnlyTransaction(final DOMDataReadOnlyTransaction readTx,
             final DataNormalizer normalizer) {
 
-        return new BackwardsCompatibleTransaction<DOMDataReadTransaction>(readTx, normalizer) {
+        return new BackwardsCompatibleTransaction<DOMDataReadOnlyTransaction>(readTx, normalizer) {
 
             @Override
             public TransactionStatus getStatus() {
@@ -227,23 +228,23 @@ public abstract class BackwardsCompatibleTransaction<T extends DOMDataReadTransa
 
             LOG.trace("write {}:{} ",store,normalizedPath);
             try {
-            List<PathArgument> currentArguments = new ArrayList<>();
-            DataNormalizationOperation<?> currentOp = getNormalizer().getRootOperation();
-            Iterator<PathArgument> iterator = normalizedPath.getPath().iterator();
-            while(iterator.hasNext()) {
-                PathArgument currentArg = iterator.next();
-                try {
-                    currentOp = currentOp.getChild(currentArg);
-                } catch (DataNormalizationException e) {
-                    throw new IllegalArgumentException(String.format("Invalid child encountered in path %s", normalizedPath), e);
+                List<PathArgument> currentArguments = new ArrayList<>();
+                DataNormalizationOperation<?> currentOp = getNormalizer().getRootOperation();
+                Iterator<PathArgument> iterator = normalizedPath.getPathArguments().iterator();
+                while(iterator.hasNext()) {
+                    PathArgument currentArg = iterator.next();
+                    try {
+                        currentOp = currentOp.getChild(currentArg);
+                    } catch (DataNormalizationException e) {
+                        throw new IllegalArgumentException(String.format("Invalid child encountered in path %s", normalizedPath), e);
+                    }
+                    currentArguments.add(currentArg);
+                    InstanceIdentifier currentPath = InstanceIdentifier.create(currentArguments);
+                    boolean isPresent = getDelegate().read(store, currentPath).get().isPresent();
+                    if(isPresent == false && iterator.hasNext()) {
+                        getDelegate().merge(store, currentPath, currentOp.createDefault(currentArg));
+                    }
                 }
-                currentArguments.add(currentArg);
-                InstanceIdentifier currentPath = new InstanceIdentifier(currentArguments);
-                boolean isPresent = getDelegate().read(store, currentPath).get().isPresent();
-                if(isPresent == false && iterator.hasNext()) {
-                    getDelegate().merge(store, currentPath, currentOp.createDefault(currentArg));
-                }
-            }
             } catch (InterruptedException | ExecutionException e) {
                 LOG.error("Exception durring read.",e);
             }
diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/BrokerConfigActivator.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/BrokerConfigActivator.java
deleted file mode 100644 (file)
index 3291afa..0000000
+++ /dev/null
@@ -1,134 +0,0 @@
-/**
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.dom.broker;
-
-import java.util.Hashtable;
-
-import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
-import org.opendaylight.controller.md.sal.dom.broker.impl.compat.BackwardsCompatibleDataBroker;
-import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
-import org.opendaylight.controller.sal.core.api.data.DataBrokerService;
-import org.opendaylight.controller.sal.core.api.data.DataProviderService;
-import org.opendaylight.controller.sal.core.api.data.DataStore;
-import org.opendaylight.controller.sal.core.api.model.SchemaService;
-import org.opendaylight.controller.sal.core.api.mount.MountProvisionService;
-import org.opendaylight.controller.sal.core.api.mount.MountService;
-import org.opendaylight.controller.sal.dom.broker.impl.SchemaAwareDataStoreAdapter;
-import org.opendaylight.controller.sal.dom.broker.impl.SchemaAwareRpcBroker;
-import org.opendaylight.controller.sal.dom.broker.impl.SchemaContextProviders;
-import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.model.api.SchemaServiceListener;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.osgi.framework.ServiceRegistration;
-
-public class BrokerConfigActivator implements AutoCloseable {
-
-    private static InstanceIdentifier ROOT = InstanceIdentifier.builder()
-            .toInstance();
-
-    private DataProviderService dataService;
-
-    private ServiceRegistration<DataBrokerService> dataReg = null;
-    private ServiceRegistration<DataProviderService> dataProviderReg = null;
-    private ServiceRegistration<MountService> mountReg = null;
-    private ServiceRegistration<MountProvisionService> mountProviderReg = null;
-    private SchemaService schemaService = null;
-    private ServiceRegistration<RpcProvisionRegistry> rpcProvisionRegistryReg = null;
-    private MountPointManagerImpl mountService = null;
-
-    private SchemaAwareDataStoreAdapter wrappedStore = null;
-
-    public void start(final BrokerImpl broker, final DataStore store,
-            final DOMDataBroker asyncBroker, final BundleContext context) {
-
-        final Hashtable<String, String> emptyProperties = new Hashtable<String, String>();
-        broker.setBundleContext(context);
-
-        final ServiceReference<SchemaService> serviceRef = context
-                .getServiceReference(SchemaService.class);
-        schemaService = context.<SchemaService> getService(serviceRef);
-
-        broker.setRouter(new SchemaAwareRpcBroker("/", SchemaContextProviders
-                .fromSchemaService(schemaService)));
-
-        if (asyncBroker == null) {
-            dataService = new DataBrokerImpl();
-            dataProviderReg = context.registerService(
-                    DataProviderService.class, dataService, emptyProperties);
-
-            wrappedStore = new SchemaAwareDataStoreAdapter();
-            wrappedStore.changeDelegate(store);
-            wrappedStore.setValidationEnabled(false);
-            context.registerService(SchemaServiceListener.class, wrappedStore,
-                    emptyProperties);
-
-            dataService.registerConfigurationReader(ROOT, wrappedStore);
-            dataService.registerCommitHandler(ROOT, wrappedStore);
-            dataService.registerOperationalReader(ROOT, wrappedStore);
-        } else {
-            BackwardsCompatibleDataBroker compatibleDataBroker = new BackwardsCompatibleDataBroker(
-                    asyncBroker);
-            context.registerService(SchemaServiceListener.class,
-                    compatibleDataBroker, emptyProperties);
-            dataService = compatibleDataBroker;
-        }
-
-        mountService = new MountPointManagerImpl();
-        dataReg = context.registerService(DataBrokerService.class, dataService,
-                emptyProperties);
-        mountReg = context.registerService(MountService.class, mountService,
-                emptyProperties);
-        mountProviderReg = context.registerService(MountProvisionService.class,
-                mountService, emptyProperties);
-
-        rpcProvisionRegistryReg = context
-                .registerService(RpcProvisionRegistry.class,
-                        broker.getRouter(), emptyProperties);
-    }
-
-    @Override
-    public void close() {
-
-        if (dataReg != null) {
-            dataReg.unregister();
-            dataReg = null;
-        }
-        if (dataProviderReg != null) {
-            dataProviderReg.unregister();
-            dataProviderReg = null;
-        }
-        if (mountReg != null) {
-            mountReg.unregister();
-            mountReg = null;
-        }
-        if (mountProviderReg != null) {
-            mountProviderReg.unregister();
-            mountProviderReg = null;
-        }
-        if (rpcProvisionRegistryReg != null) {
-            rpcProvisionRegistryReg.unregister();
-            rpcProvisionRegistryReg = null;
-        }
-    }
-
-    /**
-     * @return the dataService
-     */
-    public DataProviderService getDataService() {
-        return dataService;
-    }
-
-    /**
-     * @param dataService
-     *            the dataService to set
-     */
-    public void setDataService(final DataProviderService dataService) {
-        this.dataService = dataService;
-    }
-}
index e4bd0343cfcf62999d3becca52177eaf8d366bcd..1af03e50465e2acc922f19ad66f15a3c640bfc34 100644 (file)
@@ -7,9 +7,6 @@
  */
 package org.opendaylight.controller.sal.dom.broker;
 
-import com.google.common.base.Preconditions;
-import com.google.common.util.concurrent.ListenableFuture;
-
 import java.util.Collections;
 import java.util.HashSet;
 import java.util.Set;
@@ -17,22 +14,29 @@ import java.util.concurrent.Future;
 
 import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
 import org.opendaylight.controller.sal.core.api.Broker;
+import org.opendaylight.controller.sal.core.api.BrokerService;
 import org.opendaylight.controller.sal.core.api.Consumer;
 import org.opendaylight.controller.sal.core.api.Provider;
+import org.opendaylight.controller.sal.core.api.RoutedRpcDefaultImplementation;
+import org.opendaylight.controller.sal.core.api.RpcImplementation;
+import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
+import org.opendaylight.controller.sal.core.api.RpcRegistrationListener;
+import org.opendaylight.controller.sal.core.api.RpcRoutingContext;
+import org.opendaylight.controller.sal.dom.broker.spi.RpcRouter;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.osgi.framework.BundleContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import org.opendaylight.controller.sal.dom.broker.spi.RpcRouter;
-import org.opendaylight.controller.sal.core.api.RpcRegistrationListener;
-import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
-import org.opendaylight.controller.sal.core.api.RpcImplementation;
-import org.opendaylight.controller.sal.core.api.RpcRoutingContext;
-import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
-import org.opendaylight.controller.sal.core.api.RoutedRpcDefaultImplementation;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ClassToInstanceMap;
+import com.google.common.collect.ImmutableClassToInstanceMap;
+import com.google.common.util.concurrent.ListenableFuture;
 
 public class BrokerImpl implements Broker, RpcProvisionRegistry, AutoCloseable {
     private final static Logger log = LoggerFactory.getLogger(BrokerImpl.class);
@@ -43,12 +47,18 @@ public class BrokerImpl implements Broker, RpcProvisionRegistry, AutoCloseable {
     private final Set<ProviderContextImpl> providerSessions = Collections
             .synchronizedSet(new HashSet<ProviderContextImpl>());
 
-    private BundleContext bundleContext = null;
-
     private AutoCloseable deactivator = null;
 
     private RpcRouter router = null;
 
+    private final ClassToInstanceMap<BrokerService> services;
+
+    public  BrokerImpl(final RpcRouter router,final ClassToInstanceMap<BrokerService> services) {
+        this.router = Preconditions.checkNotNull(router, "RPC Router must not be null");
+        this.services = ImmutableClassToInstanceMap.copyOf(services);
+    }
+
+
     @Override
     public ConsumerSession registerConsumer(final Consumer consumer,
             final BundleContext ctx) {
@@ -79,8 +89,9 @@ public class BrokerImpl implements Broker, RpcProvisionRegistry, AutoCloseable {
     private void checkPredicates(final Provider prov) {
         Preconditions.checkNotNull(prov, "Provider should not be null.");
         for (ProviderContextImpl session : providerSessions) {
-            if (prov.equals(session.getProvider()))
+            if (prov.equals(session.getProvider())) {
                 throw new IllegalStateException("Provider already registered");
+            }
         }
 
     }
@@ -88,23 +99,22 @@ public class BrokerImpl implements Broker, RpcProvisionRegistry, AutoCloseable {
     private void checkPredicates(final Consumer cons) {
         Preconditions.checkNotNull(cons, "Consumer should not be null.");
         for (ConsumerContextImpl session : sessions) {
-            if (cons.equals(session.getConsumer()))
+            if (cons.equals(session.getConsumer())) {
                 throw new IllegalStateException("Consumer already registered");
+            }
         }
     }
 
     // Private Factory methods
     private ConsumerContextImpl newSessionFor(final Consumer provider,
             final BundleContext ctx) {
-        ConsumerContextImpl ret = new ConsumerContextImpl(provider, ctx);
-        ret.setBroker(this);
+        ConsumerContextImpl ret = new ConsumerContextImpl(provider, this);
         return ret;
     }
 
     private ProviderContextImpl newSessionFor(final Provider provider,
             final BundleContext ctx) {
-        ProviderContextImpl ret = new ProviderContextImpl(provider, ctx);
-        ret.setBroker(this);
+        ProviderContextImpl ret = new ProviderContextImpl(provider, this);
         return ret;
     }
 
@@ -164,21 +174,6 @@ public class BrokerImpl implements Broker, RpcProvisionRegistry, AutoCloseable {
         return router.invokeRpc(rpc, input);
     }
 
-    /**
-     * @return the bundleContext
-     */
-    public BundleContext getBundleContext() {
-        return bundleContext;
-    }
-
-    /**
-     * @param bundleContext
-     *            the bundleContext to set
-     */
-    public void setBundleContext(final BundleContext bundleContext) {
-        this.bundleContext = bundleContext;
-    }
-
     /**
      * @return the deactivator
      */
@@ -208,4 +203,9 @@ public class BrokerImpl implements Broker, RpcProvisionRegistry, AutoCloseable {
     public void setRouter(final RpcRouter router) {
         this.router = router;
     }
+
+    protected <T extends BrokerService> Optional<T> getGlobalService(final Class<T> service) {
+        return Optional.fromNullable(services.getInstance(service));
+    }
+
 }
index fa81bc9040849c6b198187c4d846de308bfbe685..e96b242720e88bbabe918cbde127af6eb0b3d5e8 100644 (file)
@@ -20,9 +20,9 @@ import org.opendaylight.controller.sal.dom.broker.osgi.ProxyFactory;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
 
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
 import com.google.common.collect.ClassToInstanceMap;
 import com.google.common.collect.MutableClassToInstanceMap;
 
@@ -30,41 +30,39 @@ class ConsumerContextImpl implements ConsumerSession {
 
     private final ClassToInstanceMap<BrokerService> instantiatedServices = MutableClassToInstanceMap
             .create();
-    private final BundleContext context;
     private final Consumer consumer;
 
     private BrokerImpl broker = null;
     @GuardedBy("this")
     private boolean closed = false;
 
-    public ConsumerContextImpl(final Consumer consumer, final BundleContext ctx) {
-        this.consumer = consumer;
-        this.context = ctx;
+    public ConsumerContextImpl(final Consumer provider, final BrokerImpl brokerImpl) {
+        broker = brokerImpl;
+        consumer = provider;
     }
 
     @Override
     public Future<RpcResult<CompositeNode>> rpc(final QName rpc,
             final CompositeNode input) {
+        checkNotClosed();
         return broker.invokeRpcAsync(rpc, input);
     }
 
     @Override
     public <T extends BrokerService> T getService(final Class<T> service) {
+        checkNotClosed();
         final T localProxy = instantiatedServices.getInstance(service);
         if (localProxy != null) {
             return localProxy;
         }
-        final ServiceReference<T> serviceRef = context
-                .getServiceReference(service);
-        if (serviceRef == null) {
-            return null;
-        }
-        final T serviceImpl = context.getService(serviceRef);
-        final T ret = ProxyFactory.createProxy(serviceRef, serviceImpl);
-        if (ret != null) {
+        final Optional<T> serviceImpl = broker.getGlobalService(service);
+        if(serviceImpl.isPresent()) {
+            final T ret = ProxyFactory.createProxy(null,serviceImpl.get());
             instantiatedServices.putInstance(service, ret);
+            return ret;
+        } else {
+            return null;
         }
-        return ret;
     }
 
     @Override
@@ -83,6 +81,7 @@ class ConsumerContextImpl implements ConsumerSession {
             }
         }
         broker.consumerSessionClosed(this);
+        broker = null;
     }
 
     @Override
@@ -93,22 +92,19 @@ class ConsumerContextImpl implements ConsumerSession {
     /**
      * @return the broker
      */
-    public BrokerImpl getBroker() {
+    protected final  BrokerImpl getBrokerChecked() {
+        checkNotClosed();
         return broker;
     }
 
-    /**
-     * @param broker
-     *            the broker to set
-     */
-    public void setBroker(final BrokerImpl broker) {
-        this.broker = broker;
-    }
-
     /**
      * @return the _consumer
      */
     public Consumer getConsumer() {
         return consumer;
     }
+
+    protected final void checkNotClosed()  {
+        Preconditions.checkState(!closed, "Session is closed.");
+    }
 }
index 430963a884b4fbaa71a7c3c12d5df9356058be0c..60a7e81c4c046183e6ee59e0f27d48e5a15e90bc 100644 (file)
@@ -9,6 +9,7 @@ package org.opendaylight.controller.sal.dom.broker;
 
 import static com.google.common.base.Preconditions.checkState;
 
+import com.google.common.annotations.VisibleForTesting;
 import java.net.URL;
 import java.util.ArrayList;
 import java.util.Collections;
@@ -50,11 +51,29 @@ public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvi
     private ServiceTracker<SchemaServiceListener, SchemaServiceListener> listenerTracker;
     private BundleTracker<Iterable<Registration<URL>>> bundleTracker;
     private boolean starting = true;
+    private static GlobalBundleScanningSchemaServiceImpl instance;
 
-    public GlobalBundleScanningSchemaServiceImpl(final BundleContext context) {
+    private GlobalBundleScanningSchemaServiceImpl(final BundleContext context) {
         this.context = Preconditions.checkNotNull(context);
     }
 
+    public synchronized static GlobalBundleScanningSchemaServiceImpl createInstance(final BundleContext ctx) {
+        Preconditions.checkState(instance == null);
+        instance = new GlobalBundleScanningSchemaServiceImpl(ctx);
+        instance.start();
+        return instance;
+    }
+
+    public synchronized static GlobalBundleScanningSchemaServiceImpl getInstance() {
+        Preconditions.checkState(instance != null, "Global Instance was not instantiated");
+        return instance;
+    }
+
+    @VisibleForTesting
+    public static synchronized void destroyInstance() {
+        instance = null;
+    }
+
     public BundleContext getContext() {
         return context;
     }
@@ -96,7 +115,7 @@ public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvi
     }
 
     @Override
-    public ListenerRegistration<SchemaServiceListener> registerSchemaServiceListener(final SchemaServiceListener listener) {
+    public synchronized ListenerRegistration<SchemaServiceListener> registerSchemaServiceListener(final SchemaServiceListener listener) {
         Optional<SchemaContext> potentialCtx = contextResolver.getSchemaContext();
         if(potentialCtx.isPresent()) {
             listener.onGlobalContextUpdated(potentialCtx.get());
@@ -116,7 +135,7 @@ public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvi
     }
 
 
-    private void updateContext(final SchemaContext snapshot) {
+    private synchronized void updateContext(final SchemaContext snapshot) {
         Object[] services = listenerTracker.getServices();
         for (ListenerRegistration<SchemaServiceListener> listener : listeners) {
             try {
@@ -194,7 +213,7 @@ public class GlobalBundleScanningSchemaServiceImpl implements SchemaContextProvi
     }
 
     @Override
-    public SchemaServiceListener addingService(final ServiceReference<SchemaServiceListener> reference) {
+    public synchronized SchemaServiceListener addingService(final ServiceReference<SchemaServiceListener> reference) {
 
         SchemaServiceListener listener = context.getService(reference);
         SchemaContext _ctxContext = getGlobalContext();
index 623bbdb19514ce15ffa0b9102959fbac77cb51d2..e69343d4fe82c7f36a7a9c378c8669e67cb1114b 100644 (file)
@@ -54,7 +54,7 @@ public class MountPointImpl implements MountProvisionInstance, SchemaContextProv
 
     private SchemaContext schemaContext;
 
-    public MountPointImpl(InstanceIdentifier path) {
+    public MountPointImpl(final InstanceIdentifier path) {
         this.mountPath = path;
         rpcs = new SchemaAwareRpcBroker(path.toString(),this);
         dataReader = new DataBrokerImpl();
@@ -71,49 +71,49 @@ public class MountPointImpl implements MountProvisionInstance, SchemaContextProv
     }
 
     @Override
-    public void publish(CompositeNode notification) {
+    public void publish(final CompositeNode notification) {
         notificationRouter.publish(notification);
     }
 
     @Override
-    public Registration<NotificationListener> addNotificationListener(QName notification, NotificationListener listener) {
+    public Registration<NotificationListener> addNotificationListener(final QName notification, final NotificationListener listener) {
         return notificationRouter.addNotificationListener(notification, listener);
     }
 
     @Override
-    public CompositeNode readConfigurationData(InstanceIdentifier path) {
+    public CompositeNode readConfigurationData(final InstanceIdentifier path) {
         return dataReader.readConfigurationData(path);
     }
 
     @Override
-    public CompositeNode readOperationalData(InstanceIdentifier path) {
+    public CompositeNode readOperationalData(final InstanceIdentifier path) {
         return dataReader.readOperationalData(path);
     }
 
     @Override
     public Registration<DataReader<InstanceIdentifier, CompositeNode>> registerOperationalReader(
-            InstanceIdentifier path, DataReader<InstanceIdentifier, CompositeNode> reader) {
+            final InstanceIdentifier path, final DataReader<InstanceIdentifier, CompositeNode> reader) {
         return dataReader.registerOperationalReader(path, reader);
     }
 
     @Override
     public Registration<DataReader<InstanceIdentifier, CompositeNode>> registerConfigurationReader(
-            InstanceIdentifier path, DataReader<InstanceIdentifier, CompositeNode> reader) {
+            final InstanceIdentifier path, final DataReader<InstanceIdentifier, CompositeNode> reader) {
         return dataReader.registerConfigurationReader(path, reader);
     }
 
     @Override
-    public RoutedRpcRegistration addRoutedRpcImplementation(QName rpcType, RpcImplementation implementation) {
+    public RoutedRpcRegistration addRoutedRpcImplementation(final QName rpcType, final RpcImplementation implementation) {
         return rpcs.addRoutedRpcImplementation(rpcType, implementation);
     }
 
     @Override
-    public void setRoutedRpcDefaultDelegate(RoutedRpcDefaultImplementation defaultImplementation) {
-      rpcs.setRoutedRpcDefaultDelegate(defaultImplementation);
+    public void setRoutedRpcDefaultDelegate(final RoutedRpcDefaultImplementation defaultImplementation) {
+        rpcs.setRoutedRpcDefaultDelegate(defaultImplementation);
     }
 
-  @Override
-    public RpcRegistration addRpcImplementation(QName rpcType, RpcImplementation implementation)
+    @Override
+    public RpcRegistration addRpcImplementation(final QName rpcType, final RpcImplementation implementation)
             throws IllegalArgumentException {
         return rpcs.addRpcImplementation(rpcType, implementation);
     }
@@ -124,17 +124,17 @@ public class MountPointImpl implements MountProvisionInstance, SchemaContextProv
     }
 
     @Override
-    public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(QName rpc, CompositeNode input) {
+    public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(final QName rpc, final CompositeNode input) {
         return rpcs.invokeRpc(rpc, input);
     }
 
     @Override
-    public ListenerRegistration<RpcRegistrationListener> addRpcRegistrationListener(RpcRegistrationListener listener) {
+    public ListenerRegistration<RpcRegistrationListener> addRpcRegistrationListener(final RpcRegistrationListener listener) {
         return rpcs.addRpcRegistrationListener(listener);
     }
 
     @Override
-    public ListenableFuture<RpcResult<CompositeNode>> rpc(QName type, CompositeNode input) {
+    public ListenableFuture<RpcResult<CompositeNode>> rpc(final QName type, final CompositeNode input) {
         return rpcs.invokeRpc( type, input );
     }
 
@@ -144,33 +144,33 @@ public class MountPointImpl implements MountProvisionInstance, SchemaContextProv
     }
 
     @Override
-    public ListenerRegistration<DataChangeListener> registerDataChangeListener(InstanceIdentifier path,
-            DataChangeListener listener) {
+    public ListenerRegistration<DataChangeListener> registerDataChangeListener(final InstanceIdentifier path,
+            final DataChangeListener listener) {
         return dataReader.registerDataChangeListener(path, listener);
     }
 
     @Override
     public Registration<DataCommitHandler<InstanceIdentifier, CompositeNode>> registerCommitHandler(
-            InstanceIdentifier path, DataCommitHandler<InstanceIdentifier, CompositeNode> commitHandler) {
+            final InstanceIdentifier path, final DataCommitHandler<InstanceIdentifier, CompositeNode> commitHandler) {
         return dataReader.registerCommitHandler(path, commitHandler);
     }
 
     @Override
-    public void removeRefresher(DataStoreIdentifier store, DataRefresher refresher) {
-     // NOOP
+    public void removeRefresher(final DataStoreIdentifier store, final DataRefresher refresher) {
+        // NOOP
     }
 
     @Override
-    public void addRefresher(DataStoreIdentifier store, DataRefresher refresher) {
-     // NOOP
+    public void addRefresher(final DataStoreIdentifier store, final DataRefresher refresher) {
+        // NOOP
     }
 
     @Override
-    public void addValidator(DataStoreIdentifier store, DataValidator validator) {
-     // NOOP
+    public void addValidator(final DataStoreIdentifier store, final DataValidator validator) {
+        // NOOP
     }
     @Override
-    public void removeValidator(DataStoreIdentifier store, DataValidator validator) {
+    public void removeValidator(final DataStoreIdentifier store, final DataValidator validator) {
         // NOOP
     }
 
@@ -180,24 +180,22 @@ public class MountPointImpl implements MountProvisionInstance, SchemaContextProv
     }
 
     @Override
-    public void setSchemaContext(SchemaContext schemaContext) {
+    public void setSchemaContext(final SchemaContext schemaContext) {
         this.schemaContext = schemaContext;
     }
 
     class ReadWrapper implements DataReader<InstanceIdentifier, CompositeNode> {
-
-
-        private InstanceIdentifier shortenPath(InstanceIdentifier path) {
+        private InstanceIdentifier shortenPath(final InstanceIdentifier path) {
             InstanceIdentifier ret = null;
             if(mountPath.contains(path)) {
                 List<PathArgument> newArgs = path.getPath().subList(mountPath.getPath().size(), path.getPath().size());
-                ret = new InstanceIdentifier(newArgs);
+                ret = InstanceIdentifier.create(newArgs);
             }
             return ret;
         }
 
         @Override
-        public CompositeNode readConfigurationData(InstanceIdentifier path) {
+        public CompositeNode readConfigurationData(final InstanceIdentifier path) {
             InstanceIdentifier newPath = shortenPath(path);
             if(newPath == null) {
                 return null;
@@ -206,7 +204,7 @@ public class MountPointImpl implements MountProvisionInstance, SchemaContextProv
         }
 
         @Override
-        public CompositeNode readOperationalData(InstanceIdentifier path) {
+        public CompositeNode readOperationalData(final InstanceIdentifier path) {
             InstanceIdentifier newPath = shortenPath(path);
             if(newPath == null) {
                 return null;
@@ -217,13 +215,13 @@ public class MountPointImpl implements MountProvisionInstance, SchemaContextProv
 
     @Override
     public ListenerRegistration<RegistrationListener<DataCommitHandlerRegistration<InstanceIdentifier, CompositeNode>>> registerCommitHandlerListener(
-            RegistrationListener<DataCommitHandlerRegistration<InstanceIdentifier, CompositeNode>> commitHandlerListener) {
+            final RegistrationListener<DataCommitHandlerRegistration<InstanceIdentifier, CompositeNode>> commitHandlerListener) {
         return dataReader.registerCommitHandlerListener(commitHandlerListener);
     }
 
     @Override
     public <L extends RouteChangeListener<RpcRoutingContext, InstanceIdentifier>> ListenerRegistration<L> registerRouteChangeListener(
-            L listener) {
+            final L listener) {
         return rpcs.registerRouteChangeListener(listener);
     }
 }
diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/NotificationModule.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/NotificationModule.java
deleted file mode 100644 (file)
index b298a02..0000000
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.dom.broker;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
-import org.opendaylight.controller.sal.core.api.Broker.ConsumerSession;
-import org.opendaylight.controller.sal.core.api.Broker.ProviderSession;
-import org.opendaylight.controller.sal.core.api.BrokerService;
-import org.opendaylight.controller.sal.core.api.Consumer.ConsumerFunctionality;
-import org.opendaylight.controller.sal.core.api.Provider.ProviderFunctionality;
-import org.opendaylight.controller.sal.core.api.notify.NotificationListener;
-import org.opendaylight.controller.sal.core.api.notify.NotificationPublishService;
-import org.opendaylight.controller.sal.core.api.notify.NotificationService;
-import org.opendaylight.controller.sal.core.spi.BrokerModule;
-import org.opendaylight.yangtools.concepts.Registration;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.collect.HashMultimap;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.Multimap;
-
-public class NotificationModule implements BrokerModule {
-    private static Logger log = LoggerFactory
-            .getLogger(NotificationModule.class);
-
-    private final Multimap<QName, NotificationListener> listeners = HashMultimap
-            .create();
-
-    private static final Set<Class<? extends BrokerService>> PROVIDED_SERVICE_TYPE = ImmutableSet
-            .<Class<? extends BrokerService>>of(NotificationService.class,
-                    NotificationPublishService.class);
-
-    private static final Set<Class<? extends ConsumerFunctionality>> SUPPORTED_CONSUMER_FUNCTIONALITY = ImmutableSet
-            .of((Class<? extends ConsumerFunctionality>) NotificationListener.class,
-                    NotificationListener.class); // Workaround: if we use the
-                                                 // version of method with only
-                                                 // one argument, the generics
-                                                 // inference will not work
-
-    @Override
-    public Set<Class<? extends BrokerService>> getProvidedServices() {
-        return PROVIDED_SERVICE_TYPE;
-    }
-
-    @Override
-    public Set<Class<? extends ConsumerFunctionality>> getSupportedConsumerFunctionality() {
-        return SUPPORTED_CONSUMER_FUNCTIONALITY;
-    }
-
-    @Override
-    public <T extends BrokerService> T getServiceForSession(Class<T> service,
-            ConsumerSession session) {
-        if (NotificationPublishService.class.equals(service)
-                && session instanceof ProviderSession) {
-            @SuppressWarnings("unchecked")
-            T ret = (T) newNotificationPublishService(session);
-            return ret;
-        } else if (NotificationService.class.equals(service)) {
-
-            @SuppressWarnings("unchecked")
-            T ret = (T) newNotificationConsumerService(session);
-            return ret;
-        }
-
-        throw new IllegalArgumentException(
-                "The requested session-specific service is not provided by this module.");
-    }
-
-    private void sendNotification(CompositeNode notification) {
-        QName type = notification.getNodeType();
-        Collection<NotificationListener> toNotify = listeners.get(type);
-        log.trace("Publishing notification " + type);
-
-        if (toNotify == null) {
-            // No listeners were registered - returns.
-            return;
-        }
-
-        for (NotificationListener listener : toNotify) {
-            try {
-                // FIXME: ensure that notification is immutable
-                listener.onNotification(notification);
-            } catch (Exception e) {
-                log.error("Uncaught exception in NotificationListener", e);
-            }
-        }
-
-    }
-
-    private NotificationService newNotificationConsumerService(
-            ConsumerSession session) {
-        return new NotificationConsumerSessionImpl();
-    }
-
-    private NotificationPublishService newNotificationPublishService(
-            ConsumerSession session) {
-        return new NotificationProviderSessionImpl();
-    }
-
-    private class NotificationConsumerSessionImpl implements
-            NotificationService {
-
-        private final Multimap<QName, NotificationListener> consumerListeners = HashMultimap
-                .create();
-        private boolean closed = false;
-
-
-        @Override
-        public Registration<NotificationListener> addNotificationListener(QName notification,
-                NotificationListener listener) {
-            checkSessionState();
-            if (notification == null) {
-                throw new IllegalArgumentException(
-                        "Notification type must not be null.");
-            }
-            if (listener == null) {
-                throw new IllegalArgumentException("Listener must not be null.");
-            }
-
-            consumerListeners.put(notification, listener);
-            listeners.put(notification, listener);
-            log.trace("Registered listener for notification: " + notification);
-            return null; // Return registration Object.
-        }
-
-        public void removeNotificationListener(QName notification,
-                NotificationListener listener) {
-            checkSessionState();
-            if (notification == null) {
-                throw new IllegalArgumentException(
-                        "Notification type must not be null.");
-            }
-            if (listener == null) {
-                throw new IllegalArgumentException("Listener must not be null.");
-            }
-            consumerListeners.remove(notification, listener);
-            listeners.remove(notification, listener);
-        }
-
-        public void closeSession() {
-            closed = true;
-            Map<QName, Collection<NotificationListener>> toRemove = consumerListeners
-                    .asMap();
-            for (Entry<QName, Collection<NotificationListener>> entry : toRemove
-                    .entrySet()) {
-                listeners.remove(entry.getKey(), entry.getValue());
-            }
-        }
-
-        protected void checkSessionState() {
-            if (closed)
-                throw new IllegalStateException("Session is closed");
-        }
-    }
-
-    private class NotificationProviderSessionImpl extends
-            NotificationConsumerSessionImpl implements
-            NotificationPublishService {
-
-        @Override
-        public void publish(CompositeNode notification) {
-            checkSessionState();
-            if (notification == null)
-                throw new IllegalArgumentException(
-                        "Notification must not be null.");
-            NotificationModule.this.sendNotification(notification);
-        }
-    }
-
-    @Override
-    public Set<Class<? extends ProviderFunctionality>> getSupportedProviderFunctionality() {
-        return Collections.emptySet();
-    }
-}
index 5e8c0e82538b4d2beacddd3366571ac2a734f7c5..b8bb279297cf835cb185d909d6eaf280dccc59d7 100644 (file)
@@ -18,21 +18,20 @@ import org.opendaylight.controller.sal.core.api.RpcImplementation;
 import org.opendaylight.controller.sal.core.api.RpcRegistrationListener;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.osgi.framework.BundleContext;
 
 class ProviderContextImpl extends ConsumerContextImpl implements ProviderSession {
     private final Set<RpcRegistrationWrapper> registrations = new HashSet<>();
     private final Provider provider;
 
-    public ProviderContextImpl(final Provider provider, final BundleContext ctx) {
-        super(null, ctx);
+    public ProviderContextImpl(final Provider provider, final BrokerImpl broker) {
+        super(null, broker);
         this.provider = provider;
     }
 
     @Override
     public RpcRegistrationWrapper addRpcImplementation(final QName rpcType,
             final RpcImplementation implementation) throws IllegalArgumentException {
-        final RpcRegistration origReg = getBroker().getRouter()
+        final RpcRegistration origReg = getBrokerChecked().getRouter()
                 .addRpcImplementation(rpcType, implementation);
         final RpcRegistrationWrapper newReg = new RpcRegistrationWrapper(
                 origReg);
@@ -56,24 +55,24 @@ class ProviderContextImpl extends ConsumerContextImpl implements ProviderSession
             final QName rpcType, final RpcImplementation implementation) {
         throw new UnsupportedOperationException(
                 "TODO: auto-generated method stub");
+
     }
 
     @Override
     public RoutedRpcRegistration addRoutedRpcImplementation(
             final QName rpcType, final RpcImplementation implementation) {
-        throw new UnsupportedOperationException(
-                "TODO: auto-generated method stub");
+        return getBrokerChecked().getRouter().addRoutedRpcImplementation(rpcType, implementation);
     }
 
     @Override
     public Set<QName> getSupportedRpcs() {
-        return getBroker().getRouter().getSupportedRpcs();
+        return getBrokerChecked().getRouter().getSupportedRpcs();
     }
 
     @Override
     public ListenerRegistration<RpcRegistrationListener> addRpcRegistrationListener(
             final RpcRegistrationListener listener) {
-        return getBroker().getRouter().addRpcRegistrationListener(listener);
+        return getBrokerChecked().getRouter().addRpcRegistrationListener(listener);
     }
 
     /**
index ba9b2b7f55964d90023532082bc41767f037daa4..4b5b86d0dafd2cc08df1f7c9a31086350e3b3512 100644 (file)
@@ -9,6 +9,8 @@ package org.opendaylight.controller.sal.dom.broker.impl;
 
 import static com.google.common.base.Preconditions.checkState;
 
+import com.google.common.collect.Iterables;
+
 import java.net.URI;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -32,8 +34,6 @@ import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.collect.Iterables;
-
 public class DataReaderRouter extends
 AbstractDataReadRouter<InstanceIdentifier, CompositeNode> {
     private final static Logger LOG = LoggerFactory
@@ -46,7 +46,7 @@ AbstractDataReadRouter<InstanceIdentifier, CompositeNode> {
     @Override
     protected CompositeNodeTOImpl merge(final InstanceIdentifier path,
             final Iterable<CompositeNode> data) {
-        PathArgument pathArgument = Iterables.getLast(path.getPath(), null);
+        PathArgument pathArgument = Iterables.getLast(path.getPathArguments(), null);
         boolean empty = true;
         QName name = (pathArgument == null ? null : pathArgument.getNodeType());
         final ArrayList<Node<?>> nodes = new ArrayList<Node<?>>();
diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/GlobalRpcRegistration.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/GlobalRpcRegistration.java
new file mode 100644 (file)
index 0000000..f63e5ea
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.sal.dom.broker.impl;
+
+import org.opendaylight.controller.sal.core.api.Broker.RpcRegistration;
+import org.opendaylight.controller.sal.core.api.RpcImplementation;
+import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
+import org.opendaylight.yangtools.yang.common.QName;
+
+class GlobalRpcRegistration extends AbstractObjectRegistration<RpcImplementation> implements
+        RpcRegistration {
+    private final QName type;
+    private SchemaAwareRpcBroker router;
+
+    public GlobalRpcRegistration(final QName type, final RpcImplementation instance, final SchemaAwareRpcBroker router) {
+        super(instance);
+        this.type = type;
+        this.router = router;
+    }
+
+    @Override
+    public QName getType() {
+        return type;
+    }
+
+    @Override
+    protected void removeRegistration() {
+        if (router != null) {
+            router.remove(this);
+            router = null;
+        }
+    }
+}
\ No newline at end of file
index 50dfbe852b4d7241e08fba0686c6253068a59492..d7309b9ed31717ebe8641bdc4bee5f15ce8d948f 100644 (file)
@@ -7,7 +7,6 @@
  */
 package org.opendaylight.controller.sal.dom.broker.impl;
 
-import java.util.Collections;
 import java.util.HashSet;
 import java.util.Map;
 import java.util.Set;
@@ -15,10 +14,9 @@ import java.util.concurrent.ConcurrentHashMap;
 
 import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler;
 import org.opendaylight.controller.md.sal.common.api.data.DataModification;
-import org.opendaylight.controller.sal.common.util.Rpcs;
 import org.opendaylight.controller.sal.core.api.data.DataStore;
-import org.opendaylight.yangtools.yang.common.RpcError;
 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.InstanceIdentifier;
 import org.slf4j.Logger;
@@ -70,8 +68,7 @@ public final class HashMapDataStore implements DataStore, AutoCloseable {
     }
 
     public RpcResult<Void> rollback(HashMapDataStoreTransaction transaction) {
-        return Rpcs.<Void> getRpcResult(true, null,
-                Collections.<RpcError> emptySet());
+        return RpcResultBuilder.<Void> success().build();
     }
 
     public RpcResult<Void> finish(HashMapDataStoreTransaction transaction) {
@@ -100,8 +97,7 @@ public final class HashMapDataStore implements DataStore, AutoCloseable {
         configuration.putAll(modification.getUpdatedConfigurationData());
         operational.putAll(modification.getUpdatedOperationalData());
 
-        return Rpcs.<Void> getRpcResult(true, null,
-                Collections.<RpcError> emptySet());
+        return RpcResultBuilder.<Void> success().build();
     }
 
     public void remove(final Map<InstanceIdentifier, CompositeNode> map,
diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/RoutedRpcRegImpl.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/RoutedRpcRegImpl.java
new file mode 100644 (file)
index 0000000..e4f19bb
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.sal.dom.broker.impl;
+
+import org.opendaylight.controller.sal.core.api.Broker.RoutedRpcRegistration;
+import org.opendaylight.controller.sal.core.api.RpcImplementation;
+import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+
+class RoutedRpcRegImpl extends AbstractObjectRegistration<RpcImplementation> implements
+        RoutedRpcRegistration {
+
+    private final QName type;
+    private final RoutedRpcSelector router;
+
+    public RoutedRpcRegImpl(final QName rpcType, final RpcImplementation implementation, final RoutedRpcSelector routedRpcSelector) {
+        super(implementation);
+        this.type = rpcType;
+        router = routedRpcSelector;
+    }
+
+    @Override
+    public void registerPath(final QName context, final InstanceIdentifier path) {
+        router.addPath(context, path, this);
+    }
+
+    @Override
+    public void unregisterPath(final QName context, final InstanceIdentifier path) {
+        router.removePath(context, path, this);
+    }
+
+    @Override
+    protected void removeRegistration() {
+
+    }
+
+    @Override
+    public QName getType() {
+        return type;
+    }
+
+}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/RoutedRpcSelector.java b/opendaylight/md-sal/sal-dom-broker/src/main/java/org/opendaylight/controller/sal/dom/broker/impl/RoutedRpcSelector.java
new file mode 100644 (file)
index 0000000..a22aed7
--- /dev/null
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.sal.dom.broker.impl;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkState;
+
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+import org.opendaylight.controller.md.sal.dom.broker.spi.rpc.RpcRoutingStrategy;
+import org.opendaylight.controller.sal.core.api.Broker.RoutedRpcRegistration;
+import org.opendaylight.controller.sal.core.api.RpcImplementation;
+import org.opendaylight.controller.sal.core.api.RpcRoutingContext;
+import org.opendaylight.yangtools.concepts.Identifiable;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.SimpleNode;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.common.util.concurrent.ListenableFuture;
+
+class RoutedRpcSelector implements RpcImplementation, AutoCloseable, Identifiable<RpcRoutingContext> {
+
+    private final RpcRoutingStrategy strategy;
+    private final Set<QName> supportedRpcs;
+    private final RpcRoutingContext identifier;
+    final ConcurrentMap<InstanceIdentifier, RoutedRpcRegImpl> implementations = new ConcurrentHashMap<>();
+    private final SchemaAwareRpcBroker router;
+
+    public RoutedRpcSelector(final RpcRoutingStrategy strategy, final SchemaAwareRpcBroker router) {
+        super();
+        this.strategy = strategy;
+        supportedRpcs = ImmutableSet.of(strategy.getIdentifier());
+        identifier = RpcRoutingContext.create(strategy.getContext(), strategy.getIdentifier());
+        this.router = router;
+    }
+
+    @Override
+    public RpcRoutingContext getIdentifier() {
+        return identifier;
+    }
+
+    @Override
+    public void close() throws Exception {
+
+    }
+
+    @Override
+    public Set<QName> getSupportedRpcs() {
+        return supportedRpcs;
+    }
+
+    public RoutedRpcRegistration addRoutedRpcImplementation(final QName rpcType, final RpcImplementation implementation) {
+        return new RoutedRpcRegImpl(rpcType, implementation, this);
+    }
+
+    @Override
+    public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(final QName rpc, final CompositeNode input) {
+        CompositeNode inputContainer = input.getFirstCompositeByName(QName.create(rpc,"input"));
+        checkArgument(inputContainer != null, "Rpc payload must contain input element");
+        SimpleNode<?> routeContainer = inputContainer.getFirstSimpleByName(strategy.getLeaf());
+        checkArgument(routeContainer != null, "Leaf %s must be set with value", strategy.getLeaf());
+        Object route = routeContainer.getValue();
+        checkArgument(route instanceof InstanceIdentifier,
+                      "The routed node %s is not an instance identifier", route);
+        RpcImplementation potential = null;
+        if (route != null) {
+            RoutedRpcRegImpl potentialReg = implementations.get(route);
+            if (potentialReg != null) {
+                potential = potentialReg.getInstance();
+            }
+        }
+        if (potential == null) {
+            return router.invokeRpc(rpc, (InstanceIdentifier) route, input);
+        }
+        checkState(potential != null, "No implementation is available for rpc:%s path:%s", rpc, route);
+        return potential.invokeRpc(rpc, input);
+    }
+
+    public void addPath(final QName context, final InstanceIdentifier path, final RoutedRpcRegImpl routedRpcRegImpl) {
+        //checkArgument(strategy.getContext().equals(context),"Supplied context is not supported.");
+        RoutedRpcRegImpl previous = implementations.put(path, routedRpcRegImpl);
+        if (previous == null) {
+            router.notifyPathAnnouncement(context,strategy.getIdentifier(), path);
+        }
+
+    }
+
+    public void removePath(final QName context, final InstanceIdentifier path, final RoutedRpcRegImpl routedRpcRegImpl) {
+        boolean removed = implementations.remove(path, routedRpcRegImpl);
+        if (removed) {
+            router.notifyPathWithdrawal(context, strategy.getIdentifier(), path);
+        }
+    }
+}
\ No newline at end of file
index 1a572d157dba9f8272140495b8eabf9669df11bc..3cd7ed5e13ed16b2449f2386604aa81802679b17 100644 (file)
@@ -9,6 +9,11 @@ package org.opendaylight.controller.sal.dom.broker.impl;
 
 import static com.google.common.base.Preconditions.checkState;
 
+import com.google.common.base.Predicate;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterables;
+
 import java.util.ArrayList;
 import java.util.Comparator;
 import java.util.HashMap;
@@ -40,10 +45,6 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Predicate;
-import com.google.common.collect.FluentIterable;
-import com.google.common.collect.ImmutableSet;
-
 public class SchemaAwareDataStoreAdapter extends AbstractLockableDelegator<DataStore> implements //
 DataStore, //
 SchemaContextListener, //
@@ -235,7 +236,7 @@ AutoCloseable {
         public CompositeNode readConfigurationData(final InstanceIdentifier path) {
             getDelegateReadLock().lock();
             try {
-                if (path.getPath().isEmpty()) {
+                if (Iterables.isEmpty(path.getPathArguments())) {
                     return null;
                 }
                 QName qname = null;
@@ -278,7 +279,7 @@ AutoCloseable {
         public CompositeNode readOperationalData(final InstanceIdentifier path) {
             getDelegateReadLock().lock();
             try {
-                if (path.getPath().isEmpty()) {
+                if (Iterables.isEmpty(path.getPathArguments())) {
                     return null;
                 }
                 QName qname = null;
index 8fc6fe229500ecc39506fcc5b215b82cfdd9cb5e..7bc827dcb0329d41825638efa9b5d1748ac0c83c 100644 (file)
@@ -17,6 +17,7 @@ import java.util.concurrent.ConcurrentMap;
 import org.opendaylight.controller.md.sal.common.api.routing.RouteChange;
 import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
 import org.opendaylight.controller.md.sal.common.impl.routing.RoutingUtils;
+import org.opendaylight.controller.md.sal.dom.broker.spi.rpc.RpcRoutingStrategy;
 import org.opendaylight.controller.sal.core.api.Broker.RoutedRpcRegistration;
 import org.opendaylight.controller.sal.core.api.Broker.RpcRegistration;
 import org.opendaylight.controller.sal.core.api.RoutedRpcDefaultImplementation;
@@ -24,7 +25,6 @@ import org.opendaylight.controller.sal.core.api.RpcImplementation;
 import org.opendaylight.controller.sal.core.api.RpcRegistrationListener;
 import org.opendaylight.controller.sal.core.api.RpcRoutingContext;
 import org.opendaylight.controller.sal.dom.broker.spi.RpcRouter;
-import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
 import org.opendaylight.yangtools.concepts.Identifiable;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
 import org.opendaylight.yangtools.concepts.util.ListenerRegistry;
@@ -32,17 +32,13 @@ import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
 import com.google.common.collect.FluentIterable;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
@@ -52,8 +48,7 @@ public class SchemaAwareRpcBroker implements RpcRouter, Identifiable<String>, Ro
 
     private static final Logger LOG = LoggerFactory.getLogger(SchemaAwareRpcBroker.class);
 
-    private static final QName CONTEXT_REFERENCE = QName.create("urn:opendaylight:yang:extension:yang-ext",
-            "2013-07-09", "context-reference");
+
     private final ListenerRegistry<RpcRegistrationListener> rpcRegistrationListeners = new ListenerRegistry<>();
     private final ListenerRegistry<RouteChangeListener<RpcRoutingContext, InstanceIdentifier>> routeChangeListeners = new ListenerRegistry<>();
 
@@ -64,7 +59,7 @@ public class SchemaAwareRpcBroker implements RpcRouter, Identifiable<String>, Ro
     private SchemaContextProvider schemaProvider;
     private RoutedRpcDefaultImplementation defaultDelegate;
 
-    public SchemaAwareRpcBroker(String identifier, SchemaContextProvider schemaProvider) {
+    public SchemaAwareRpcBroker(final String identifier, final SchemaContextProvider schemaProvider) {
         super();
         this.identifier = identifier;
         this.schemaProvider = schemaProvider;
@@ -74,7 +69,7 @@ public class SchemaAwareRpcBroker implements RpcRouter, Identifiable<String>, Ro
         return defaultImplementation;
     }
 
-    public void setDefaultImplementation(RpcImplementation defaultImplementation) {
+    public void setDefaultImplementation(final RpcImplementation defaultImplementation) {
         this.defaultImplementation = defaultImplementation;
     }
 
@@ -82,7 +77,7 @@ public class SchemaAwareRpcBroker implements RpcRouter, Identifiable<String>, Ro
         return schemaProvider;
     }
 
-    public void setSchemaProvider(SchemaContextProvider schemaProvider) {
+    public void setSchemaProvider(final SchemaContextProvider schemaProvider) {
         this.schemaProvider = schemaProvider;
     }
 
@@ -91,18 +86,18 @@ public class SchemaAwareRpcBroker implements RpcRouter, Identifiable<String>, Ro
     }
 
     @Override
-    public void setRoutedRpcDefaultDelegate(RoutedRpcDefaultImplementation defaultDelegate) {
+    public void setRoutedRpcDefaultDelegate(final RoutedRpcDefaultImplementation defaultDelegate) {
         this.defaultDelegate = defaultDelegate;
     }
 
     @Override
-    public RoutedRpcRegistration addRoutedRpcImplementation(QName rpcType, RpcImplementation implementation) {
+    public RoutedRpcRegistration addRoutedRpcImplementation(final QName rpcType, final RpcImplementation implementation) {
         checkArgument(rpcType != null, "RPC Type should not be null");
         checkArgument(implementation != null, "RPC Implementatoin should not be null");
         return getOrCreateRoutedRpcRouter(rpcType).addRoutedRpcImplementation(rpcType, implementation);
     }
 
-    private RoutedRpcSelector getOrCreateRoutedRpcRouter(QName rpcType) {
+    private RoutedRpcSelector getOrCreateRoutedRpcRouter(final QName rpcType) {
         RoutedRpcSelector potential = getRoutedRpcRouter(rpcType);
         if (potential != null) {
             return potential;
@@ -113,15 +108,15 @@ public class SchemaAwareRpcBroker implements RpcRouter, Identifiable<String>, Ro
                 return potential;
             }
             RpcDefinition definition = findRpcDefinition(rpcType);
-            RoutingStrategy strategy = getRoutingStrategy(definition);
-            checkState(strategy instanceof RoutedRpcStrategy, "Rpc %s is not routed.", rpcType);
-            potential = new RoutedRpcSelector((RoutedRpcStrategy) strategy, this);
+            RpcRoutingStrategy strategy = RpcRoutingStrategy.from(definition);
+            checkState(strategy.isContextBasedRouted(), "Rpc %s is not routed.", rpcType);
+            potential = new RoutedRpcSelector( strategy, this);
             implementations.put(rpcType, potential);
             return potential;
         }
     }
 
-    private RoutedRpcSelector getRoutedRpcRouter(QName rpcType) {
+    private RoutedRpcSelector getRoutedRpcRouter(final QName rpcType) {
         RpcImplementation potential = implementations.get(rpcType);
         if (potential != null) {
             checkState(potential instanceof RoutedRpcSelector, "Rpc %s is not routed.", rpcType);
@@ -132,25 +127,38 @@ public class SchemaAwareRpcBroker implements RpcRouter, Identifiable<String>, Ro
     }
 
     @Override
-    public RpcRegistration addRpcImplementation(QName rpcType, RpcImplementation implementation)
+    public RpcRegistration addRpcImplementation(final QName rpcType, final RpcImplementation implementation)
             throws IllegalArgumentException {
         checkArgument(rpcType != null, "RPC Type should not be null");
         checkArgument(implementation != null, "RPC Implementatoin should not be null");
         checkState(!hasRpcImplementation(rpcType), "Implementation already registered");
         RpcDefinition definition = findRpcDefinition(rpcType);
-        checkArgument(!isRoutedRpc(definition), "RPC Type must not be routed.");
+        checkArgument(!RpcRoutingStrategy.from(definition).isContextBasedRouted(), "RPC Type must not be content routed.");
         GlobalRpcRegistration reg = new GlobalRpcRegistration(rpcType, implementation, this);
-        implementations.putIfAbsent(rpcType, implementation);
+        final RpcImplementation previous = implementations.putIfAbsent(rpcType, implementation);
+        Preconditions.checkState(previous == null, "Rpc %s is already registered.",rpcType);
+        notifyRpcAdded(rpcType);
         return reg;
     }
 
-    private boolean isRoutedRpc(RpcDefinition definition) {
-        return getRoutingStrategy(definition) instanceof RoutedRpcStrategy;
+    private void notifyRpcAdded(final QName rpcType) {
+        for (ListenerRegistration<RpcRegistrationListener> listener : rpcRegistrationListeners) {
+            try {
+                listener.getInstance().onRpcImplementationAdded(rpcType);
+            } catch (Exception ex) {
+                LOG.error("Unhandled exception during invoking listener {}", listener.getInstance(), ex);
+            }
+
+        }
     }
 
     @Override
-    public ListenerRegistration<RpcRegistrationListener> addRpcRegistrationListener(RpcRegistrationListener listener) {
-        return rpcRegistrationListeners.register(listener);
+    public ListenerRegistration<RpcRegistrationListener> addRpcRegistrationListener(final RpcRegistrationListener listener) {
+        ListenerRegistration<RpcRegistrationListener> reg = rpcRegistrationListeners.register(listener);
+        for (QName impl : implementations.keySet()) {
+            listener.onRpcImplementationAdded(impl);
+        }
+        return reg;
     }
 
     @Override
@@ -164,11 +172,11 @@ public class SchemaAwareRpcBroker implements RpcRouter, Identifiable<String>, Ro
     }
 
     @Override
-    public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(QName rpc, CompositeNode input) {
+    public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(final QName rpc, final CompositeNode input) {
         return findRpcImplemention(rpc).invokeRpc(rpc, input);
     }
 
-    private RpcImplementation findRpcImplemention(QName rpc) {
+    private RpcImplementation findRpcImplemention(final QName rpc) {
         checkArgument(rpc != null, "Rpc name should not be null");
         RpcImplementation potentialImpl = implementations.get(rpc);
         if (potentialImpl != null) {
@@ -183,11 +191,11 @@ public class SchemaAwareRpcBroker implements RpcRouter, Identifiable<String>, Ro
         return potentialImpl;
     }
 
-    private boolean hasRpcImplementation(QName rpc) {
+    private boolean hasRpcImplementation(final QName rpc) {
         return implementations.containsKey(rpc);
     }
 
-    private RpcDefinition findRpcDefinition(QName rpcType) {
+    private RpcDefinition findRpcDefinition(final QName rpcType) {
         checkArgument(rpcType != null, "Rpc name must be supplied.");
         checkState(schemaProvider != null, "Schema Provider is not available.");
         SchemaContext ctx = schemaProvider.getSchemaContext();
@@ -197,7 +205,7 @@ public class SchemaAwareRpcBroker implements RpcRouter, Identifiable<String>, Ro
         return findRpcDefinition(rpcType, module.getRpcs());
     }
 
-    static private RpcDefinition findRpcDefinition(QName rpcType, Set<RpcDefinition> rpcs) {
+    static private RpcDefinition findRpcDefinition(final QName rpcType, final Set<RpcDefinition> rpcs) {
         checkState(rpcs != null, "Rpc schema is not available.");
         for (RpcDefinition rpc : rpcs) {
             if (rpcType.equals(rpc.getQName())) {
@@ -207,225 +215,17 @@ public class SchemaAwareRpcBroker implements RpcRouter, Identifiable<String>, Ro
         throw new IllegalArgumentException("Supplied Rpc Type is not defined.");
     }
 
-    private RoutingStrategy getRoutingStrategy(RpcDefinition rpc) {
-        ContainerSchemaNode input = rpc.getInput();
-        if (input != null) {
-            for (DataSchemaNode schemaNode : input.getChildNodes()) {
-                Optional<QName> context = getRoutingContext(schemaNode);
-                if (context.isPresent()) {
-                    return createRoutedStrategy(rpc, context.get(), schemaNode.getQName());
-                }
-            }
-        }
-        return createGlobalStrategy(rpc);
-    }
-
-    private static RoutingStrategy createRoutedStrategy(RpcDefinition rpc, QName context, QName leafNode) {
-        return new RoutedRpcStrategy(rpc.getQName(), context, leafNode);
-    }
-
-    private Optional<QName> getRoutingContext(DataSchemaNode schemaNode) {
-        for (UnknownSchemaNode extension : schemaNode.getUnknownSchemaNodes()) {
-            if (CONTEXT_REFERENCE.equals(extension.getNodeType())) {
-                return Optional.fromNullable(extension.getQName());
-            }
-        }
-        return Optional.absent();
-    }
-
-    private static RoutingStrategy createGlobalStrategy(RpcDefinition rpc) {
-        GlobalRpcStrategy ret = new GlobalRpcStrategy(rpc.getQName());
-        return ret;
-    }
-
     @Override
-    public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(QName rpc, InstanceIdentifier identifier, CompositeNode input) {
-      checkState(defaultDelegate != null);
-      return defaultDelegate.invokeRpc(rpc, identifier, input);
+    public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(final QName rpc, final InstanceIdentifier route, final CompositeNode input) {
+      checkState(defaultDelegate != null, "No implementation is available for rpc:%s path:%s", rpc, route);
+      return defaultDelegate.invokeRpc(rpc, route, input);
     }
 
-    private static abstract class RoutingStrategy implements Identifiable<QName> {
-
-        private final QName identifier;
-
-        public RoutingStrategy(QName identifier) {
-            super();
-            this.identifier = identifier;
-        }
-
-        @Override
-        public QName getIdentifier() {
-            return identifier;
-        }
-    }
-
-    private static class GlobalRpcStrategy extends RoutingStrategy {
-
-        public GlobalRpcStrategy(QName identifier) {
-            super(identifier);
-        }
-    }
-
-    private static class RoutedRpcStrategy extends RoutingStrategy {
-
-        private final QName context;
-        private final QName leaf;
-
-        public RoutedRpcStrategy(QName identifier, QName ctx, QName leaf) {
-            super(identifier);
-            this.context = ctx;
-            this.leaf = leaf;
-        }
-
-        public QName getContext() {
-            return context;
-        }
-
-        public QName getLeaf() {
-            return leaf;
-        }
-    }
-
-    private static class RoutedRpcSelector implements RpcImplementation, AutoCloseable, Identifiable<RpcRoutingContext> {
-
-        private final RoutedRpcStrategy strategy;
-        private final Set<QName> supportedRpcs;
-        private final RpcRoutingContext identifier;
-        private RpcImplementation defaultDelegate;
-        private final ConcurrentMap<InstanceIdentifier, RoutedRpcRegImpl> implementations = new ConcurrentHashMap<>();
-        private final SchemaAwareRpcBroker router;
-
-        public RoutedRpcSelector(RoutedRpcStrategy strategy, SchemaAwareRpcBroker router) {
-            super();
-            this.strategy = strategy;
-            supportedRpcs = ImmutableSet.of(strategy.getIdentifier());
-            identifier = RpcRoutingContext.create(strategy.context, strategy.getIdentifier());
-            this.router = router;
-        }
-
-        @Override
-        public RpcRoutingContext getIdentifier() {
-            return identifier;
-        }
-
-        @Override
-        public void close() throws Exception {
-
-        }
-
-        @Override
-        public Set<QName> getSupportedRpcs() {
-            return supportedRpcs;
-        }
-
-        public RoutedRpcRegistration addRoutedRpcImplementation(QName rpcType, RpcImplementation implementation) {
-            return new RoutedRpcRegImpl(rpcType, implementation, this);
-        }
-
-        @Override
-        public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(QName rpc, CompositeNode input) {
-            CompositeNode inputContainer = input.getFirstCompositeByName(QName.create(rpc,"input"));
-            checkArgument(inputContainer != null, "Rpc payload must contain input element");
-            SimpleNode<?> routeContainer = inputContainer.getFirstSimpleByName(strategy.getLeaf());
-            checkArgument(routeContainer != null, "Leaf %s must be set with value", strategy.getLeaf());
-            Object route = routeContainer.getValue();
-            checkArgument(route instanceof InstanceIdentifier,
-                          "The routed node %s is not an instance identifier", route);
-            RpcImplementation potential = null;
-            if (route != null) {
-                RoutedRpcRegImpl potentialReg = implementations.get(route);
-                if (potentialReg != null) {
-                    potential = potentialReg.getInstance();
-                }
-            }
-            if (potential == null) {
-                return router.invokeRpc(rpc, (InstanceIdentifier) route, input);
-            }
-            checkState(potential != null, "No implementation is available for rpc:%s path:%s", rpc, route);
-            return potential.invokeRpc(rpc, input);
-        }
-
-        public void addPath(QName context, InstanceIdentifier path, RoutedRpcRegImpl routedRpcRegImpl) {
-            //checkArgument(strategy.getContext().equals(context),"Supplied context is not supported.");
-            RoutedRpcRegImpl previous = implementations.put(path, routedRpcRegImpl);
-            if (previous == null) {
-                router.notifyPathAnnouncement(context,strategy.getIdentifier(), path);
-            }
-
-        }
-
-        public void removePath(QName context, InstanceIdentifier path, RoutedRpcRegImpl routedRpcRegImpl) {
-            boolean removed = implementations.remove(path, routedRpcRegImpl);
-            if (removed) {
-                router.notifyPathWithdrawal(context, strategy.getIdentifier(), path);
-            }
-        }
-    }
-
-    private static class GlobalRpcRegistration extends AbstractObjectRegistration<RpcImplementation> implements
-            RpcRegistration {
-        private final QName type;
-        private SchemaAwareRpcBroker router;
-
-        public GlobalRpcRegistration(QName type, RpcImplementation instance, SchemaAwareRpcBroker router) {
-            super(instance);
-            this.type = type;
-            this.router = router;
-        }
-
-        @Override
-        public QName getType() {
-            return type;
-        }
-
-        @Override
-        protected void removeRegistration() {
-            if (router != null) {
-                router.remove(this);
-                router = null;
-            }
-        }
-    }
-
-    private static class RoutedRpcRegImpl extends AbstractObjectRegistration<RpcImplementation> implements
-            RoutedRpcRegistration {
-
-        private final QName type;
-        private final RoutedRpcSelector router;
-
-        public RoutedRpcRegImpl(QName rpcType, RpcImplementation implementation, RoutedRpcSelector routedRpcSelector) {
-            super(implementation);
-            this.type = rpcType;
-            router = routedRpcSelector;
-        }
-
-        @Override
-        public void registerPath(QName context, InstanceIdentifier path) {
-            router.addPath(context, path, this);
-        }
-
-        @Override
-        public void unregisterPath(QName context, InstanceIdentifier path) {
-            router.removePath(context, path, this);
-        }
-
-        @Override
-        protected void removeRegistration() {
-
-        }
-
-        @Override
-        public QName getType() {
-            return type;
-        }
-
-    }
-
-    private void remove(GlobalRpcRegistration registration) {
+    void remove(final GlobalRpcRegistration registration) {
         implementations.remove(registration.getType(), registration);
     }
 
-    private void notifyPathAnnouncement(QName context, QName identifier, InstanceIdentifier path) {
+    void notifyPathAnnouncement(final QName context, final QName identifier, final InstanceIdentifier path) {
         RpcRoutingContext contextWrapped = RpcRoutingContext.create(context, identifier);
         RouteChange<RpcRoutingContext, InstanceIdentifier> change = RoutingUtils.announcementChange(contextWrapped , path);
         for(ListenerRegistration<RouteChangeListener<RpcRoutingContext, InstanceIdentifier>> routeListener : routeChangeListeners) {
@@ -433,15 +233,12 @@ public class SchemaAwareRpcBroker implements RpcRouter, Identifiable<String>, Ro
                 routeListener.getInstance().onRouteChange(change);
             } catch (Exception e) {
                 LOG.error("Unhandled exception during invoking onRouteChange for {}",routeListener.getInstance(),e);
-
             }
         }
 
     }
 
-
-
-    private void notifyPathWithdrawal(QName context,QName identifier, InstanceIdentifier path) {
+    void notifyPathWithdrawal(final QName context,final QName identifier, final InstanceIdentifier path) {
         RpcRoutingContext contextWrapped = RpcRoutingContext.create(context, identifier);
         RouteChange<RpcRoutingContext, InstanceIdentifier> change = RoutingUtils.removalChange(contextWrapped , path);
         for(ListenerRegistration<RouteChangeListener<RpcRoutingContext, InstanceIdentifier>> routeListener : routeChangeListeners) {
@@ -455,7 +252,7 @@ public class SchemaAwareRpcBroker implements RpcRouter, Identifiable<String>, Ro
 
     @Override
     public <L extends RouteChangeListener<RpcRoutingContext, InstanceIdentifier>> ListenerRegistration<L> registerRouteChangeListener(
-            L listener) {
+            final L listener) {
         ListenerRegistration<L> reg = routeChangeListeners.registerWithType(listener);
         RouteChange<RpcRoutingContext, InstanceIdentifier> initial = createInitialRouteChange();
         try {
index 853e3e391f591a8b3d6c5aad72d5d62da0093471..8d33ff7997dab4b2a09d813c9200e8b95f7dc762 100644 (file)
@@ -14,6 +14,8 @@ import java.util.Collections;
 import java.util.HashSet;
 import java.util.Set;
 
+import javax.annotation.Nullable;
+
 import org.opendaylight.controller.sal.core.api.BrokerService;
 import org.opendaylight.yangtools.concepts.Registration;
 import org.osgi.framework.ServiceReference;
@@ -23,9 +25,9 @@ public abstract class AbstractBrokerServiceProxy<T extends BrokerService> implem
     private T delegate;
     private final ServiceReference<T> reference;
 
-    public AbstractBrokerServiceProxy(final ServiceReference<T> ref, final T delegate) {
+    public AbstractBrokerServiceProxy(final @Nullable ServiceReference<T> ref, final T delegate) {
         this.delegate = checkNotNull(delegate, "Delegate should not be null.");
-        this.reference = checkNotNull(ref, "Reference should not be null.");
+        this.reference = ref;
     }
 
     protected final T getDelegate() {
index b0ccfb995db612188cff2bbb5014def94911e4d7..4f44f361d5d352e51378a681ef57dc48ebddd78c 100644 (file)
@@ -4,7 +4,7 @@ import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataBroker;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataChangeListener;
-import org.opendaylight.controller.md.sal.dom.api.DOMDataReadTransaction;
+import org.opendaylight.controller.md.sal.dom.api.DOMDataReadOnlyTransaction;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataReadWriteTransaction;
 import org.opendaylight.controller.md.sal.dom.api.DOMDataWriteTransaction;
 import org.opendaylight.controller.md.sal.dom.api.DOMTransactionChain;
@@ -19,7 +19,7 @@ public class DOMDataBrokerProxy extends AbstractBrokerServiceProxy<DOMDataBroker
     }
 
     @Override
-    public DOMDataReadTransaction newReadOnlyTransaction() {
+    public DOMDataReadOnlyTransaction newReadOnlyTransaction() {
         return getDelegate().newReadOnlyTransaction();
     }
 
index f893f96d18c59e94df9fe7961b8856b214a6f196..113a9c08dbe064f2d8d2066ee94dd8a1e0952505 100644 (file)
@@ -23,7 +23,7 @@ public class SchemaServiceActivator implements BundleActivator {
 
     @Override
     public void start(final BundleContext context) {
-        schemaService = new GlobalBundleScanningSchemaServiceImpl(context);
+        schemaService = GlobalBundleScanningSchemaServiceImpl.createInstance(context);
         schemaService.start();
         schemaServiceReg = context.registerService(SchemaService.class, schemaService, new Hashtable<String,String>());
     }
index 0f8ce1d95d31f727c018a9f801dca421c73f8a32..5adf39142ec5ee2af194b921a76b2ce01031ffd5 100644 (file)
@@ -9,6 +9,9 @@ package org.opendaylight.controller.sal.dom.broker.util;
 
 import static com.google.common.base.Preconditions.checkArgument;
 
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Iterables;
+
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
@@ -29,9 +32,6 @@ import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Iterables;
-
 public class YangDataOperations {
 
     public static CompositeNode merge(final DataSchemaNode schema,
@@ -84,10 +84,10 @@ public class YangDataOperations {
         }
         @SuppressWarnings({ "unchecked", "rawtypes" })
         final Map<Map<QName, Object>, CompositeNode> originalMap = YangDataUtils
-                .toIndexMap((List) original, node.getKeyDefinition());
+        .toIndexMap((List) original, node.getKeyDefinition());
         @SuppressWarnings({ "unchecked", "rawtypes" })
         final Map<Map<QName, Object>, CompositeNode> modifiedMap = YangDataUtils
-                .toIndexMap((List) modified, node.getKeyDefinition());
+        .toIndexMap((List) modified, node.getKeyDefinition());
 
         final List<Node<?>> mergedNodes = new ArrayList<Node<?>>(
                 original.size() + modified.size());
@@ -140,7 +140,7 @@ public class YangDataOperations {
                 modified.getNodeType()));
 
         final List<Node<?>> mergedChildNodes = new ArrayList<Node<?>>(stored
-                .getChildren().size() + modified.getChildren().size());
+                .getValue().size() + modified.getValue().size());
         final Set<QName> toProcess = new HashSet<QName>(stored.keySet());
         toProcess.addAll(modified.keySet());
 
index 306cd34a69502187084bec2a33643cac5231e979..29392dc7b3e91e6c6dbe202cbe1b4e4292cce17d 100644 (file)
@@ -10,6 +10,9 @@ package org.opendaylight.controller.sal.dom.broker.util;
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkState;
 
+import com.google.common.base.Function;
+import com.google.common.collect.FluentIterable;
+
 import java.util.Iterator;
 import java.util.List;
 import java.util.Set;
@@ -34,9 +37,6 @@ import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.UsesNode;
 
-import com.google.common.base.Function;
-import com.google.common.collect.FluentIterable;
-
 public final class YangSchemaUtils {
 
     private static final Function<PathArgument, QName> QNAME_FROM_PATH_ARGUMENT = new Function<PathArgument, QName>(){
@@ -57,7 +57,7 @@ public final class YangSchemaUtils {
     public static DataSchemaNode getSchemaNode(final SchemaContext schema,final InstanceIdentifier path) {
         checkArgument(schema != null,"YANG Schema must not be null.");
         checkArgument(path != null,"Path must not be null.");
-        return getSchemaNode(schema, FluentIterable.from(path.getPath()).transform(QNAME_FROM_PATH_ARGUMENT));
+        return getSchemaNode(schema, FluentIterable.from(path.getPathArguments()).transform(QNAME_FROM_PATH_ARGUMENT));
     }
 
     public static DataSchemaNode getSchemaNode(final SchemaContext schema,final Iterable<QName> path) {
index 82897b0198cbf183953f2051f87c8fcfe9f030a8..a0ee5c50c93bc8a576c2d71b2dd7b37b86cda896 100644 (file)
@@ -55,7 +55,7 @@ module opendaylight-sal-dom-broker-impl {
                     }
                 }
             }
-            
+
             container async-data-broker {
                 uses config:service-ref {
                     refine type {
@@ -63,7 +63,15 @@ module opendaylight-sal-dom-broker-impl {
                         config:required-identity sal:dom-async-data-broker;
                     }
                 }
-            
+            }
+
+            container root-schema-service {
+                uses config:service-ref {
+                    refine type {
+                        mandatory false;
+                        config:required-identity sal:schema-service;
+                    }
+                }
             }
         }
     }
index 2a955e5f4215e6dccc0c397ca9c0850ccb159aa3..38f08b30f94ea37d4e73e3537c5c7bd798eb12ed 100644 (file)
@@ -104,28 +104,29 @@ public class DOMTransactionChainTest {
          */
         DOMDataReadWriteTransaction thirdDeleteTx = allocateAndDelete(txChain);
 
-        /**
-         * third transaction is sealed.
-         */
-        ListenableFuture<RpcResult<TransactionStatus>> thirdDeleteTxFuture = thirdDeleteTx.commit();
-
         /**
          * We commit first transaction
          *
          */
         assertCommitSuccessful(firstWriteTxFuture);
 
-        // Alocates store transaction
+        /**
+         *
+         * Allocates transaction from data store.
+         *
+         */
         DOMDataReadTransaction storeReadTx = domBroker.newReadOnlyTransaction();
+
         /**
          * We verify transaction is commited to store, container should exists
          * in datastore.
          */
         assertTestContainerExists(storeReadTx);
+
         /**
-         * We commit third transaction
-         *
+         * third transaction is sealed and commited
          */
+        ListenableFuture<RpcResult<TransactionStatus>> thirdDeleteTxFuture = thirdDeleteTx.commit();
         assertCommitSuccessful(thirdDeleteTxFuture);
 
         /**
diff --git a/opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/broker/spi/rpc/RpcRoutingStrategy.java b/opendaylight/md-sal/sal-dom-spi/src/main/java/org/opendaylight/controller/md/sal/dom/broker/spi/rpc/RpcRoutingStrategy.java
new file mode 100644 (file)
index 0000000..81203c5
--- /dev/null
@@ -0,0 +1,142 @@
+/*
+ * 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.spi.rpc;
+
+import org.opendaylight.yangtools.concepts.Identifiable;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
+import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
+
+import com.google.common.base.Optional;
+
+public abstract class RpcRoutingStrategy implements Identifiable<QName> {
+
+    private final QName identifier;
+    private static final QName CONTEXT_REFERENCE = QName.create("urn:opendaylight:yang:extension:yang-ext",
+            "2013-07-09", "context-reference");
+
+    private RpcRoutingStrategy(final QName identifier) {
+        super();
+        this.identifier = identifier;
+    }
+
+    /**
+     * Returns leaf QName in which RPC Route is stored
+     *
+     *
+     * @return leaf QName in which RPC Route is stored
+     * @throws UnsupportedOperationException If RPC is not content routed.
+     *  ({@link #isContextBasedRouted()} returned <code>false</code>)
+     */
+    public abstract QName getLeaf();
+
+    /**
+     * Returns identity QName which represents RPC Routing context
+     *
+     * @return identity QName which represents RPC Routing context
+     * @throws UnsupportedOperationException If RPC is not content routed.
+     *  ({@link #isContextBasedRouted()} returned <code>false</code>)
+     */
+    public abstract QName getContext();
+
+    @Override
+    public QName getIdentifier() {
+        return identifier;
+    }
+
+    /**
+     * Returns true if RPC is routed by context.
+     *
+     * @return true if RPC is routed by content.
+     */
+    public abstract boolean isContextBasedRouted();
+
+    public static RpcRoutingStrategy from(final RpcDefinition rpc) {
+        ContainerSchemaNode input = rpc.getInput();
+        if (input != null) {
+            for (DataSchemaNode schemaNode : input.getChildNodes()) {
+                Optional<QName> context = getRoutingContext(schemaNode);
+                if (context.isPresent()) {
+                    return createRoutedStrategy(rpc, context.get(), schemaNode.getQName());
+                }
+            }
+        }
+        return createGlobalStrategy(rpc);
+    }
+
+    public static  Optional<QName> getRoutingContext(final DataSchemaNode schemaNode) {
+        for (UnknownSchemaNode extension : schemaNode.getUnknownSchemaNodes()) {
+            if (CONTEXT_REFERENCE.equals(extension.getNodeType())) {
+                return Optional.fromNullable(extension.getQName());
+            }
+        }
+        return Optional.absent();
+    }
+
+    private static RpcRoutingStrategy createRoutedStrategy(final RpcDefinition rpc, final QName context, final QName leafNode) {
+        return new RoutedRpcStrategy(rpc.getQName(), context, leafNode);
+    }
+
+
+
+    private static RpcRoutingStrategy createGlobalStrategy(final RpcDefinition rpc) {
+        GlobalRpcStrategy ret = new GlobalRpcStrategy(rpc.getQName());
+        return ret;
+    }
+
+    private static class RoutedRpcStrategy extends RpcRoutingStrategy {
+
+        final QName context;
+        private final QName leaf;
+
+        private RoutedRpcStrategy(final QName identifier, final QName ctx, final QName leaf) {
+            super(identifier);
+            this.context = ctx;
+            this.leaf = leaf;
+        }
+
+        @Override
+        public QName getContext() {
+            return context;
+        }
+
+        @Override
+        public QName getLeaf() {
+            return leaf;
+        }
+
+        @Override
+        public boolean isContextBasedRouted() {
+            return true;
+        }
+    }
+
+    private static class GlobalRpcStrategy extends RpcRoutingStrategy {
+
+        public GlobalRpcStrategy(final QName identifier) {
+            super(identifier);
+        }
+
+        @Override
+        public boolean isContextBasedRouted() {
+            return false;
+        }
+
+        @Override
+        public QName getContext() {
+            throw new UnsupportedOperationException("Not routed strategy does not have context.");
+        }
+
+        @Override
+        public QName getLeaf() {
+            throw new UnsupportedOperationException("Not routed strategy does not have context.");
+        }
+    }
+}
\ No newline at end of file
index dadef821eb349e048d8395f6ab1c24cb39eb89b4..906847426c6087d9b486de7aeb3237f28f971a7f 100644 (file)
     <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-simple</artifactId>
-      <version>${slf4j.version}</version>
       <scope>test</scope>
     </dependency>
+    <dependency>
+      <groupId>org.opendaylight.yangtools</groupId>
+      <artifactId>binding-generator-impl</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>sal-test-model</artifactId>
+      <scope>test</scope>
+      <version>${project.version}</version>
+    </dependency>
   </dependencies>
 
   <build>
index 3ed02dfb411fcb26cda91cc8cf227cf9f2ef4a0e..01a5989dcd8a6b5afa67a50844e540cbd68c80c5 100644 (file)
@@ -1,14 +1,17 @@
 package org.opendaylight.controller.config.yang.inmemory_datastore_provider;
 
-import com.google.common.util.concurrent.MoreExecutors;
+import java.util.concurrent.Executors;
+
 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
 
+import com.google.common.util.concurrent.MoreExecutors;
+
 public class InMemoryConfigDataStoreProviderModule extends org.opendaylight.controller.config.yang.inmemory_datastore_provider.AbstractInMemoryConfigDataStoreProviderModule {
-    public InMemoryConfigDataStoreProviderModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
+    public InMemoryConfigDataStoreProviderModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
         super(identifier, dependencyResolver);
     }
 
-    public InMemoryConfigDataStoreProviderModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.controller.config.yang.inmemory_datastore_provider.InMemoryConfigDataStoreProviderModule oldModule, java.lang.AutoCloseable oldInstance) {
+    public InMemoryConfigDataStoreProviderModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, final org.opendaylight.controller.config.yang.inmemory_datastore_provider.InMemoryConfigDataStoreProviderModule oldModule, final java.lang.AutoCloseable oldInstance) {
         super(identifier, dependencyResolver, oldModule, oldInstance);
     }
 
@@ -19,7 +22,7 @@ public class InMemoryConfigDataStoreProviderModule extends org.opendaylight.cont
 
     @Override
     public java.lang.AutoCloseable createInstance() {
-      InMemoryDOMDataStore   ids = new InMemoryDOMDataStore("DOM-CFG", MoreExecutors.sameThreadExecutor());
+      InMemoryDOMDataStore   ids = new InMemoryDOMDataStore("DOM-CFG", MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()));
       getSchemaServiceDependency().registerSchemaServiceListener(ids);
       return ids;
     }
index eea95990a1509a4231c2d5452ce661cb6c3270c5..172b0dbc01b0deb3e384a12a46722806db273bbc 100644 (file)
@@ -1,14 +1,17 @@
 package org.opendaylight.controller.config.yang.inmemory_datastore_provider;
 
-import com.google.common.util.concurrent.MoreExecutors;
+import java.util.concurrent.Executors;
+
 import org.opendaylight.controller.md.sal.dom.store.impl.InMemoryDOMDataStore;
 
+import com.google.common.util.concurrent.MoreExecutors;
+
 public class InMemoryOperationalDataStoreProviderModule extends org.opendaylight.controller.config.yang.inmemory_datastore_provider.AbstractInMemoryOperationalDataStoreProviderModule {
-    public InMemoryOperationalDataStoreProviderModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
+    public InMemoryOperationalDataStoreProviderModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
         super(identifier, dependencyResolver);
     }
 
-    public InMemoryOperationalDataStoreProviderModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, org.opendaylight.controller.config.yang.inmemory_datastore_provider.InMemoryOperationalDataStoreProviderModule oldModule, java.lang.AutoCloseable oldInstance) {
+    public InMemoryOperationalDataStoreProviderModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier, final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver, final org.opendaylight.controller.config.yang.inmemory_datastore_provider.InMemoryOperationalDataStoreProviderModule oldModule, final java.lang.AutoCloseable oldInstance) {
         super(identifier, dependencyResolver, oldModule, oldInstance);
     }
 
@@ -19,7 +22,7 @@ public class InMemoryOperationalDataStoreProviderModule extends org.opendaylight
 
     @Override
     public java.lang.AutoCloseable createInstance() {
-      InMemoryDOMDataStore ids = new InMemoryDOMDataStore("DOM-OPER", MoreExecutors.sameThreadExecutor());
+      InMemoryDOMDataStore ids = new InMemoryDOMDataStore("DOM-OPER", MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor()));
       getSchemaServiceDependency().registerSchemaServiceListener(ids);
       return ids;
     }
index af479743aa12a824a0e7610e057b7bbdd299e448..743ddd1ae069f6f1435c51fa7eb5fe709650fbc3 100644 (file)
@@ -30,7 +30,7 @@ public final class DOMImmutableDataChangeEvent implements
 
     private final NormalizedNode<?, ?> original;
     private final NormalizedNode<?, ?> updated;
-    private final Map<InstanceIdentifier, ? extends NormalizedNode<?, ?>> originalData;
+    private final Map<InstanceIdentifier, NormalizedNode<?, ?>> originalData;
     private final Map<InstanceIdentifier, NormalizedNode<?, ?>> createdData;
     private final Map<InstanceIdentifier, NormalizedNode<?, ?>> updatedData;
     private final Set<InstanceIdentifier> removedPaths;
@@ -67,7 +67,7 @@ public final class DOMImmutableDataChangeEvent implements
     }
 
     @Override
-    public Map<InstanceIdentifier, ? extends NormalizedNode<?, ?>> getOriginalData() {
+    public Map<InstanceIdentifier, NormalizedNode<?, ?>> getOriginalData() {
         return originalData;
     }
 
index 71a3534c811448d6f941f6166e145021db0653d7..b679de54d63ad7697381768eeba6bb7a044c85ac 100644 (file)
@@ -7,12 +7,17 @@
  */
 package org.opendaylight.controller.md.sal.dom.store.impl;
 
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.HashMultimap;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Multimap;
+import static org.opendaylight.controller.md.sal.dom.store.impl.DOMImmutableDataChangeEvent.builder;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.concurrent.Callable;
+
 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
 import org.opendaylight.controller.md.sal.dom.store.impl.DOMImmutableDataChangeEvent.Builder;
 import org.opendaylight.controller.md.sal.dom.store.impl.DOMImmutableDataChangeEvent.SimpleEventFactory;
@@ -32,16 +37,12 @@ import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.concurrent.Callable;
-
-import static org.opendaylight.controller.md.sal.dom.store.impl.DOMImmutableDataChangeEvent.builder;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.HashMultimap;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Multimap;
 
 /**
  * Resolve Data Change Events based on modifications and listeners
@@ -438,17 +439,19 @@ final class ResolveDataChangeEventsTask implements Callable<Iterable<ChangeListe
         Builder subtree = builder(DataChangeScope.SUBTREE).
                 setBefore(modification.getDataBefore().get()).
                 setAfter(modification.getDataAfter().get());
-
+        boolean oneModified = false;
         for (DataTreeCandidateNode childMod : modification.getChildNodes()) {
             PathArgument childId = childMod.getIdentifier();
             InstanceIdentifier childPath = path.node(childId);
             Collection<ListenerTree.Node> childListeners = getListenerChildrenWildcarded(listeners, childId);
 
+
             switch (childMod.getModificationType()) {
             case WRITE:
             case MERGE:
             case DELETE:
                 one.merge(resolveAnyChangeEvent(childPath, childListeners, childMod));
+                oneModified = true;
                 break;
             case SUBTREE_MODIFIED:
                 subtree.merge(resolveSubtreeChangeEvent(childPath, childListeners, childMod));
@@ -458,11 +461,20 @@ final class ResolveDataChangeEventsTask implements Callable<Iterable<ChangeListe
                 break;
             }
         }
-        DOMImmutableDataChangeEvent oneChangeEvent = one.build();
-        subtree.merge(oneChangeEvent);
+        final DOMImmutableDataChangeEvent oneChangeEvent;
+        if(oneModified) {
+            one.addUpdated(path, modification.getDataBefore().get(), modification.getDataAfter().get());
+            oneChangeEvent = one.build();
+            subtree.merge(oneChangeEvent);
+        } else {
+            oneChangeEvent = null;
+            subtree.addUpdated(path, modification.getDataBefore().get(), modification.getDataAfter().get());
+        }
         DOMImmutableDataChangeEvent subtreeEvent = subtree.build();
         if (!listeners.isEmpty()) {
-            addPartialTask(listeners, oneChangeEvent);
+            if(oneChangeEvent != null) {
+                addPartialTask(listeners, oneChangeEvent);
+            }
             addPartialTask(listeners, subtreeEvent);
         }
         return subtreeEvent;
index e6221f6920152aab2d60936af78646c3dd394ea2..9d04a1b6ed039043a7737699b4c3bf88a5a91ef7 100644 (file)
@@ -9,6 +9,19 @@ package org.opendaylight.controller.md.sal.dom.store.impl.tree;
 
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
+
+import java.lang.ref.Reference;
+import java.lang.ref.WeakReference;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+import javax.annotation.concurrent.GuardedBy;
+
 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
 import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeListener;
 import org.opendaylight.controller.md.sal.dom.store.impl.DataChangeListenerRegistration;
@@ -21,17 +34,6 @@ import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNode;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import javax.annotation.concurrent.GuardedBy;
-import java.lang.ref.Reference;
-import java.lang.ref.WeakReference;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.concurrent.locks.Lock;
-import java.util.concurrent.locks.ReadWriteLock;
-import java.util.concurrent.locks.ReentrantReadWriteLock;
-
 /**
  * A set of listeners organized as a tree by node to which they listen. This class
  * allows for efficient lookup of listeners when we walk the DataTreeCandidate.
@@ -70,7 +72,7 @@ public final class ListenerTree  {
 
         try {
             Node walkNode = rootNode;
-            for (final PathArgument arg : path.getPath()) {
+            for (final PathArgument arg : path.getPathArguments()) {
                 walkNode = walkNode.ensureChild(arg);
             }
 
diff --git a/opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/AbstractDataChangeListenerTest.java b/opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/AbstractDataChangeListenerTest.java
new file mode 100644 (file)
index 0000000..4d2d078
--- /dev/null
@@ -0,0 +1,163 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.dom.store.impl;
+
+import java.util.Collection;
+import java.util.Map;
+
+import org.junit.Assert;
+import org.junit.Before;
+import org.opendaylight.controller.md.sal.dom.store.impl.DatastoreTestTask.WriteTransactionCustomizer;
+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.TwoLevelList;
+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.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.top.level.list.NestedList;
+import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
+import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
+import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
+import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+import com.google.common.util.concurrent.MoreExecutors;
+
+public abstract class AbstractDataChangeListenerTest {
+
+    protected static final InstanceIdentifier TOP_LEVEL = InstanceIdentifier
+            .of(Top.QNAME);
+    private static final QName NAME_QNAME = QName.create(Top.QNAME, "name");
+    protected static final String FOO = "foo";
+    protected static final String BAR = "bar";
+    protected static final String BAZ = "baz";
+
+    private InMemoryDOMDataStore datastore;
+    private SchemaContext schemaContext;
+
+    @Before
+    public final void setup() throws Exception {
+        YangModuleInfo moduleInfo = BindingReflections
+                .getModuleInfo(TwoLevelList.class);
+        ModuleInfoBackedContext context = ModuleInfoBackedContext.create();
+        context.registerModuleInfo(moduleInfo);
+        schemaContext = context.tryToCreateSchemaContext().get();
+        datastore = new InMemoryDOMDataStore("TEST",
+                MoreExecutors.sameThreadExecutor());
+        datastore.onGlobalContextUpdated(schemaContext);
+    }
+
+    public final DatastoreTestTask newTestTask() {
+        return new DatastoreTestTask(datastore).cleanup(DatastoreTestTask
+                .simpleDelete(TOP_LEVEL));
+    }
+
+
+    public static final InstanceIdentifier path(final String topName,
+            final String nestedName) {
+        return path(topName).node(NestedList.QNAME).node(
+                new NodeIdentifierWithPredicates(NestedList.QNAME, NAME_QNAME,
+                        nestedName));
+    }
+
+    public static final InstanceIdentifier path(final String topName) {
+        return TOP_LEVEL.node(TopLevelList.QNAME).node(
+                new NodeIdentifierWithPredicates(TopLevelList.QNAME,
+                        NAME_QNAME, topName));
+    }
+
+    protected static DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> top() {
+        return Builders.containerBuilder().withNodeIdentifier(
+                new NodeIdentifier(Top.QNAME));
+    }
+
+
+
+    protected static void assertEmpty(final Collection<?> set) {
+        Assert.assertTrue(set.isEmpty());
+    }
+
+    protected static void assertEmpty(final Map<?,?> set) {
+        Assert.assertTrue(set.isEmpty());
+    }
+
+    protected static <K> void assertContains(final Collection<K> set, final K... values) {
+        for (K key : values) {
+            Assert.assertTrue(set.contains(key));
+        }
+
+    }
+
+    protected static <K> void assertNotContains(final Collection<K> set, final K... values) {
+        for (K key : values) {
+            Assert.assertFalse(set.contains(key));
+        }
+    }
+
+    protected static <K> void assertContains(final Map<K,?> map, final K... values) {
+        for (K key : values) {
+            Assert.assertTrue(map.containsKey(key));
+        }
+    }
+
+    protected static <K> void assertNotContains(final Map<K,?> map, final K... values) {
+        for (K key : values) {
+            Assert.assertFalse(map.containsKey(key));
+        }
+    }
+
+    protected static CollectionNodeBuilder<MapEntryNode, MapNode> topLevelMap() {
+        return ImmutableNodes.mapNodeBuilder(TopLevelList.QNAME);
+    }
+
+    protected static CollectionNodeBuilder<MapEntryNode, OrderedMapNode> nestedMap() {
+        return Builders.orderedMapBuilder().withNodeIdentifier(new NodeIdentifier(NestedList.QNAME));
+    }
+
+    public static DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> topLevelList(
+            final String key) {
+        return ImmutableNodes.mapEntryBuilder(TopLevelList.QNAME, NAME_QNAME,
+                key);
+    }
+
+    public static DataContainerNodeBuilder<NodeIdentifierWithPredicates, MapEntryNode> nestedList(
+            final String key) {
+        return ImmutableNodes
+                .mapEntryBuilder(NestedList.QNAME, NAME_QNAME, key);
+    }
+
+    public static final WriteTransactionCustomizer writeOneTopMultipleNested(
+            final String topName, final String... nestedName) {
+        CollectionNodeBuilder<MapEntryNode, OrderedMapNode> nestedMapBuilder = nestedMap();
+        for (String nestedItem : nestedName) {
+            nestedMapBuilder.addChild(nestedList(nestedItem).build());
+        }
+
+        final ContainerNode data = top().addChild(
+                topLevelMap().addChild(
+                        topLevelList(topName)
+                                .addChild(nestedMapBuilder.build()).build())
+                        .build()).build();
+
+        return DatastoreTestTask.simpleWrite(TOP_LEVEL, data);
+    }
+
+    public static final  WriteTransactionCustomizer deleteNested(final String topName,
+            final String nestedName) {
+        return DatastoreTestTask.simpleDelete(path(topName, nestedName));
+    }
+}
diff --git a/opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/DatastoreTestTask.java b/opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/DatastoreTestTask.java
new file mode 100644 (file)
index 0000000..8ac93b1
--- /dev/null
@@ -0,0 +1,174 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.dom.store.impl;
+
+import static org.junit.Assert.assertTrue;
+
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+
+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.AsyncDataChangeListener;
+import org.opendaylight.controller.sal.core.spi.data.DOMStore;
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadTransaction;
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort;
+import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+import com.google.common.base.Preconditions;
+import com.google.common.util.concurrent.SettableFuture;
+
+public class DatastoreTestTask {
+
+    private final DOMStore store;
+    private AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>> changeListener;
+
+    private WriteTransactionCustomizer setup;
+    private WriteTransactionCustomizer write;
+    private ReadTransactionVerifier read;
+    private WriteTransactionCustomizer cleanup;
+    private InstanceIdentifier changePath;
+    private DataChangeScope changeScope;
+    private boolean postSetup = false;
+    private final ChangeEventListener internalListener;
+
+    public DatastoreTestTask(final DOMStore datastore) {
+        this.store = datastore;
+        internalListener = new ChangeEventListener();
+    }
+
+    public DatastoreTestTask changeListener(final InstanceIdentifier path, final DataChangeScope scope,
+            final AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>> changeListener) {
+        this.changeListener = changeListener;
+        this.changePath = path;
+        this.changeScope = scope;
+        return this;
+    }
+
+    public DatastoreTestTask changeListener(final InstanceIdentifier path, final DataChangeScope scope) {
+        this.changePath = path;
+        this.changeScope = scope;
+        return this;
+    }
+
+    public DatastoreTestTask setup(final WriteTransactionCustomizer setup) {
+        this.setup = setup;
+        return this;
+    }
+
+    public DatastoreTestTask test(final WriteTransactionCustomizer write) {
+        this.write = write;
+        return this;
+    }
+
+    public DatastoreTestTask read(final ReadTransactionVerifier read) {
+        this.read = read;
+        return this;
+    }
+
+    public DatastoreTestTask cleanup(final WriteTransactionCustomizer cleanup) {
+        this.cleanup = cleanup;
+        return this;
+    }
+
+    public void run() throws InterruptedException, ExecutionException {
+        if (setup != null) {
+            execute(setup);
+        }
+        ListenerRegistration<ChangeEventListener> registration = null;
+        if (changePath != null) {
+            registration = store.registerChangeListener(changePath, internalListener, changeScope);
+        }
+
+        Preconditions.checkState(write != null, "Write Transaction must be set.");
+        postSetup = true;
+        execute(write);
+        if (registration != null) {
+            registration.close();
+        }
+        if (changeListener != null) {
+            changeListener.onDataChanged(internalListener.receivedChange.get());
+        }
+        if (read != null) {
+            read.verify(store.newReadOnlyTransaction());
+        }
+        if (cleanup != null) {
+            execute(cleanup);
+        }
+    }
+
+    public Future<AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>>> getChangeEvent() {
+        return internalListener.receivedChange;
+    }
+
+    private void execute(final WriteTransactionCustomizer writeCustomizer) throws InterruptedException,
+            ExecutionException {
+        DOMStoreReadWriteTransaction tx = store.newReadWriteTransaction();
+        writeCustomizer.customize(tx);
+        DOMStoreThreePhaseCommitCohort cohort = tx.ready();
+        assertTrue(cohort.canCommit().get());
+        cohort.preCommit().get();
+        cohort.commit().get();
+    }
+
+    public interface WriteTransactionCustomizer {
+        public void customize(DOMStoreReadWriteTransaction tx);
+    }
+
+    public interface ReadTransactionVerifier {
+        public void verify(DOMStoreReadTransaction tx);
+    }
+
+    private final class ChangeEventListener implements
+            AsyncDataChangeListener<InstanceIdentifier, NormalizedNode<?, ?>> {
+
+        protected final SettableFuture<AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>>> receivedChange = SettableFuture
+                .create();
+
+        @Override
+        public void onDataChanged(final AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change) {
+            if (postSetup) {
+                receivedChange.set(change);
+            }
+        }
+    }
+
+    public static final WriteTransactionCustomizer simpleWrite(final InstanceIdentifier path,
+            final NormalizedNode<?, ?> data) {
+        return new WriteTransactionCustomizer() {
+
+            @Override
+            public void customize(final DOMStoreReadWriteTransaction tx) {
+                tx.write(path, data);
+            }
+        };
+    }
+
+    public static final WriteTransactionCustomizer simpleMerge(final InstanceIdentifier path,
+            final NormalizedNode<?, ?> data) {
+        return new WriteTransactionCustomizer() {
+
+            @Override
+            public void customize(final DOMStoreReadWriteTransaction tx) {
+                tx.merge(path, data);
+            }
+        };
+    }
+
+    public static final WriteTransactionCustomizer simpleDelete(final InstanceIdentifier path) {
+        return new WriteTransactionCustomizer() {
+            @Override
+            public void customize(final DOMStoreReadWriteTransaction tx) {
+                tx.delete(path);
+            }
+        };
+    }
+}
diff --git a/opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/DefaultDataChangeListenerTestSuite.java b/opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/DefaultDataChangeListenerTestSuite.java
new file mode 100644 (file)
index 0000000..54d2043
--- /dev/null
@@ -0,0 +1,134 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.dom.store.impl;
+
+import java.util.concurrent.ExecutionException;
+
+import org.junit.Test;
+import org.opendaylight.controller.md.sal.dom.store.impl.DatastoreTestTask.WriteTransactionCustomizer;
+import org.opendaylight.controller.sal.core.spi.data.DOMStoreReadWriteTransaction;
+
+public abstract class DefaultDataChangeListenerTestSuite extends AbstractDataChangeListenerTest {
+
+    protected static final String FOO_SIBLING = "foo-sibling";
+
+    abstract protected void customizeTask(DatastoreTestTask task);
+
+    @Test
+    public final void putTopLevelOneNested() throws InterruptedException, ExecutionException {
+
+        DatastoreTestTask task = newTestTask().test(writeOneTopMultipleNested(FOO, BAR));
+        customizeTask(task);
+        task.run();
+        putTopLevelOneNested(task);
+    }
+
+    @Test
+    public final void existingTopWriteSibling() throws InterruptedException, ExecutionException {
+        DatastoreTestTask task = newTestTask().setup(writeOneTopMultipleNested(FOO)).test(
+                new WriteTransactionCustomizer() {
+                    @Override
+                    public void customize(final DOMStoreReadWriteTransaction tx) {
+                        tx.write(path(FOO_SIBLING), topLevelList(FOO_SIBLING).build());
+                    }
+                });
+        customizeTask(task);
+        task.run();
+        existingTopWriteSibling(task);
+    }
+
+    protected abstract void existingTopWriteSibling(DatastoreTestTask task) throws InterruptedException, ExecutionException;
+
+
+    @Test
+    public final void existingTopWriteTwoNested() throws InterruptedException, ExecutionException {
+        DatastoreTestTask task = newTestTask().setup(writeOneTopMultipleNested(FOO)).test(
+                new WriteTransactionCustomizer() {
+                    @Override
+                    public void customize(final DOMStoreReadWriteTransaction tx) {
+                        tx.write(path(FOO,BAR), nestedList(BAR).build());
+                        tx.write(path(FOO,BAZ), nestedList(BAZ).build());
+                    }
+                });
+        customizeTask(task);
+        task.run();
+        existingTopWriteTwoNested(task);
+    }
+
+    protected abstract void existingTopWriteTwoNested(DatastoreTestTask task) throws InterruptedException, ExecutionException;
+
+
+    @Test
+    public final void existingOneNestedWriteAdditionalNested() throws InterruptedException, ExecutionException {
+        DatastoreTestTask task = newTestTask().setup(writeOneTopMultipleNested(FOO, BAR)).test(
+                new WriteTransactionCustomizer() {
+                    @Override
+                    public void customize(final DOMStoreReadWriteTransaction tx) {
+                        tx.write(path(FOO,BAZ), nestedList(BAZ).build());
+                    }
+                });
+        customizeTask(task);
+        task.run();
+        existingOneNestedWriteAdditionalNested(task);
+    }
+
+    protected abstract void existingOneNestedWriteAdditionalNested(DatastoreTestTask task) throws InterruptedException, ExecutionException;
+
+    protected abstract void putTopLevelOneNested(DatastoreTestTask task) throws InterruptedException,
+            ExecutionException;
+
+    @Test
+    public final void replaceTopLevelNestedChanged() throws InterruptedException, ExecutionException {
+        DatastoreTestTask task = newTestTask().setup(writeOneTopMultipleNested(FOO, BAR)).test(
+                writeOneTopMultipleNested(FOO, BAZ));
+        customizeTask(task);
+        task.run();
+        replaceTopLevelNestedChanged(task);
+    }
+
+    protected abstract void replaceTopLevelNestedChanged(DatastoreTestTask task) throws InterruptedException,
+            ExecutionException;
+
+    @Test
+    public final void putTopLevelWithTwoNested() throws InterruptedException, ExecutionException {
+
+        DatastoreTestTask task = newTestTask().test(writeOneTopMultipleNested(FOO, BAR, BAZ));
+        customizeTask(task);
+        task.run();
+        putTopLevelWithTwoNested(task);
+    }
+
+    protected abstract void putTopLevelWithTwoNested(DatastoreTestTask task) throws InterruptedException,
+            ExecutionException;
+
+    @Test
+    public final void twoNestedExistsOneIsDeleted() throws InterruptedException, ExecutionException {
+
+        DatastoreTestTask task = newTestTask().setup(writeOneTopMultipleNested(FOO, BAR, BAZ)).test(
+                deleteNested(FOO, BAZ));
+        customizeTask(task);
+        task.run();
+        twoNestedExistsOneIsDeleted(task);
+    }
+
+    protected abstract void twoNestedExistsOneIsDeleted(DatastoreTestTask task) throws InterruptedException,
+            ExecutionException;
+
+    @Test
+    public final void nestedListExistsRootDeleted() throws InterruptedException, ExecutionException {
+
+        DatastoreTestTask task = newTestTask().cleanup(null).setup(writeOneTopMultipleNested(FOO, BAR, BAZ))
+                .test(DatastoreTestTask.simpleDelete(TOP_LEVEL));
+        customizeTask(task);
+        task.run();
+        nestedListExistsRootDeleted(task);
+    }
+
+    protected abstract void nestedListExistsRootDeleted(DatastoreTestTask task) throws InterruptedException,
+            ExecutionException;
+}
index 369a7da138731dd6149d4b426096af7cc2a553dc..96369dea5fabc7d3ce25272f5e0cceaf5291a0c6 100644 (file)
@@ -1,8 +1,18 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
 package org.opendaylight.controller.md.sal.dom.store.impl;
 
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.MoreExecutors;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.concurrent.ExecutionException;
+
 import org.junit.Before;
 import org.junit.Ignore;
 import org.junit.Test;
@@ -14,11 +24,9 @@ import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
-import java.util.concurrent.ExecutionException;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.MoreExecutors;
 
 
 public class InMemoryDataStoreTest {
@@ -237,7 +245,7 @@ public class InMemoryDataStoreTest {
   /**
    * Reads /test from readTx Read should return container.
    */
-  private static Optional<NormalizedNode<?, ?>> assertTestContainerExists(DOMStoreReadTransaction readTx)
+  private static Optional<NormalizedNode<?, ?>> assertTestContainerExists(final DOMStoreReadTransaction readTx)
       throws InterruptedException, ExecutionException {
 
     ListenableFuture<Optional<NormalizedNode<?, ?>>> writeTxContainer = readTx.read(TestModel.TEST_PATH);
diff --git a/opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/RootScopeSubtreeTest.java b/opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/RootScopeSubtreeTest.java
new file mode 100644 (file)
index 0000000..ef2a474
--- /dev/null
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.dom.store.impl;
+
+import java.util.concurrent.ExecutionException;
+
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+public class RootScopeSubtreeTest extends DefaultDataChangeListenerTestSuite {
+
+    @Override
+    protected void customizeTask(final DatastoreTestTask task) {
+        task.changeListener(TOP_LEVEL, DataChangeScope.SUBTREE);
+    }
+
+    @Override
+    public void putTopLevelOneNested(final DatastoreTestTask task) throws InterruptedException, ExecutionException {
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+
+        assertContains(change.getCreatedData(), TOP_LEVEL, path(FOO), path(FOO, BAR));
+        assertEmpty(change.getUpdatedData());
+        assertEmpty(change.getRemovedPaths());
+    }
+
+    @Override
+    public void replaceTopLevelNestedChanged(final DatastoreTestTask task) throws InterruptedException,
+            ExecutionException {
+
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+
+        assertContains(change.getCreatedData(), path(FOO, BAZ));
+        assertContains(change.getUpdatedData(), TOP_LEVEL, path(FOO));
+        assertContains(change.getRemovedPaths(), path(FOO, BAR));
+    }
+
+    @Override
+    protected void putTopLevelWithTwoNested(final DatastoreTestTask task) throws InterruptedException,
+            ExecutionException {
+
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+
+        assertContains(change.getCreatedData(), TOP_LEVEL, path(FOO), path(FOO, BAR), path(FOO, BAZ));
+        assertEmpty(change.getUpdatedData());
+        assertEmpty(change.getRemovedPaths());
+    }
+
+    @Override
+    protected void twoNestedExistsOneIsDeleted(final DatastoreTestTask task) throws InterruptedException,
+            ExecutionException {
+
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+
+        assertEmpty(change.getCreatedData());
+        assertContains(change.getUpdatedData(), TOP_LEVEL, path(FOO));
+        assertContains(change.getRemovedPaths(), path(FOO, BAZ));
+    }
+
+    @Override
+    protected void nestedListExistsRootDeleted(final DatastoreTestTask task) throws InterruptedException,
+            ExecutionException {
+
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+
+        assertEmpty(change.getCreatedData());
+        assertEmpty(change.getUpdatedData());
+        assertContains(change.getRemovedPaths(), TOP_LEVEL, path(FOO), path(FOO, BAR), path(FOO, BAZ));
+    }
+
+    @Override
+    protected void existingOneNestedWriteAdditionalNested(final DatastoreTestTask task) throws InterruptedException, ExecutionException {
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+
+        assertContains(change.getCreatedData(), path(FOO,BAZ));
+        assertNotContains(change.getCreatedData(), path(FOO,BAR));
+        assertContains(change.getUpdatedData(), TOP_LEVEL, path(FOO));
+        assertEmpty(change.getRemovedPaths());
+    }
+
+    @Override
+    protected void existingTopWriteTwoNested(final DatastoreTestTask task) throws InterruptedException, ExecutionException {
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+
+        assertContains(change.getCreatedData(), path(FOO,BAR),path(FOO,BAZ));
+        assertContains(change.getUpdatedData(), TOP_LEVEL, path(FOO));
+        assertNotContains(change.getUpdatedData(), path(FOO,BAR));
+        assertEmpty(change.getRemovedPaths());
+    }
+
+    @Override
+    protected void existingTopWriteSibling(final DatastoreTestTask task) throws InterruptedException, ExecutionException {
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+
+        assertContains(change.getCreatedData(), path(FOO_SIBLING));
+        assertContains(change.getUpdatedData(), TOP_LEVEL);
+        assertNotContains(change.getUpdatedData(), path(FOO));
+        assertEmpty(change.getRemovedPaths());
+    }
+}
diff --git a/opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/WildcardedScopeBaseTest.java b/opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/WildcardedScopeBaseTest.java
new file mode 100644 (file)
index 0000000..4c1a860
--- /dev/null
@@ -0,0 +1,140 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.dom.store.impl;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
+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.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+public class WildcardedScopeBaseTest extends DefaultDataChangeListenerTestSuite {
+
+    private static final InstanceIdentifier TOP_LEVEL_LIST_ALL = TOP_LEVEL.node(TopLevelList.QNAME).node(
+            TopLevelList.QNAME);
+
+    @Override
+    protected void customizeTask(final DatastoreTestTask task) {
+        task.changeListener(TOP_LEVEL_LIST_ALL, DataChangeScope.BASE);
+    }
+
+    @Override
+    public void putTopLevelOneNested(final DatastoreTestTask task) throws InterruptedException, ExecutionException {
+
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+
+        assertNotNull(change);
+
+        assertNotContains(change.getCreatedData(), TOP_LEVEL);
+        assertContains(change.getCreatedData(), path(FOO), path(FOO, BAR));
+
+        assertEmpty(change.getUpdatedData());
+        assertEmpty(change.getRemovedPaths());
+
+    }
+
+    @Override
+    public void replaceTopLevelNestedChanged(final DatastoreTestTask task) throws InterruptedException,
+            ExecutionException {
+
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+        assertNotNull(change);
+
+        assertContains(change.getCreatedData(), path(FOO, BAZ));
+        assertContains(change.getUpdatedData(), path(FOO));
+        assertNotContains(change.getUpdatedData(), TOP_LEVEL);
+        assertContains(change.getRemovedPaths(), path(FOO, BAR));
+
+    }
+
+    @Override
+    protected void putTopLevelWithTwoNested(final DatastoreTestTask task) throws InterruptedException,
+            ExecutionException {
+
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+        assertNotNull(change);
+        assertFalse(change.getCreatedData().isEmpty());
+
+        assertContains(change.getCreatedData(), path(FOO), path(FOO, BAR), path(FOO, BAZ));
+        assertNotContains(change.getCreatedData(), TOP_LEVEL);
+        assertEmpty(change.getUpdatedData());
+        assertEmpty(change.getRemovedPaths());
+
+    }
+
+    @Override
+    protected void twoNestedExistsOneIsDeleted(final DatastoreTestTask task) throws InterruptedException,
+            ExecutionException {
+
+        Future<?> future = task.getChangeEvent();
+        /*
+         * Base listener should be notified only and only if actual node changed its state,
+         * since deletion of child, did not result in change of node we are listening
+         * for, we should not be getting data change event
+         * and this means settable future containing receivedDataChangeEvent is not done.
+         *
+         */
+        assertFalse(future.isDone());
+    }
+
+    @Override
+    public void nestedListExistsRootDeleted(final DatastoreTestTask task) throws InterruptedException,
+            ExecutionException {
+
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+
+        assertEmpty(change.getCreatedData());
+        assertEmpty(change.getUpdatedData());
+
+        assertNotContains(change.getUpdatedData(), TOP_LEVEL);
+        assertContains(change.getRemovedPaths(), path(FOO),path(FOO, BAZ),path(FOO,BAR));
+    }
+
+    @Override
+    protected void existingOneNestedWriteAdditionalNested(final DatastoreTestTask task) {
+        Future<?> future = task.getChangeEvent();
+        /*
+         * One listener should be notified only and only if actual node changed its state,
+         * since deletion of nested child (in this case /nested-list/nested-list[foo],
+         * did not result in change of node we are listening
+         * for, we should not be getting data change event
+         * and this means settable future containing receivedDataChangeEvent is not done.
+         *
+         */
+        assertFalse(future.isDone());
+    }
+
+    @Override
+    protected void existingTopWriteTwoNested(final DatastoreTestTask task) throws InterruptedException, ExecutionException {
+        Future<?> future = task.getChangeEvent();
+        /*
+         * One listener should be notified only and only if actual node changed its state,
+         * since deletion of nested child (in this case /nested-list/nested-list[foo],
+         * did not result in change of node we are listening
+         * for, we should not be getting data change event
+         * and this means settable future containing receivedDataChangeEvent is not done.
+         *
+         */
+        assertFalse(future.isDone());
+    }
+
+    @Override
+    protected void existingTopWriteSibling(final DatastoreTestTask task) throws InterruptedException, ExecutionException {
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+
+        assertContains(change.getCreatedData(), path(FOO_SIBLING));
+        assertNotContains(change.getUpdatedData(), path(FOO), TOP_LEVEL);
+        assertEmpty(change.getRemovedPaths());
+    }
+}
diff --git a/opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/WildcardedScopeOneTest.java b/opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/WildcardedScopeOneTest.java
new file mode 100644 (file)
index 0000000..1f2cb22
--- /dev/null
@@ -0,0 +1,141 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.dom.store.impl;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
+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.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+public class WildcardedScopeOneTest extends DefaultDataChangeListenerTestSuite {
+
+    private static final InstanceIdentifier TOP_LEVEL_LIST_ALL = TOP_LEVEL.node(TopLevelList.QNAME).node(
+            TopLevelList.QNAME);
+
+    @Override
+    protected void customizeTask(final DatastoreTestTask task) {
+        task.changeListener(TOP_LEVEL_LIST_ALL, DataChangeScope.ONE);
+    }
+
+    @Override
+    public void putTopLevelOneNested(final DatastoreTestTask task) throws InterruptedException, ExecutionException {
+
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+
+        assertNotNull(change);
+
+        assertNotContains(change.getCreatedData(), TOP_LEVEL);
+        assertContains(change.getCreatedData(), path(FOO), path(FOO, BAR));
+
+        assertEmpty(change.getUpdatedData());
+        assertEmpty(change.getRemovedPaths());
+
+    }
+
+    @Override
+    public void replaceTopLevelNestedChanged(final DatastoreTestTask task) throws InterruptedException,
+            ExecutionException {
+
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+        assertNotNull(change);
+
+        assertContains(change.getCreatedData(), path(FOO, BAZ));
+        assertContains(change.getUpdatedData(), path(FOO));
+        assertNotContains(change.getUpdatedData(), TOP_LEVEL);
+        assertContains(change.getRemovedPaths(), path(FOO, BAR));
+
+    }
+
+    @Override
+    protected void putTopLevelWithTwoNested(final DatastoreTestTask task) throws InterruptedException,
+            ExecutionException {
+
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+        assertNotNull(change);
+        assertFalse(change.getCreatedData().isEmpty());
+
+        assertContains(change.getCreatedData(), path(FOO), path(FOO, BAR), path(FOO, BAZ));
+        assertNotContains(change.getCreatedData(), TOP_LEVEL);
+        assertEmpty(change.getUpdatedData());
+        assertEmpty(change.getRemovedPaths());
+
+    }
+
+    @Override
+    protected void twoNestedExistsOneIsDeleted(final DatastoreTestTask task) throws InterruptedException,
+            ExecutionException {
+
+        Future<?> future = task.getChangeEvent();
+        /*
+         * One listener should be notified only and only if actual node changed its state,
+         * since deletion of nested child (in this case /nested-list/nested-list[foo],
+         * did not result in change of node we are listening
+         * for, we should not be getting data change event
+         * and this means settable future containing receivedDataChangeEvent is not done.
+         *
+         */
+        assertFalse(future.isDone());
+    }
+
+    @Override
+    public void nestedListExistsRootDeleted(final DatastoreTestTask task) throws InterruptedException,
+            ExecutionException {
+
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+
+        assertEmpty(change.getCreatedData());
+        assertEmpty(change.getUpdatedData());
+
+        assertNotContains(change.getUpdatedData(), TOP_LEVEL);
+        assertContains(change.getRemovedPaths(), path(FOO),path(FOO, BAZ),path(FOO,BAR));
+    }
+
+    @Override
+    protected void existingOneNestedWriteAdditionalNested(final DatastoreTestTask task) {
+        Future<?> future = task.getChangeEvent();
+        /*
+         * One listener should be notified only and only if actual node changed its state,
+         * since deletion of nested child (in this case /nested-list/nested-list[foo],
+         * did not result in change of node we are listening
+         * for, we should not be getting data change event
+         * and this means settable future containing receivedDataChangeEvent is not done.
+         *
+         */
+        assertFalse(future.isDone());
+    }
+
+    @Override
+    protected void existingTopWriteTwoNested(final DatastoreTestTask task) throws InterruptedException, ExecutionException {
+        Future<?> future = task.getChangeEvent();
+        /*
+         * One listener should be notified only and only if actual node changed its state,
+         * since deletion of nested child (in this case /nested-list/nested-list[foo],
+         * did not result in change of node we are listening
+         * for, we should not be getting data change event
+         * and this means settable future containing receivedDataChangeEvent is not done.
+         *
+         */
+        assertFalse(future.isDone());
+    }
+
+    @Override
+    protected void existingTopWriteSibling(final DatastoreTestTask task) throws InterruptedException, ExecutionException {
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+
+        assertContains(change.getCreatedData(), path(FOO_SIBLING));
+        assertNotContains(change.getUpdatedData(),path(FOO), TOP_LEVEL);
+        assertEmpty(change.getRemovedPaths());
+    }
+}
diff --git a/opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/WildcardedScopeSubtreeTest.java b/opendaylight/md-sal/sal-inmemory-datastore/src/test/java/org/opendaylight/controller/md/sal/dom/store/impl/WildcardedScopeSubtreeTest.java
new file mode 100644 (file)
index 0000000..0102048
--- /dev/null
@@ -0,0 +1,127 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.md.sal.dom.store.impl;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.util.concurrent.ExecutionException;
+
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
+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.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+public class WildcardedScopeSubtreeTest extends DefaultDataChangeListenerTestSuite {
+
+    private static final InstanceIdentifier TOP_LEVEL_LIST_ALL = TOP_LEVEL.node(TopLevelList.QNAME).node(
+            TopLevelList.QNAME);
+
+    @Override
+    protected void customizeTask(final DatastoreTestTask task) {
+        task.changeListener(TOP_LEVEL_LIST_ALL, DataChangeScope.SUBTREE);
+    }
+
+    @Override
+    public void putTopLevelOneNested(final DatastoreTestTask task) throws InterruptedException, ExecutionException {
+
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+
+        assertNotContains(change.getCreatedData(), TOP_LEVEL);
+        assertContains(change.getCreatedData(), path(FOO), path(FOO, BAR));
+        assertEmpty(change.getUpdatedData());
+        assertEmpty(change.getRemovedPaths());
+
+    }
+
+    @Override
+    public void replaceTopLevelNestedChanged(final DatastoreTestTask task) throws InterruptedException,
+            ExecutionException {
+
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+        assertNotNull(change);
+
+        assertContains(change.getCreatedData(), path(FOO, BAZ));
+        assertContains(change.getUpdatedData(), path(FOO));
+        assertNotContains(change.getUpdatedData(), TOP_LEVEL);
+        assertContains(change.getRemovedPaths(), path(FOO, BAR));
+
+    }
+
+    @Override
+    protected void putTopLevelWithTwoNested(final DatastoreTestTask task) throws InterruptedException,
+            ExecutionException {
+
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+        assertNotNull(change);
+        assertFalse(change.getCreatedData().isEmpty());
+
+        assertContains(change.getCreatedData(), path(FOO), path(FOO, BAR), path(FOO, BAZ));
+        assertNotContains(change.getCreatedData(), TOP_LEVEL);
+        assertEmpty(change.getUpdatedData());
+        assertEmpty(change.getRemovedPaths());
+
+    }
+
+    @Override
+    protected void twoNestedExistsOneIsDeleted(final DatastoreTestTask task) throws InterruptedException,
+            ExecutionException {
+
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+        assertNotNull(change);
+        assertTrue(change.getCreatedData().isEmpty());
+        assertContains(change.getUpdatedData(), path(FOO));
+        assertNotContains(change.getUpdatedData(), TOP_LEVEL);
+        assertContains(change.getRemovedPaths(),path(FOO, BAZ));
+    }
+
+    @Override
+    public void nestedListExistsRootDeleted(final DatastoreTestTask task) throws InterruptedException,
+            ExecutionException {
+
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+
+        assertEmpty(change.getCreatedData());
+        assertEmpty(change.getUpdatedData());
+
+        assertNotContains(change.getUpdatedData(), TOP_LEVEL);
+        assertContains(change.getRemovedPaths(), path(FOO),path(FOO, BAZ),path(FOO,BAR));
+    }
+
+    @Override
+    protected void existingOneNestedWriteAdditionalNested(final DatastoreTestTask task) throws InterruptedException, ExecutionException {
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+
+        assertContains(change.getCreatedData(), path(FOO,BAZ));
+        assertNotContains(change.getCreatedData(), path(FOO,BAR));
+        assertContains(change.getUpdatedData(), path(FOO));
+        assertNotContains(change.getUpdatedData(), TOP_LEVEL);
+        assertEmpty(change.getRemovedPaths());
+    }
+
+    @Override
+    protected void existingTopWriteTwoNested(final DatastoreTestTask task) throws InterruptedException, ExecutionException {
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+
+        assertContains(change.getCreatedData(), path(FOO,BAR),path(FOO,BAZ));
+        assertContains(change.getUpdatedData(), path(FOO));
+        assertNotContains(change.getUpdatedData(), TOP_LEVEL, path(FOO,BAR));
+        assertEmpty(change.getRemovedPaths());
+    }
+
+    @Override
+    protected void existingTopWriteSibling(final DatastoreTestTask task) throws InterruptedException, ExecutionException {
+        AsyncDataChangeEvent<InstanceIdentifier, NormalizedNode<?, ?>> change = task.getChangeEvent().get();
+
+        assertContains(change.getCreatedData(), path(FOO_SIBLING));
+        assertNotContains(change.getUpdatedData(), path(FOO), TOP_LEVEL);
+        assertEmpty(change.getRemovedPaths());
+    }
+}
index f73d9cc72f893aa0260e6adc7bf0f257eb18252e..037bfb4a82c2cd8f34dbfe05513e602e7077b3ff 100644 (file)
@@ -12,13 +12,10 @@ import static org.opendaylight.controller.config.api.JmxAttributeValidationExcep
 
 import java.io.File;
 import java.io.InputStream;
-import java.net.InetAddress;
 import java.net.InetSocketAddress;
 import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
 
 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
-import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
 import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
 import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfiguration;
 import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfigurationBuilder;
@@ -33,19 +30,16 @@ import org.opendaylight.controller.sal.core.api.Broker;
 import org.opendaylight.protocol.framework.ReconnectStrategy;
 import org.opendaylight.protocol.framework.ReconnectStrategyFactory;
 import org.opendaylight.protocol.framework.TimedReconnectStrategy;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Host;
+import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress;
 import org.opendaylight.yangtools.yang.model.util.repo.AbstractCachingSchemaSourceProvider;
 import org.opendaylight.yangtools.yang.model.util.repo.FilesystemSchemaCachingProvider;
 import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProvider;
 import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProviders;
 import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Preconditions;
-import com.google.common.net.InetAddresses;
-import io.netty.util.HashedWheelTimer;
-
 /**
  *
  */
@@ -67,6 +61,7 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
     @Override
     protected void customValidation() {
         checkNotNull(getAddress(), addressJmxAttribute);
+        checkCondition(isHostAddressPresent(getAddress()), "Host address not present in " + getAddress(), addressJmxAttribute);
         checkNotNull(getPort(), portJmxAttribute);
         checkNotNull(getDomRegistry(), portJmxAttribute);
         checkNotNull(getDomRegistry(), domRegistryJmxAttribute);
@@ -77,11 +72,9 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
         checkNotNull(getBetweenAttemptsTimeoutMillis(), betweenAttemptsTimeoutMillisJmxAttribute);
         checkCondition(getBetweenAttemptsTimeoutMillis() > 0, "must be > 0", betweenAttemptsTimeoutMillisJmxAttribute);
 
-        // FIXME BUG-944 remove backwards compatibility
-        if(getClientDispatcher() == null) {
-            checkCondition(getBossThreadGroup() != null, "Client dispatcher was not set, thread groups have to be set instead", bossThreadGroupJmxAttribute);
-            checkCondition(getWorkerThreadGroup() != null, "Client dispatcher was not set, thread groups have to be set instead", workerThreadGroupJmxAttribute);
-        }
+        checkNotNull(getClientDispatcher(), clientDispatcherJmxAttribute);
+        checkNotNull(getBindingRegistry(), bindingRegistryJmxAttribute);
+        checkNotNull(getProcessingExecutor(), processingExecutorJmxAttribute);
 
         // Check username + password in case of ssh
         if(getTcpOnly() == false) {
@@ -89,33 +82,21 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
             checkNotNull(getPassword(), passwordJmxAttribute);
         }
 
-        // FIXME BUG 944 remove this warning
-        if(getBindingRegistry() == null) {
-            logger.warn("Configuration property: \"binding-registry\" not set for sal-netconf-connector (" + getIdentifier() + "). " +
-                    "Netconf-connector now requires a dependency on \"binding-broker-osgi-registry\". " +
-                    "The dependency is optional for now to preserve backwards compatibility, but will be mandatory in the future. " +
-                    "Please set the property as in \"01-netconf-connector\" initial config file. " +
-                    "The service will be retrieved from OSGi service registry now.");
-        }
+    }
 
-        // FIXME BUG 944 remove this warning
-        if(getProcessingExecutor() == null) {
-            logger.warn("Configuration property: \"processing-executor\" not set for sal-netconf-connector (" + getIdentifier() + "). " +
-                    "Netconf-connector now requires a dependency on \"threadpool\". " +
-                    "The dependency is optional for now to preserve backwards compatibility, but will be mandatory in the future. " +
-                    "Please set the property as in \"01-netconf-connector\" initial config file. " +
-                    "New instance will be created for the executor.");
-        }
+    private boolean isHostAddressPresent(Host address) {
+        return address.getDomainName() != null ||
+               address.getIpAddress() != null && (address.getIpAddress().getIpv4Address() != null || address.getIpAddress().getIpv6Address() != null);
     }
 
     @Override
     public java.lang.AutoCloseable createInstance() {
         final RemoteDeviceId id = new RemoteDeviceId(getIdentifier());
 
-        final ExecutorService globalProcessingExecutor = getGlobalProcessingExecutor();
+        final ExecutorService globalProcessingExecutor = getProcessingExecutorDependency().getExecutor();
 
         final Broker domBroker = getDomRegistryDependency();
-        final BindingAwareBroker bindingBroker = getBindingRegistryBackwards();
+        final BindingAwareBroker bindingBroker = getBindingRegistryDependency();
 
         final RemoteDeviceHandler salFacade = new NetconfDeviceSalFacade(id, domBroker, bindingBroker, bundleContext, globalProcessingExecutor);
         final NetconfDevice device =
@@ -123,8 +104,7 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
         final NetconfDeviceCommunicator listener = new NetconfDeviceCommunicator(id, device);
         final NetconfReconnectingClientConfiguration clientConfig = getClientConfig(listener);
 
-        // FIXME BUG-944 remove backwards compatibility
-        final NetconfClientDispatcher dispatcher = getClientDispatcher() == null ? createDispatcher() : getClientDispatcherDependency();
+        final NetconfClientDispatcher dispatcher = getClientDispatcherDependency();
         listener.initializeRemoteConnection(dispatcher, clientConfig);
 
         return new AutoCloseable() {
@@ -136,30 +116,6 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
         };
     }
 
-    private BindingAwareBroker getBindingRegistryBackwards() {
-        if(getBindingRegistry() != null) {
-            return getBindingRegistryDependency();
-        } else {
-            // FIXME BUG 944 remove backwards compatibility
-            final ServiceReference<BindingAwareBroker> serviceReference = bundleContext.getServiceReference(BindingAwareBroker.class);
-            Preconditions
-                    .checkNotNull(
-                            serviceReference,
-                            "Unable to retrieve %s from OSGi service registry, use binding-registry config property to inject %s with config subsystem",
-                            BindingAwareBroker.class, BindingAwareBroker.class);
-            return bundleContext.getService(serviceReference);
-        }
-    }
-
-    private ExecutorService getGlobalProcessingExecutor() {
-        if(getProcessingExecutor() != null) {
-            return getProcessingExecutorDependency().getExecutor();
-        } else {
-            // FIXME BUG 944 remove backwards compatibility
-            return Executors.newCachedThreadPool();
-        }
-    }
-
     private synchronized AbstractCachingSchemaSourceProvider<String, InputStream> getGlobalNetconfSchemaProvider() {
         if(GLOBAL_NETCONF_SOURCE_PROVIDER == null) {
             final String storageFile = "cache/schema";
@@ -171,16 +127,6 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
         return GLOBAL_NETCONF_SOURCE_PROVIDER;
     }
 
-    // FIXME BUG-944 remove backwards compatibility
-    /**
-     * @deprecated Use getClientDispatcherDependency method instead to retrieve injected dispatcher.
-     * This one creates new instance of NetconfClientDispatcher and will be removed in near future.
-     */
-    @Deprecated
-    private NetconfClientDispatcher createDispatcher() {
-        return new NetconfClientDispatcherImpl(getBossThreadGroupDependency(), getWorkerThreadGroupDependency(), new HashedWheelTimer());
-    }
-
     public void setBundleContext(final BundleContext bundleContext) {
         this.bundleContext = bundleContext;
     }
@@ -226,15 +172,12 @@ public final class NetconfConnectorModule extends org.opendaylight.controller.co
     }
 
     private InetSocketAddress getSocketAddress() {
-        /*
-         * Uncomment after Switch to IP Address
-        if(getAddress().getIpv4Address() != null) {
-            addressValue = getAddress().getIpv4Address().getValue();
+        if(getAddress().getDomainName() != null) {
+            return new InetSocketAddress(getAddress().getDomainName().getValue(), getPort().getValue());
         } else {
-            addressValue = getAddress().getIpv6Address().getValue();
+            IpAddress ipAddress = getAddress().getIpAddress();
+            String ip = ipAddress.getIpv4Address() != null ? ipAddress.getIpv4Address().getValue() : ipAddress.getIpv6Address().getValue();
+            return new InetSocketAddress(ip, getPort().getValue());
         }
-         */
-        final InetAddress inetAddress = InetAddresses.forString(getAddress());
-        return new InetSocketAddress(inetAddress, getPort().intValue());
     }
 }
index dca8fcafef4a88e31ecc6898dc52bc12b7aa5936..de4ac7ac18a106f88f530ac4dc16ea047976b091 100644 (file)
@@ -7,15 +7,19 @@
  */
 package org.opendaylight.controller.sal.connect.netconf;
 
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.base.Preconditions;
 import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
 import com.google.common.util.concurrent.ListeningExecutorService;
 import com.google.common.util.concurrent.MoreExecutors;
 import java.io.InputStream;
+import java.util.LinkedList;
+import java.util.List;
 import java.util.concurrent.ExecutorService;
-
 import org.opendaylight.controller.netconf.api.NetconfMessage;
+import org.opendaylight.controller.netconf.util.xml.XmlUtil;
 import org.opendaylight.controller.sal.connect.api.MessageTransformer;
 import org.opendaylight.controller.sal.connect.api.RemoteDevice;
 import org.opendaylight.controller.sal.connect.api.RemoteDeviceCommunicator;
@@ -36,9 +40,6 @@ import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProvider;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.base.Preconditions;
-
 /**
  *  This is a mediator between NetconfDeviceCommunicator and NetconfDeviceSalFacade
  */
@@ -53,6 +54,7 @@ public final class NetconfDevice implements RemoteDevice<NetconfSessionCapabilit
     private final MessageTransformer<NetconfMessage> messageTransformer;
     private final SchemaContextProviderFactory schemaContextProviderFactory;
     private final SchemaSourceProviderFactory<InputStream> sourceProviderFactory;
+    private final NotificationHandler notificationHandler;
 
     public static NetconfDevice createNetconfDevice(final RemoteDeviceId id,
             final AbstractCachingSchemaSourceProvider<String, InputStream> schemaSourceProvider,
@@ -79,6 +81,7 @@ public final class NetconfDevice implements RemoteDevice<NetconfSessionCapabilit
         this.sourceProviderFactory = sourceProviderFactory;
         this.processingExecutor = MoreExecutors.listeningDecorator(processingExecutor);
         this.schemaContextProviderFactory = schemaContextProviderFactory;
+        this.notificationHandler = new NotificationHandler(salFacade, messageTransformer, id);
     }
 
     @Override
@@ -99,6 +102,7 @@ public final class NetconfDevice implements RemoteDevice<NetconfSessionCapabilit
                 final SchemaContextProvider schemaContextProvider = setUpSchemaContext(delegate, remoteSessionCapabilities);
                 updateMessageTransformer(schemaContextProvider);
                 salFacade.onDeviceConnected(schemaContextProvider, remoteSessionCapabilities, deviceRpc);
+                notificationHandler.onRemoteSchemaUp();
             }
         });
 
@@ -142,7 +146,63 @@ public final class NetconfDevice implements RemoteDevice<NetconfSessionCapabilit
 
     @Override
     public void onNotification(final NetconfMessage notification) {
-        final CompositeNode parsedNotification = messageTransformer.toNotification(notification);
-        salFacade.onNotification(parsedNotification);
+        notificationHandler.handleNotification(notification);
+    }
+
+    /**
+     * Handles incoming notifications. Either caches them(until onRemoteSchemaUp is called) or passes to sal Facade.
+     */
+    private final static class NotificationHandler {
+
+        private final RemoteDeviceHandler<?> salFacade;
+        private final List<NetconfMessage> cache = new LinkedList<>();
+        private final MessageTransformer<NetconfMessage> messageTransformer;
+        private boolean passNotifications = false;
+        private final RemoteDeviceId id;
+
+        NotificationHandler(final RemoteDeviceHandler<?> salFacade, final MessageTransformer<NetconfMessage> messageTransformer, final RemoteDeviceId id) {
+            this.salFacade = salFacade;
+            this.messageTransformer = messageTransformer;
+            this.id = id;
+        }
+
+        synchronized void handleNotification(final NetconfMessage notification) {
+            if(passNotifications) {
+                passNotification(messageTransformer.toNotification(notification));
+            } else {
+                cacheNotification(notification);
+            }
+        }
+
+        /**
+         * Forward all cached notifications and pass all notifications from this point directly to sal facade.
+         */
+        synchronized void onRemoteSchemaUp() {
+            passNotifications = true;
+
+            for (final NetconfMessage cachedNotification : cache) {
+                passNotification(messageTransformer.toNotification(cachedNotification));
+            }
+
+            cache.clear();
+        }
+
+        private void cacheNotification(final NetconfMessage notification) {
+            Preconditions.checkState(passNotifications == false);
+
+            logger.debug("{}: Caching notification {}, remote schema not yet fully built", id, notification);
+            if(logger.isTraceEnabled()) {
+                logger.trace("{}: Caching notification {}", id, XmlUtil.toString(notification.getDocument()));
+            }
+
+            cache.add(notification);
+        }
+
+        private void passNotification(final CompositeNode parsedNotification) {
+            logger.debug("{}: Forwarding notification {}", id, parsedNotification);
+            Preconditions.checkNotNull(parsedNotification);
+            salFacade.onNotification(parsedNotification);
+        }
+
     }
 }
index 4da727f5c24e56e37c4e11acd6150d9afded1cd8..8045f8cb4a9556160b44fb46d4d3bbc12374435a 100644 (file)
@@ -8,7 +8,6 @@
 package org.opendaylight.controller.sal.connect.netconf.listener;
 
 import java.util.ArrayDeque;
-import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Queue;
@@ -22,19 +21,18 @@ import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
 import org.opendaylight.controller.netconf.client.NetconfClientDispatcher;
 import org.opendaylight.controller.netconf.client.NetconfClientSession;
 import org.opendaylight.controller.netconf.client.NetconfClientSessionListener;
+import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
 import org.opendaylight.controller.netconf.client.conf.NetconfReconnectingClientConfiguration;
 import org.opendaylight.controller.netconf.util.xml.XmlElement;
 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
-import org.opendaylight.controller.sal.common.util.RpcErrors;
-import org.opendaylight.controller.sal.common.util.Rpcs;
 import org.opendaylight.controller.sal.connect.api.RemoteDevice;
 import org.opendaylight.controller.sal.connect.api.RemoteDeviceCommunicator;
 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
-import org.opendaylight.controller.sal.connect.util.FailedRpcResult;
 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.RpcError;
 import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -82,8 +80,12 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
     }
 
     public void initializeRemoteConnection(final NetconfClientDispatcher dispatch,
-                                           final NetconfReconnectingClientConfiguration config) {
-        dispatch.createReconnectingClient(config);
+                                           final NetconfClientConfiguration config) {
+        if(config instanceof NetconfReconnectingClientConfiguration) {
+            dispatch.createReconnectingClient((NetconfReconnectingClientConfiguration) config);
+        } else {
+            dispatch.createClient(config);
+        }
     }
 
     private void tearDown( String reason ) {
@@ -135,9 +137,10 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
 
     private RpcResult<NetconfMessage> createErrorRpcResult( RpcError.ErrorType errorType, String message )
     {
-        return new FailedRpcResult<NetconfMessage>( RpcErrors.getRpcError( null,
-                NetconfDocumentedException.ErrorTag.operation_failed.getTagValue(),
-                null, RpcError.ErrorSeverity.ERROR, message, errorType, null ) );
+        return RpcResultBuilder.<NetconfMessage>failed()
+                .withError( errorType, NetconfDocumentedException.ErrorTag.operation_failed.getTagValue(),
+                            message )
+                .build();
     }
 
     @Override
@@ -203,8 +206,8 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
                 logger.warn( "{}: Invalid request-reply match, reply message contains different message-id, request: {}, response: {}",
                              id, msgToS( request.request ), msgToS( message ), e );
 
-                request.future.set( new FailedRpcResult<NetconfMessage>(
-                                                           NetconfMessageTransformUtil.toRpcError( e ) ) );
+                request.future.set( RpcResultBuilder.<NetconfMessage>failed()
+                        .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
                 return;
             }
 
@@ -215,12 +218,12 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
                 logger.warn( "{}: Error reply from remote device, request: {}, response: {}", id,
                              msgToS( request.request ), msgToS( message ), e );
 
-                request.future.set( new FailedRpcResult<NetconfMessage>(
-                                                          NetconfMessageTransformUtil.toRpcError( e ) ) );
+                request.future.set( RpcResultBuilder.<NetconfMessage>failed()
+                        .withRpcError( NetconfMessageTransformUtil.toRpcError( e ) ).build() );
                 return;
             }
 
-            request.future.set(Rpcs.getRpcResult( true, message, Collections.<RpcError>emptySet() ) );
+            request.future.set( RpcResultBuilder.<NetconfMessage>success( message ).build() );
         }
     }
 
index 457b8c36b987996bd28c041cff0d17068547f7a6..26c6a2758cc10beb574df359ccb6707dd41e319b 100644 (file)
@@ -11,12 +11,11 @@ import java.util.concurrent.ExecutionException;
 
 import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler;
 import org.opendaylight.controller.md.sal.common.api.data.DataModification;
-import org.opendaylight.controller.sal.common.util.RpcErrors;
-import org.opendaylight.controller.sal.connect.util.FailedRpcResult;
 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
 import org.opendaylight.controller.sal.core.api.RpcImplementation;
 import org.opendaylight.yangtools.yang.common.RpcError;
 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.InstanceIdentifier;
 import org.slf4j.Logger;
@@ -48,7 +47,7 @@ public final class NetconfDeviceCommitHandler implements DataCommitHandler<Insta
             Thread.currentThread().interrupt();
             throw new RuntimeException(id + ": Interrupted while waiting for response", e);
         } catch (final ExecutionException e) {
-            logger.warn("%s: Error executing pre commit operation on remote device", id, e);
+            logger.warn("{}: Error executing pre commit operation on remote device", id, e);
             return new FailingTransaction(twoPhaseCommit, e);
         }
 
@@ -74,8 +73,8 @@ public final class NetconfDeviceCommitHandler implements DataCommitHandler<Insta
 
         @Override
         public RpcResult<Void> finish() throws IllegalStateException {
-            return new FailedRpcResult<>(RpcErrors.getRpcError(null, null, null, RpcError.ErrorSeverity.ERROR,
-                    id + ": Unexpected operation error during pre-commit operations", RpcError.ErrorType.APPLICATION, e));
+            return RpcResultBuilder.<Void>failed().withError( RpcError.ErrorType.APPLICATION,
+                    id + ": Unexpected operation error during pre-commit operations", e ).build();
         }
 
         @Override
index 2909baccdb0dd0bc8a23e80553a6914c3dd13fe6..3535c96c804e7a97aa7aad1c516dfa224819a95d 100644 (file)
@@ -74,7 +74,7 @@ public final class NetconfDeviceDataReader implements DataReader<InstanceIdentif
     private static Node<?> findNode(final CompositeNode node, final InstanceIdentifier identifier) {
 
         Node<?> current = node;
-        for (final InstanceIdentifier.PathArgument arg : identifier.getPath()) {
+        for (final InstanceIdentifier.PathArgument arg : identifier.getPathArguments()) {
             if (current instanceof SimpleNode<?>) {
                 return null;
             } else if (current instanceof CompositeNode) {
index 6a62b1e20bba755367111924f78a49a6e2de7d5c..8d5b7aed2f4482b7730d764598e2fd56f44c25a1 100644 (file)
@@ -9,17 +9,19 @@ package org.opendaylight.controller.sal.connect.netconf.sal;
 
 import com.google.common.base.Function;
 import com.google.common.util.concurrent.Futures;
+
 import java.util.Collections;
 import java.util.Set;
 
 import javax.annotation.Nullable;
+
 import org.opendaylight.controller.netconf.api.NetconfMessage;
-import org.opendaylight.controller.sal.common.util.Rpcs;
 import org.opendaylight.controller.sal.connect.api.MessageTransformer;
 import org.opendaylight.controller.sal.connect.api.RemoteDeviceCommunicator;
 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 com.google.common.util.concurrent.ListenableFuture;
@@ -66,7 +68,8 @@ public final class NetconfDeviceRpc implements RpcImplementation {
         if (netconfMessageRpcResult.isSuccessful()) {
             return transformer.toRpcResult(netconfMessageRpcResult.getResult(), rpc);
         } else {
-            return Rpcs.getRpcResult(false, netconfMessageRpcResult.getErrors());
+            return RpcResultBuilder.<CompositeNode> failed()
+                                      .withRpcErrors(netconfMessageRpcResult.getErrors()).build();
         }
     }
 
index 01af84c9acf72057ec02b4b9123525f81cf00cd7..fc54bfbc3d8f0b93ec58d9df664b26815a500184 100644 (file)
@@ -7,9 +7,9 @@
  */
 package org.opendaylight.controller.sal.connect.netconf.sal;
 
+import com.google.common.base.Preconditions;
 import java.util.Collection;
 import java.util.Collections;
-
 import java.util.concurrent.ExecutorService;
 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
 import org.opendaylight.controller.sal.binding.api.BindingAwareProvider;
@@ -23,8 +23,6 @@ import org.opendaylight.yangtools.yang.binding.RpcService;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Preconditions;
-
 final class NetconfDeviceSalProvider implements AutoCloseable, Provider, BindingAwareProvider {
 
     private static final Logger logger = LoggerFactory.getLogger(NetconfDeviceSalProvider.class);
@@ -41,13 +39,13 @@ final class NetconfDeviceSalProvider implements AutoCloseable, Provider, Binding
 
     public MountProvisionInstance getMountInstance() {
         Preconditions.checkState(mountInstance != null,
-                "%s: Sal provider was not initialized by sal. Cannot publish notification", id);
+                "%s: Sal provider was not initialized by sal. Cannot get mount instance", id);
         return mountInstance;
     }
 
     public NetconfDeviceDatastoreAdapter getDatastoreAdapter() {
         Preconditions.checkState(datastoreAdapter != null,
-                "%s: Sal provider %s was not initialized by sal. Cannot publish notification", id);
+                "%s: Sal provider %s was not initialized by sal. Cannot get datastore adapter", id);
         return datastoreAdapter;
     }
 
index 41f9fec3c4d5e1f0240cc9adc84b179ac52bc50f..960f2ef2e80f094c3155e9d8a3632008ce7f13d6 100644 (file)
@@ -10,6 +10,7 @@ package org.opendaylight.controller.sal.connect.netconf.sal;
 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_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;
@@ -17,6 +18,12 @@ import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessag
 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.NETCONF_TARGET_QNAME;
 import static org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil.ROLLBACK_ON_ERROR_OPTION;
 
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+
 import java.util.Collection;
 import java.util.Collections;
 import java.util.List;
@@ -26,29 +33,26 @@ import java.util.concurrent.ExecutionException;
 
 import org.opendaylight.controller.md.sal.common.api.data.DataCommitHandler.DataCommitTransaction;
 import org.opendaylight.controller.md.sal.common.api.data.DataModification;
-import org.opendaylight.controller.sal.common.util.RpcErrors;
 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
-import org.opendaylight.controller.sal.connect.util.FailedRpcResult;
 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.RpcError;
 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.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.data.api.ModifyAction;
 import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.data.api.SimpleNode;
 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
+import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
 import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-
 /**
  *  Remote transaction that delegates data change to remote device using netconf messages.
  */
@@ -87,17 +91,16 @@ final class NetconfDeviceTwoPhaseCommitTransaction implements DataCommitTransact
     }
 
     private void sendMerge(final InstanceIdentifier key, final CompositeNode value) throws InterruptedException, ExecutionException {
-        sendEditRpc(createEditConfigStructure(key, Optional.<String>absent(), Optional.of(value)));
+        sendEditRpc(createEditConfigStructure(key, Optional.<ModifyAction>absent(), Optional.of(value)), Optional.<ModifyAction>absent());
     }
 
     private void sendDelete(final InstanceIdentifier toDelete) throws InterruptedException, ExecutionException {
-        sendEditRpc(createEditConfigStructure(toDelete, Optional.of("delete"), Optional.<CompositeNode>absent()));
+        sendEditRpc(createEditConfigStructure(toDelete, Optional.of(ModifyAction.DELETE), Optional.<CompositeNode>absent()), Optional.of(ModifyAction.NONE));
     }
 
-    private void sendEditRpc(final CompositeNode editStructure) throws InterruptedException, ExecutionException {
-        final ImmutableCompositeNode editConfigRequest = createEditConfigRequest(editStructure);
+    private void sendEditRpc(final CompositeNode editStructure, final Optional<ModifyAction> defaultOperation) throws InterruptedException, ExecutionException {
+        final ImmutableCompositeNode editConfigRequest = createEditConfigRequest(editStructure, defaultOperation);
         final RpcResult<CompositeNode> rpcResult = rpc.invokeRpc(NETCONF_EDIT_CONFIG_QNAME, editConfigRequest).get();
-        // TODO 874 add default operation when sending delete
 
         // Check result
         if(rpcResult.isSuccessful() == false) {
@@ -106,23 +109,33 @@ final class NetconfDeviceTwoPhaseCommitTransaction implements DataCommitTransact
         }
     }
 
-    private ImmutableCompositeNode createEditConfigRequest(final CompositeNode editStructure) {
+    private ImmutableCompositeNode createEditConfigRequest(final CompositeNode editStructure, final Optional<ModifyAction> defaultOperation) {
         final CompositeNodeBuilder<ImmutableCompositeNode> ret = ImmutableCompositeNode.builder();
 
+        // Target
         final Node<?> targetWrapperNode = ImmutableCompositeNode.create(NETCONF_TARGET_QNAME, ImmutableList.<Node<?>>of(targetNode));
         ret.add(targetWrapperNode);
 
+        // Default operation
+        if(defaultOperation.isPresent()) {
+            final SimpleNode<String> defOp = NodeFactory.createImmutableSimpleNode(NETCONF_DEFAULT_OPERATION_QNAME, null, modifyOperationToXmlString(defaultOperation.get()));
+            ret.add(defOp);
+        }
+
+        // Error option
         if(rollbackSupported) {
             ret.addLeaf(NETCONF_ERROR_OPTION_QNAME, ROLLBACK_ON_ERROR_OPTION);
         }
+
         ret.setQName(NETCONF_EDIT_CONFIG_QNAME);
+        // Edit content
         ret.add(editStructure);
         return ret.toInstance();
     }
 
-    private CompositeNode createEditConfigStructure(final InstanceIdentifier dataPath, final Optional<String> operation,
-                                                    final Optional<CompositeNode> lastChildOverride) {
-        Preconditions.checkArgument(dataPath.getPath().isEmpty() == false, "Instance identifier with empty path %s", dataPath);
+    private CompositeNode createEditConfigStructure(final InstanceIdentifier dataPath, final Optional<ModifyAction> operation,
+            final Optional<CompositeNode> lastChildOverride) {
+        Preconditions.checkArgument(Iterables.isEmpty(dataPath.getPathArguments()) == false, "Instance identifier with empty path %s", dataPath);
 
         List<PathArgument> reversedPath = Lists.reverse(dataPath.getPath());
 
@@ -160,7 +173,7 @@ final class NetconfDeviceTwoPhaseCommitTransaction implements DataCommitTransact
         return predicates;
     }
 
-    private CompositeNode getDeepestEditElement(final PathArgument arg, final Optional<String> operation, final Optional<CompositeNode> lastChildOverride) {
+    private CompositeNode getDeepestEditElement(final PathArgument arg, final Optional<ModifyAction> operation, final Optional<CompositeNode> lastChildOverride) {
         final CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
         builder.setQName(arg.getNodeType());
 
@@ -168,7 +181,7 @@ final class NetconfDeviceTwoPhaseCommitTransaction implements DataCommitTransact
         addPredicatesToCompositeNodeBuilder(predicates, builder);
 
         if (operation.isPresent()) {
-            builder.setAttribute(NETCONF_OPERATION_QNAME, operation.get());
+            builder.setAttribute(NETCONF_OPERATION_QNAME, modifyOperationToXmlString(operation.get()));
         }
         if (lastChildOverride.isPresent()) {
             final List<Node<?>> children = lastChildOverride.get().getValue();
@@ -182,6 +195,10 @@ final class NetconfDeviceTwoPhaseCommitTransaction implements DataCommitTransact
         return builder.toInstance();
     }
 
+    private String modifyOperationToXmlString(final ModifyAction operation) {
+        return operation.name().toLowerCase();
+    }
+
     /**
      * Send commit rpc to finish the transaction
      * In case of failure or unexpected error response, ExecutionException is thrown
@@ -196,8 +213,8 @@ final class NetconfDeviceTwoPhaseCommitTransaction implements DataCommitTransact
             throw new RuntimeException(id + ": Interrupted while waiting for response", e);
         } catch (final ExecutionException e) {
             LOG.warn("{}: Failed to finish commit operation", id, e);
-            return new FailedRpcResult<>(RpcErrors.getRpcError(null, null, null, RpcError.ErrorSeverity.ERROR,
-                    id + ": Unexpected operation error during commit operation", RpcError.ErrorType.APPLICATION, e));
+            return RpcResultBuilder.<Void>failed().withError( RpcError.ErrorType.APPLICATION,
+                            id + ": Unexpected operation error during commit operation", e ).build();
         }
     }
 
index 2adc1be79e65b35b4bc52312e56d6653b2d7551f..80d0f67ac49c72b47d35e6ca094ec4610099c1b1 100644 (file)
@@ -8,18 +8,19 @@
 package org.opendaylight.controller.sal.connect.netconf.schema.mapping;
 
 import com.google.common.base.Optional;
-import java.util.Collections;
+
 import java.util.List;
 import java.util.Set;
+
 import javax.activation.UnsupportedDataTypeException;
+
 import org.opendaylight.controller.netconf.api.NetconfMessage;
-import org.opendaylight.controller.sal.common.util.Rpcs;
 import org.opendaylight.controller.sal.connect.api.MessageTransformer;
 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
 import org.opendaylight.controller.sal.connect.util.MessageCounter;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.RpcError;
 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.impl.CompositeNodeTOImpl;
 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
@@ -55,7 +56,7 @@ public class NetconfMessageTransformer implements MessageTransformer<NetconfMess
     private static CompositeNode toNotification(final NetconfMessage message, final SchemaContext ctx) {
         final Set<NotificationDefinition> notifications = ctx.getNotifications();
         final Document document = message.getDocument();
-        return XmlDocumentUtils.notificationToDomNodes(document, Optional.fromNullable(notifications));
+        return XmlDocumentUtils.notificationToDomNodes(document, Optional.fromNullable(notifications), ctx);
     }
 
     @Override
@@ -70,6 +71,8 @@ public class NetconfMessageTransformer implements MessageTransformer<NetconfMess
                     final DataNodeContainer schemaForEdit = NetconfMessageTransformUtil.createSchemaForEdit(schemaContext.get());
                     w3cPayload = XmlDocumentUtils.toDocument(rpcPayload, schemaForEdit, codecProvider);
                 } else {
+                    // FIXME get and get-config needs schema as well to transform filter using schema context
+                    // e.g. Identityref nodes in filter fail to serialize properly to xml without schema
                     w3cPayload = XmlDocumentUtils.toDocument(rpcPayload, schemaContext.get(), codecProvider);
                 }
             } else {
@@ -88,7 +91,7 @@ public class NetconfMessageTransformer implements MessageTransformer<NetconfMess
             return toRpcResult(message, rpc, schemaContext.get());
         } else {
             final CompositeNode node = (CompositeNode) XmlDocumentUtils.toDomNode(message.getDocument());
-            return Rpcs.getRpcResult(true, node, Collections.<RpcError>emptySet());
+            return RpcResultBuilder.success( node ).build();
         }
     }
 
@@ -112,7 +115,7 @@ public class NetconfMessageTransformer implements MessageTransformer<NetconfMess
             compositeNode = (CompositeNode) XmlDocumentUtils.toDomNode(message.getDocument());
         }
 
-        return Rpcs.getRpcResult(true, compositeNode, Collections.<RpcError> emptySet());
+        return RpcResultBuilder.success( compositeNode ).build();
     }
 
     @Override
index 08a5822d366d16fa5d078e17ae8af2065cdba30e..0aeec64690d971abfa7f74b1bd58385e669163fe 100644 (file)
@@ -7,6 +7,14 @@
  */
 package org.opendaylight.controller.sal.connect.netconf.util;
 
+import com.google.common.base.Predicate;
+import com.google.common.collect.Collections2;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+
 import java.net.URI;
 import java.util.ArrayList;
 import java.util.Collections;
@@ -19,9 +27,9 @@ import javax.annotation.Nullable;
 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
 import org.opendaylight.controller.netconf.api.NetconfMessage;
 import org.opendaylight.controller.netconf.util.messages.NetconfMessageUtil;
-import org.opendaylight.controller.sal.common.util.RpcErrors;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.RpcError;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
@@ -36,28 +44,19 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-import com.google.common.base.Predicate;
-import com.google.common.collect.Collections2;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-
 public class 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 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");
     public static QName NETCONF_QNAME = QName.create(NETCONF_URI, null, "netconf");
     public static QName NETCONF_DATA_QNAME = QName.create(NETCONF_QNAME, "data");
     public static QName NETCONF_RPC_REPLY_QNAME = QName.create(NETCONF_QNAME, "rpc-reply");
     public static QName NETCONF_ERROR_OPTION_QNAME = QName.create(NETCONF_QNAME, "error-option");
     public static QName NETCONF_RUNNING_QNAME = QName.create(NETCONF_QNAME, "running");
-    static List<Node<?>> RUNNING = Collections.<Node<?>> singletonList(new SimpleNodeTOImpl<>(NETCONF_RUNNING_QNAME,
-            null, null));
+    static List<Node<?>> RUNNING = Collections.<Node<?>> singletonList(new SimpleNodeTOImpl<>(NETCONF_RUNNING_QNAME, null, null));
     public static QName NETCONF_SOURCE_QNAME = QName.create(NETCONF_QNAME, "source");
     public static CompositeNode CONFIG_SOURCE_RUNNING = new CompositeNodeTOImpl(NETCONF_SOURCE_QNAME, null, RUNNING);
     public static QName NETCONF_CANDIDATE_QNAME = QName.create(NETCONF_QNAME, "candidate");
@@ -65,6 +64,7 @@ public class NetconfMessageTransformUtil {
     public static QName NETCONF_CONFIG_QNAME = QName.create(NETCONF_QNAME, "config");
     public static QName NETCONF_COMMIT_QNAME = QName.create(NETCONF_QNAME, "commit");
     public static QName NETCONF_OPERATION_QNAME = QName.create(NETCONF_QNAME, "operation");
+    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_TYPE_QNAME = QName.create(NETCONF_QNAME, "type");
@@ -77,7 +77,7 @@ public class NetconfMessageTransformUtil {
 
     public static Node<?> toFilterStructure(final InstanceIdentifier identifier) {
         Node<?> previous = null;
-        if (identifier.getPath().isEmpty()) {
+        if (Iterables.isEmpty(identifier.getPathArguments())) {
             return null;
         }
 
@@ -104,15 +104,15 @@ public class NetconfMessageTransformUtil {
     }
 
     public static void checkValidReply(final NetconfMessage input, final NetconfMessage output)
-        throws NetconfDocumentedException {
+            throws NetconfDocumentedException {
         final String inputMsgId = input.getDocument().getDocumentElement().getAttribute("message-id");
         final String outputMsgId = output.getDocument().getDocumentElement().getAttribute("message-id");
 
         if(inputMsgId.equals(outputMsgId) == false) {
             Map<String,String> errorInfo = ImmutableMap.<String,String>builder()
-                .put( "actual-message-id", outputMsgId )
-                .put( "expected-message-id", inputMsgId )
-                .build();
+                    .put( "actual-message-id", outputMsgId )
+                    .put( "expected-message-id", inputMsgId )
+                    .build();
 
             throw new NetconfDocumentedException( "Response message contained unknown \"message-id\"",
                     null, NetconfDocumentedException.ErrorType.protocol,
@@ -127,7 +127,7 @@ public class NetconfMessageTransformUtil {
         }
     }
 
-    public static RpcError toRpcError( NetconfDocumentedException ex )
+    public static RpcError toRpcError( final NetconfDocumentedException ex )
     {
         StringBuilder infoBuilder = new StringBuilder();
         Map<String, String> errorInfo = ex.getErrorInfo();
@@ -135,44 +135,50 @@ public class NetconfMessageTransformUtil {
         {
             for( Entry<String,String> e: errorInfo.entrySet() ) {
                 infoBuilder.append( '<' ).append( e.getKey() ).append( '>' ).append( e.getValue() )
-                           .append( "</" ).append( e.getKey() ).append( '>' );
+                .append( "</" ).append( e.getKey() ).append( '>' );
 
             }
         }
 
-        return RpcErrors.getRpcError( null, ex.getErrorTag().getTagValue(), infoBuilder.toString(),
-                                      toRpcErrorSeverity( ex.getErrorSeverity() ), ex.getLocalizedMessage(),
-                                      toRpcErrorType( ex.getErrorType() ), ex.getCause() );
+        ErrorSeverity severity = toRpcErrorSeverity( ex.getErrorSeverity() );
+        return severity == ErrorSeverity.ERROR ?
+                    RpcResultBuilder.newError(
+                        toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
+                        ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() ) :
+                    RpcResultBuilder.newWarning(
+                        toRpcErrorType( ex.getErrorType() ), ex.getErrorTag().getTagValue(),
+                        ex.getLocalizedMessage(), null, infoBuilder.toString(), ex.getCause() );
     }
 
-    private static ErrorSeverity toRpcErrorSeverity( NetconfDocumentedException.ErrorSeverity severity ) {
+    private static ErrorSeverity toRpcErrorSeverity( final NetconfDocumentedException.ErrorSeverity severity ) {
         switch( severity ) {
-            case warning:
-                return RpcError.ErrorSeverity.WARNING;
-            default:
-                return RpcError.ErrorSeverity.ERROR;
+        case warning:
+            return RpcError.ErrorSeverity.WARNING;
+        default:
+            return RpcError.ErrorSeverity.ERROR;
         }
     }
 
-    private static RpcError.ErrorType toRpcErrorType( NetconfDocumentedException.ErrorType type )
+    private static RpcError.ErrorType toRpcErrorType( final NetconfDocumentedException.ErrorType type )
     {
         switch( type ) {
-            case protocol:
-                return RpcError.ErrorType.PROTOCOL;
-            case rpc:
-                return RpcError.ErrorType.RPC;
-            case transport:
-                return RpcError.ErrorType.TRANSPORT;
-            default:
-                return RpcError.ErrorType.APPLICATION;
+        case protocol:
+            return RpcError.ErrorType.PROTOCOL;
+        case rpc:
+            return RpcError.ErrorType.RPC;
+        case transport:
+            return RpcError.ErrorType.TRANSPORT;
+        default:
+            return RpcError.ErrorType.APPLICATION;
         }
     }
 
     public static CompositeNode flattenInput(final CompositeNode node) {
         final QName inputQName = QName.create(node.getNodeType(), "input");
         final CompositeNode input = node.getFirstCompositeByName(inputQName);
-        if (input == null)
+        if (input == null) {
             return node;
+        }
         if (input instanceof CompositeNode) {
 
             final List<Node<?>> nodes = ImmutableList.<Node<?>> builder() //
@@ -180,7 +186,7 @@ public class NetconfMessageTransformUtil {
                     .addAll(Collections2.filter(node.getValue(), new Predicate<Node<?>>() {
                         @Override
                         public boolean apply(@Nullable final Node<?> input) {
-                            return input.getNodeType() != inputQName;
+                            return !inputQName.equals(input.getNodeType());
                         }
                     })) //
                     .build();
diff --git a/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/util/FailedRpcResult.java b/opendaylight/md-sal/sal-netconf-connector/src/main/java/org/opendaylight/controller/sal/connect/util/FailedRpcResult.java
deleted file mode 100644 (file)
index 49b16d4..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.connect.util;
-
-import java.util.Collection;
-import java.util.Collections;
-
-import org.opendaylight.yangtools.yang.common.RpcError;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-
-public final class FailedRpcResult<T> implements RpcResult<T> {
-
-    private final RpcError rpcError;
-
-    public FailedRpcResult(final RpcError rpcError) {
-        this.rpcError = rpcError;
-    }
-
-    @Override
-    public boolean isSuccessful() {
-        return false;
-    }
-
-    @Override
-    public T getResult() {
-        return null;
-    }
-
-    @Override
-    public Collection<RpcError> getErrors() {
-        return Collections.singletonList(rpcError);
-    }
-}
index c59c41c4374838908cf3d7440bc71cef7940b0d3..6bad4798c290524dc04ff2d39611f2a1f0c33453 100644 (file)
@@ -9,6 +9,7 @@ module odl-sal-netconf-connector-cfg {
     import opendaylight-md-sal-dom {prefix dom;}
     import opendaylight-md-sal-binding {prefix md-sal-binding; revision-date 2013-10-28;}
     import odl-netconf-cfg { prefix cfg-net; revision-date 2014-04-08; }
+    import ietf-inet-types {prefix inet; revision-date "2010-09-24";}
 
     description
         "Service definition for Binding Aware MD-SAL.";
@@ -38,11 +39,11 @@ module odl-sal-netconf-connector-cfg {
             when "/config:modules/config:module/config:type = 'sal-netconf-connector'";
 
             leaf address {
-                type string;
+                type inet:host;
             }
 
             leaf port {
-                type uint32;
+                type inet:port-number;
             }
 
             leaf tcp-only {
@@ -69,40 +70,16 @@ module odl-sal-netconf-connector-cfg {
             container binding-registry {
                 uses config:service-ref {
                     refine type {
-                        // FIXME BUG-944 make mandatory (remove backwards compatibility)
-                        mandatory false;
+                        mandatory true;
                         config:required-identity md-sal-binding:binding-broker-osgi-registry;
                     }
                 }
             }
 
-            // FIXME BUG-944 remove backwards compatibility
-            // Deprecated, replaced by client dispatcher.
-            // This dependency will be removed in near future and all configurations of netconf-connector need to be changed to use dispatcher dependency.
-            container boss-thread-group {
-                uses config:service-ref {
-                    refine type {
-                        mandatory false;
-                        config:required-identity netty:netty-threadgroup;
-                    }
-                }
-            }
-
-            // FIXME BUG-944 remove backwards compatibility
-            // Deprecated, replaced by client dispatcher.
-            // This dependency will be removed in near future and all configurations of netconf-connector need to be changed to use dispatcher dependency.
-            container worker-thread-group {
-                uses config:service-ref {
-                    refine type {
-                        mandatory false;
-                        config:required-identity netty:netty-threadgroup;
-                    }
-                }
-            }
-
             container event-executor {
                 uses config:service-ref {
                     refine type {
+                        mandatory true;
                         config:required-identity netty:netty-event-executor;
                     }
                 }
@@ -111,8 +88,7 @@ module odl-sal-netconf-connector-cfg {
             container processing-executor {
                 uses config:service-ref {
                     refine type {
-                        // FIXME BUG-944 make mandatory (remove backwards compatibility)
-                        mandatory false;
+                        mandatory true;
                         config:required-identity th:threadpool;
                     }
                 }
@@ -120,7 +96,6 @@ module odl-sal-netconf-connector-cfg {
                 description "Makes up for flaws in netty threading design";
             }
 
-            // Replaces thread group dependencies
             container client-dispatcher {
                 uses config:service-ref {
                     refine type {
index c1b9f7b47ba8b8009b620655a729703e1809346f..defaab629f3684de2be6a5b1d7a578749cd493e0 100644 (file)
@@ -12,6 +12,7 @@ import static org.mockito.Matchers.anyString;
 import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.timeout;
+import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 
 import java.io.InputStream;
@@ -27,7 +28,6 @@ import org.junit.Test;
 import org.mockito.Mockito;
 import org.opendaylight.controller.netconf.api.NetconfMessage;
 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
-import org.opendaylight.controller.sal.common.util.Rpcs;
 import org.opendaylight.controller.sal.connect.api.MessageTransformer;
 import org.opendaylight.controller.sal.connect.api.RemoteDeviceCommunicator;
 import org.opendaylight.controller.sal.connect.api.RemoteDeviceHandler;
@@ -38,8 +38,8 @@ import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransf
 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.RpcError;
 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.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
@@ -65,8 +65,8 @@ public class NetconfDeviceTest {
         }
     }
 
-    private static final  RpcResult<NetconfMessage> rpcResult = Rpcs.getRpcResult(true, netconfMessage, Collections.<RpcError>emptySet());
-    private static final  RpcResult<CompositeNode> rpcResultC = Rpcs.getRpcResult(true, compositeNode, Collections.<RpcError>emptySet());
+    private static final  RpcResult<NetconfMessage> rpcResult = RpcResultBuilder.success(netconfMessage).build();
+    private static final  RpcResult<CompositeNode> rpcResultC = RpcResultBuilder.success(compositeNode).build();
 
     public static final String TEST_NAMESPACE = "test:namespace";
     public static final String TEST_MODULE = "test-module";
@@ -83,6 +83,32 @@ public class NetconfDeviceTest {
         Mockito.verify(facade, Mockito.timeout(5000)).onDeviceDisconnected();
     }
 
+    @Test
+    public void testNotificationBeforeSchema() throws Exception {
+        final RemoteDeviceHandler<NetconfSessionCapabilities> facade = getFacade();
+        final RemoteDeviceCommunicator<NetconfMessage> listener = getListener();
+
+        final MessageTransformer<NetconfMessage> messageTransformer = getMessageTransformer();
+        final NetconfDevice device = new NetconfDevice(getId(), facade, getExecutor(), messageTransformer, getSchemaContextProviderFactory(), getSourceProviderFactory());
+
+        device.onNotification(netconfMessage);
+        device.onNotification(netconfMessage);
+
+        verify(facade, times(0)).onNotification(any(CompositeNode.class));
+
+        final NetconfSessionCapabilities sessionCaps = getSessionCaps(true,
+                Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&amp;revision=" + TEST_REVISION));
+
+        device.onRemoteSessionUp(sessionCaps, listener);
+
+        verify(messageTransformer, timeout(10000).times(2)).toNotification(netconfMessage);
+        verify(facade, times(2)).onNotification(compositeNode);
+
+        device.onNotification(netconfMessage);
+        verify(messageTransformer, times(3)).toNotification(netconfMessage);
+        verify(facade, times(3)).onNotification(compositeNode);
+    }
+
     @Test
     public void testNetconfDeviceReconnect() throws Exception {
         final RemoteDeviceHandler<NetconfSessionCapabilities> facade = getFacade();
@@ -137,6 +163,7 @@ public class NetconfDeviceTest {
         final RemoteDeviceHandler<NetconfSessionCapabilities> remoteDeviceHandler = mockCloseableClass(RemoteDeviceHandler.class);
         doNothing().when(remoteDeviceHandler).onDeviceConnected(any(SchemaContextProvider.class), any(NetconfSessionCapabilities.class), any(RpcImplementation.class));
         doNothing().when(remoteDeviceHandler).onDeviceDisconnected();
+        doNothing().when(remoteDeviceHandler).onNotification(any(CompositeNode.class));
         return remoteDeviceHandler;
     }
 
@@ -174,6 +201,7 @@ public class NetconfDeviceTest {
         final MessageTransformer<NetconfMessage> messageTransformer = mockClass(MessageTransformer.class);
         doReturn(netconfMessage).when(messageTransformer).toRpcRequest(any(QName.class), any(CompositeNode.class));
         doReturn(rpcResultC).when(messageTransformer).toRpcResult(any(NetconfMessage.class), any(QName.class));
+        doReturn(compositeNode).when(messageTransformer).toNotification(any(NetconfMessage.class));
         doNothing().when(messageTransformer).onGlobalContextUpdated(any(SchemaContext.class));
         return messageTransformer;
     }
@@ -198,4 +226,4 @@ public class NetconfDeviceTest {
         doReturn(Futures.immediateFuture(rpcResult)).when(remoteDeviceCommunicator).sendRequest(any(NetconfMessage.class), any(QName.class));
         return remoteDeviceCommunicator;
     }
-}
\ No newline at end of file
+}
diff --git a/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfToNotificationTest.java b/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfToNotificationTest.java
new file mode 100644 (file)
index 0000000..521a55d
--- /dev/null
@@ -0,0 +1,64 @@
+package org.opendaylight.controller.sal.connect.netconf;
+
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertNotNull;
+import static junit.framework.Assert.assertTrue;
+
+import java.io.InputStream;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+
+import javax.xml.parsers.DocumentBuilderFactory;
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.controller.netconf.api.NetconfMessage;
+import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.controller.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser;
+import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
+import org.w3c.dom.Document;
+
+/**
+ * @author Lukas Sedlak <lsedlak@cisco.com>
+ */
+public class NetconfToNotificationTest {
+
+    NetconfMessageTransformer messageTransformer;
+
+    NetconfMessage userNotification;
+
+    @Before
+    public void setup() throws Exception {
+        final List<InputStream> modelsToParse = Collections.singletonList(getClass().getResourceAsStream("/schemas/user-notification.yang"));
+        final YangContextParser parser = new YangParserImpl();
+        final Set<Module> modules = parser.parseYangModelsFromStreams(modelsToParse);
+        assertTrue(!modules.isEmpty());
+        final SchemaContext schemaContext = parser.resolveSchemaContext(modules);
+        assertNotNull(schemaContext);
+
+        messageTransformer = new NetconfMessageTransformer();
+        messageTransformer.onGlobalContextUpdated(schemaContext);
+
+        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+        factory.setNamespaceAware(true);
+        InputStream notifyPayloadStream = getClass().getResourceAsStream("/notification-payload.xml");
+        assertNotNull(notifyPayloadStream);
+
+        final Document doc = XmlUtil.readXmlToDocument(notifyPayloadStream);
+        assertNotNull(doc);
+        userNotification = new NetconfMessage(doc);
+    }
+
+    @Test
+    public void test() throws Exception {
+        final CompositeNode root = messageTransformer.toNotification(userNotification);
+
+        assertNotNull(root);
+        assertEquals(6, root.size());
+        assertEquals("user-visited-page", root.getKey().getLocalName());
+    }
+}
diff --git a/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfToRpcRequestTest.java b/opendaylight/md-sal/sal-netconf-connector/src/test/java/org/opendaylight/controller/sal/connect/netconf/NetconfToRpcRequestTest.java
new file mode 100644 (file)
index 0000000..18a3b9f
--- /dev/null
@@ -0,0 +1,81 @@
+package org.opendaylight.controller.sal.connect.netconf;
+
+import static junit.framework.Assert.assertEquals;
+import static junit.framework.Assert.assertNotNull;
+import static junit.framework.Assert.assertTrue;
+
+import java.io.InputStream;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.controller.netconf.api.NetconfMessage;
+import org.opendaylight.controller.sal.connect.netconf.schema.mapping.NetconfMessageTransformer;
+import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
+import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser;
+import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
+
+/**
+ * Test case for reported bug 1355
+ *
+ * @author Lukas Sedlak
+ * @see <a
+ *      https://bugs.opendaylight.org/show_bug.cgi?id=1355</a>
+ */
+public class NetconfToRpcRequestTest {
+
+    private String TEST_MODEL_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:rpc-test";
+    private String REVISION = "2014-07-14";
+    private QName INPUT_QNAME = QName.create(TEST_MODEL_NAMESPACE, REVISION, "input");
+    private QName STREAM_NAME = QName.create(TEST_MODEL_NAMESPACE, REVISION, "stream-name");
+    private QName RPC_NAME = QName.create(TEST_MODEL_NAMESPACE, REVISION, "subscribe");
+
+    NetconfMessageTransformer messageTransformer;
+
+    @SuppressWarnings("deprecation")
+    @Before
+    public void setup() throws Exception {
+        final List<InputStream> modelsToParse = Collections
+            .singletonList(getClass().getResourceAsStream("/schemas/rpc-notification-subscription.yang"));
+        final YangContextParser parser = new YangParserImpl();
+        final Set<Module> modules = parser.parseYangModelsFromStreams(modelsToParse);
+        assertTrue(!modules.isEmpty());
+        final SchemaContext schemaContext = parser.resolveSchemaContext(modules);
+        assertNotNull(schemaContext);
+
+        messageTransformer = new NetconfMessageTransformer();
+        messageTransformer.onGlobalContextUpdated(schemaContext);
+    }
+
+    @Test
+    public void test() throws Exception {
+        final CompositeNodeBuilder<ImmutableCompositeNode> rootBuilder = ImmutableCompositeNode.builder();
+        rootBuilder.setQName(RPC_NAME);
+
+        final CompositeNodeBuilder<ImmutableCompositeNode> inputBuilder = ImmutableCompositeNode.builder();
+        inputBuilder.setQName(INPUT_QNAME);
+        inputBuilder.addLeaf(STREAM_NAME, "NETCONF");
+
+        rootBuilder.add(inputBuilder.toInstance());
+        final ImmutableCompositeNode root = rootBuilder.toInstance();
+
+        final CompositeNode flattenedNode = NetconfMessageTransformUtil.flattenInput(root);
+        assertNotNull(flattenedNode);
+        assertEquals(1, flattenedNode.size());
+
+        final List<CompositeNode> inputNode = flattenedNode.getCompositesByName(INPUT_QNAME);
+        assertNotNull(inputNode);
+        assertTrue(inputNode.isEmpty());
+
+        final NetconfMessage message = messageTransformer.toRpcRequest(RPC_NAME, root);
+        assertNotNull(message);
+    }
+}
diff --git a/opendaylight/md-sal/sal-netconf-connector/src/test/resources/notification-payload.xml b/opendaylight/md-sal/sal-netconf-connector/src/test/resources/notification-payload.xml
new file mode 100644 (file)
index 0000000..837fcc1
--- /dev/null
@@ -0,0 +1,14 @@
+<notification xmlns="urn:ietf:params:xml:ns:netconf:notification:1.0">
+<eventTime>2014-07-08T11:20:48UTC</eventTime>
+<user-visited-page xmlns="org:opendaylight:notification:test:ns:yang:user-notification">
+  <ui:incoming-user xmlns:ui="org:opendaylight:notification:test:ns:yang:user-notification">ui:public-user</ui:incoming-user>
+  <ip-address>172.23.29.104</ip-address>
+  <mac>00:11:00:ff:dd:02</mac>
+  <browser-id>Chrome 35.0.1916.153 m</browser-id>
+  <region>
+    <name>Slovakia</name>
+    <time-zone>UTC/GMT+2</time-zone>
+  </region>
+  <visiting-date>2014-07-08 11:20:48</visiting-date>
+</user-visited-page>
+</notification>
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-netconf-connector/src/test/resources/schemas/rpc-notification-subscription.yang b/opendaylight/md-sal/sal-netconf-connector/src/test/resources/schemas/rpc-notification-subscription.yang
new file mode 100644 (file)
index 0000000..b13d90f
--- /dev/null
@@ -0,0 +1,38 @@
+module rpc-notification-subscription {
+
+  namespace "urn:opendaylight:params:xml:ns:yang:controller:md:sal:rpc-test";
+  prefix "rpc";
+
+  organization
+    "Cisco Systems, Inc.";
+
+  contact
+    "lsedlak@cisco.com";
+
+  description
+    "Test model for testing of rpc INPUT parameter during subscription call.";
+
+  revision 2014-07-14 {
+    description
+      "Initial revision.";
+  }
+
+  rpc subscribe {
+    description
+      "Test rpc to init subscription";
+
+    input {
+      leaf stream-name {
+        type string;
+        default "NETCONF";
+        description
+          "Optional stream name param.";
+      }
+
+      anyxml data {
+        description
+          "Optional additional data.";
+      }
+    }
+  }
+}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-netconf-connector/src/test/resources/schemas/user-notification.yang b/opendaylight/md-sal/sal-netconf-connector/src/test/resources/schemas/user-notification.yang
new file mode 100644 (file)
index 0000000..50d2206
--- /dev/null
@@ -0,0 +1,56 @@
+module user-notification {
+    yang-version 1;
+    namespace "org:opendaylight:notification:test:ns:yang:user-notification";
+    prefix "user";
+
+    organization "Cisco Systems";
+    contact "Lukas Sedlak";
+    description "Test model for testing notifications";
+
+    revision "2014-07-08" {
+        description "Initial revision";
+    }
+
+    identity user-identity {
+        description "Identity of user incoming to Web Page";
+    }
+
+    identity public-user {
+        base user-identity;
+        description "Identity of random public non-registered user";
+    }
+
+    notification user-visited-page {
+        leaf incoming-user {
+            type identityref {
+                base "user-identity";
+            }
+        }
+
+        leaf ip-address {
+            type string;
+        }
+
+        leaf mac {
+            type string;
+        }
+
+        leaf browser-id {
+            type string;
+        }
+
+        container region {
+            leaf name {
+                type string;
+            }
+
+            leaf time-zone {
+                type string;
+            }
+        }
+
+        leaf visiting-date {
+            type string;
+        }
+    }
+}
\ No newline at end of file
index 778d8c6162c988bb282d5995e7d3e3ab5615ba43..d0be2cbcbb02cdc4310f130aa25c8e4f25fd386b 100644 (file)
@@ -20,4 +20,9 @@ machine
 
  protoc --proto_path=src/main/resources --java_out=src/main/java src/main/resources/*.proto
 
-5. Run mvn clean install and resolve any trailing spaces issues & build the .jar
+5. Run mvn clean install  & build the .jar
+
+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
+   org.opendaylight.controller.protobuff.messages to properly exclude from sonar.
index 671a9441d8733f25449d6542687c529c38d49068..5254c19fcb9d80233b134c18946395b3d16dd269 100644 (file)
       <artifactId>junit</artifactId>
       <scope>test</scope>
     </dependency>
+      <dependency>
+          <groupId>org.opendaylight.yangtools</groupId>
+          <artifactId>util</artifactId>
+      </dependency>
+      <dependency>
+          <groupId>org.opendaylight.yangtools</groupId>
+          <artifactId>yang-common</artifactId>
+      </dependency>
+      <dependency>
+          <groupId>org.opendaylight.yangtools</groupId>
+          <artifactId>yang-data-api</artifactId>
+      </dependency>
+      <dependency>
+          <groupId>org.opendaylight.yangtools</groupId>
+          <artifactId>yang-data-impl</artifactId>
+      </dependency>
+      <dependency>
+          <groupId>org.opendaylight.yangtools</groupId>
+          <artifactId>yang-model-api</artifactId>
+      </dependency>
+      <dependency>
+          <groupId>org.opendaylight.yangtools</groupId>
+          <artifactId>yang-model-util</artifactId>
+      </dependency>
+      <dependency>
+          <groupId>org.opendaylight.yangtools</groupId>
+          <artifactId>yang-binding</artifactId>
+      </dependency>
+      <dependency>
+          <groupId>com.google.guava</groupId>
+          <artifactId>guava</artifactId>
+      </dependency>
+      <dependency>
+          <groupId>junit</groupId>
+          <artifactId>junit</artifactId>
+          <scope>test</scope>
+      </dependency>
+
+      <dependency>
+          <groupId>xmlunit</groupId>
+          <artifactId>xmlunit</artifactId>
+          <version>1.5</version>
+      </dependency>
+
+      <dependency>
+          <groupId>org.opendaylight.yangtools</groupId>
+          <artifactId>yang-parser-impl</artifactId>
+      </dependency>
+      <dependency>
+          <groupId>commons-lang</groupId>
+          <artifactId>commons-lang</artifactId>
+      </dependency>
+      <dependency>
+          <groupId>org.slf4j</groupId>
+          <artifactId>slf4j-simple</artifactId>
+          <version>${slf4j.version}</version>
+          <scope>test</scope>
+      </dependency>
+      <dependency>
+          <groupId>com.google.code.findbugs</groupId>
+          <artifactId>jsr305</artifactId>
+          <version>2.0.1</version>
+      </dependency>
   </dependencies>
 
 </project>
index 72e2c87ecba11018079e9d2c95c844e0bdbfd188..c9e586ba1a1438e7d0f949b06e4881ec63bc2697 100755 (executable)
 # or run command
 #       protoc --proto_path=src/main/resources --java_out=src/main/java src/main/resources/*.proto
 #
-#5. Run mvn clean install and resolve any trailing spaces issues & build the .jar
+#5. Run mvn clean install & build the .jar
+#
+#6  !!!WARNING!!!! never edit the source files generated
+#
+#7. !!!NOTE!!! 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.
 ########################################################################################################
 
 protoc --proto_path=src/main/resources --java_out=src/main/java src/main/resources/*.proto
 
-echo "Done generating Java source files."
\ No newline at end of file
+echo "Done generating Java source files."
+
+#to remove trailing spaces in the code files
+find src/main/java -type f -name '*.java' -exec sed --in-place 's/[[:space:]]\+$//' {} \+
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/transaction/ShardTransactionMessages.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/transaction/ShardTransactionMessages.java
deleted file mode 100644 (file)
index 3a226db..0000000
+++ /dev/null
@@ -1,3606 +0,0 @@
-// Generated by the protocol buffer compiler.  DO NOT EDIT!
-// source: ShardTransactionMessages.proto
-
-package org.opendaylight.controller.cluster.datastore.transaction;
-
-public final class ShardTransactionMessages {
-  private ShardTransactionMessages() {}
-  public static void registerAllExtensions(
-      com.google.protobuf.ExtensionRegistry registry) {
-  }
-  public interface CloseTransactionOrBuilder
-      extends com.google.protobuf.MessageOrBuilder {
-  }
-  /**
-   * Protobuf type {@code org.opendaylight.controller.mdsal.CloseTransaction}
-   */
-  public static final class CloseTransaction extends
-      com.google.protobuf.GeneratedMessage
-      implements CloseTransactionOrBuilder {
-    // Use CloseTransaction.newBuilder() to construct.
-    private CloseTransaction(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
-      super(builder);
-      this.unknownFields = builder.getUnknownFields();
-    }
-    private CloseTransaction(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
-
-    private static final CloseTransaction defaultInstance;
-    public static CloseTransaction getDefaultInstance() {
-      return defaultInstance;
-    }
-
-    public CloseTransaction getDefaultInstanceForType() {
-      return defaultInstance;
-    }
-
-    private final com.google.protobuf.UnknownFieldSet unknownFields;
-    @java.lang.Override
-    public final com.google.protobuf.UnknownFieldSet
-        getUnknownFields() {
-      return this.unknownFields;
-    }
-    private CloseTransaction(
-        com.google.protobuf.CodedInputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      initFields();
-      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
-          com.google.protobuf.UnknownFieldSet.newBuilder();
-      try {
-        boolean done = false;
-        while (!done) {
-          int tag = input.readTag();
-          switch (tag) {
-            case 0:
-              done = true;
-              break;
-            default: {
-              if (!parseUnknownField(input, unknownFields,
-                                     extensionRegistry, tag)) {
-                done = true;
-              }
-              break;
-            }
-          }
-        }
-      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-        throw e.setUnfinishedMessage(this);
-      } catch (java.io.IOException e) {
-        throw new com.google.protobuf.InvalidProtocolBufferException(
-            e.getMessage()).setUnfinishedMessage(this);
-      } finally {
-        this.unknownFields = unknownFields.build();
-        makeExtensionsImmutable();
-      }
-    }
-    public static final com.google.protobuf.Descriptors.Descriptor
-        getDescriptor() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransaction_descriptor;
-    }
-
-    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
-        internalGetFieldAccessorTable() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransaction_fieldAccessorTable
-          .ensureFieldAccessorsInitialized(
-              org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction.Builder.class);
-    }
-
-    public static com.google.protobuf.Parser<CloseTransaction> PARSER =
-        new com.google.protobuf.AbstractParser<CloseTransaction>() {
-      public CloseTransaction parsePartialFrom(
-          com.google.protobuf.CodedInputStream input,
-          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-          throws com.google.protobuf.InvalidProtocolBufferException {
-        return new CloseTransaction(input, extensionRegistry);
-      }
-    };
-
-    @java.lang.Override
-    public com.google.protobuf.Parser<CloseTransaction> getParserForType() {
-      return PARSER;
-    }
-
-    private void initFields() {
-    }
-    private byte memoizedIsInitialized = -1;
-    public final boolean isInitialized() {
-      byte isInitialized = memoizedIsInitialized;
-      if (isInitialized != -1) return isInitialized == 1;
-
-      memoizedIsInitialized = 1;
-      return true;
-    }
-
-    public void writeTo(com.google.protobuf.CodedOutputStream output)
-                        throws java.io.IOException {
-      getSerializedSize();
-      getUnknownFields().writeTo(output);
-    }
-
-    private int memoizedSerializedSize = -1;
-    public int getSerializedSize() {
-      int size = memoizedSerializedSize;
-      if (size != -1) return size;
-
-      size = 0;
-      size += getUnknownFields().getSerializedSize();
-      memoizedSerializedSize = size;
-      return size;
-    }
-
-    private static final long serialVersionUID = 0L;
-    @java.lang.Override
-    protected java.lang.Object writeReplace()
-        throws java.io.ObjectStreamException {
-      return super.writeReplace();
-    }
-
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction parseFrom(
-        com.google.protobuf.ByteString data)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction parseFrom(
-        com.google.protobuf.ByteString data,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction parseFrom(byte[] data)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction parseFrom(
-        byte[] data,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction parseFrom(java.io.InputStream input)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction parseFrom(
-        java.io.InputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction parseDelimitedFrom(java.io.InputStream input)
-        throws java.io.IOException {
-      return PARSER.parseDelimitedFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction parseDelimitedFrom(
-        java.io.InputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseDelimitedFrom(input, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction parseFrom(
-        com.google.protobuf.CodedInputStream input)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction parseFrom(
-        com.google.protobuf.CodedInputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input, extensionRegistry);
-    }
-
-    public static Builder newBuilder() { return Builder.create(); }
-    public Builder newBuilderForType() { return newBuilder(); }
-    public static Builder newBuilder(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction prototype) {
-      return newBuilder().mergeFrom(prototype);
-    }
-    public Builder toBuilder() { return newBuilder(this); }
-
-    @java.lang.Override
-    protected Builder newBuilderForType(
-        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
-      Builder builder = new Builder(parent);
-      return builder;
-    }
-    /**
-     * Protobuf type {@code org.opendaylight.controller.mdsal.CloseTransaction}
-     */
-    public static final class Builder extends
-        com.google.protobuf.GeneratedMessage.Builder<Builder>
-       implements org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionOrBuilder {
-      public static final com.google.protobuf.Descriptors.Descriptor
-          getDescriptor() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransaction_descriptor;
-      }
-
-      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
-          internalGetFieldAccessorTable() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransaction_fieldAccessorTable
-            .ensureFieldAccessorsInitialized(
-                org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction.Builder.class);
-      }
-
-      // Construct using org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction.newBuilder()
-      private Builder() {
-        maybeForceBuilderInitialization();
-      }
-
-      private Builder(
-          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
-        super(parent);
-        maybeForceBuilderInitialization();
-      }
-      private void maybeForceBuilderInitialization() {
-        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
-        }
-      }
-      private static Builder create() {
-        return new Builder();
-      }
-
-      public Builder clear() {
-        super.clear();
-        return this;
-      }
-
-      public Builder clone() {
-        return create().mergeFrom(buildPartial());
-      }
-
-      public com.google.protobuf.Descriptors.Descriptor
-          getDescriptorForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransaction_descriptor;
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction getDefaultInstanceForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction.getDefaultInstance();
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction build() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction result = buildPartial();
-        if (!result.isInitialized()) {
-          throw newUninitializedMessageException(result);
-        }
-        return result;
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction buildPartial() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction result = new org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction(this);
-        onBuilt();
-        return result;
-      }
-
-      public Builder mergeFrom(com.google.protobuf.Message other) {
-        if (other instanceof org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction) {
-          return mergeFrom((org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction)other);
-        } else {
-          super.mergeFrom(other);
-          return this;
-        }
-      }
-
-      public Builder mergeFrom(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction other) {
-        if (other == org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction.getDefaultInstance()) return this;
-        this.mergeUnknownFields(other.getUnknownFields());
-        return this;
-      }
-
-      public final boolean isInitialized() {
-        return true;
-      }
-
-      public Builder mergeFrom(
-          com.google.protobuf.CodedInputStream input,
-          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-          throws java.io.IOException {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction parsedMessage = null;
-        try {
-          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
-        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-          parsedMessage = (org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransaction) e.getUnfinishedMessage();
-          throw e;
-        } finally {
-          if (parsedMessage != null) {
-            mergeFrom(parsedMessage);
-          }
-        }
-        return this;
-      }
-
-      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.CloseTransaction)
-    }
-
-    static {
-      defaultInstance = new CloseTransaction(true);
-      defaultInstance.initFields();
-    }
-
-    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.CloseTransaction)
-  }
-
-  public interface CloseTransactionReplyOrBuilder
-      extends com.google.protobuf.MessageOrBuilder {
-  }
-  /**
-   * Protobuf type {@code org.opendaylight.controller.mdsal.CloseTransactionReply}
-   */
-  public static final class CloseTransactionReply extends
-      com.google.protobuf.GeneratedMessage
-      implements CloseTransactionReplyOrBuilder {
-    // Use CloseTransactionReply.newBuilder() to construct.
-    private CloseTransactionReply(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
-      super(builder);
-      this.unknownFields = builder.getUnknownFields();
-    }
-    private CloseTransactionReply(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
-
-    private static final CloseTransactionReply defaultInstance;
-    public static CloseTransactionReply getDefaultInstance() {
-      return defaultInstance;
-    }
-
-    public CloseTransactionReply getDefaultInstanceForType() {
-      return defaultInstance;
-    }
-
-    private final com.google.protobuf.UnknownFieldSet unknownFields;
-    @java.lang.Override
-    public final com.google.protobuf.UnknownFieldSet
-        getUnknownFields() {
-      return this.unknownFields;
-    }
-    private CloseTransactionReply(
-        com.google.protobuf.CodedInputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      initFields();
-      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
-          com.google.protobuf.UnknownFieldSet.newBuilder();
-      try {
-        boolean done = false;
-        while (!done) {
-          int tag = input.readTag();
-          switch (tag) {
-            case 0:
-              done = true;
-              break;
-            default: {
-              if (!parseUnknownField(input, unknownFields,
-                                     extensionRegistry, tag)) {
-                done = true;
-              }
-              break;
-            }
-          }
-        }
-      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-        throw e.setUnfinishedMessage(this);
-      } catch (java.io.IOException e) {
-        throw new com.google.protobuf.InvalidProtocolBufferException(
-            e.getMessage()).setUnfinishedMessage(this);
-      } finally {
-        this.unknownFields = unknownFields.build();
-        makeExtensionsImmutable();
-      }
-    }
-    public static final com.google.protobuf.Descriptors.Descriptor
-        getDescriptor() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionReply_descriptor;
-    }
-
-    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
-        internalGetFieldAccessorTable() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionReply_fieldAccessorTable
-          .ensureFieldAccessorsInitialized(
-              org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply.Builder.class);
-    }
-
-    public static com.google.protobuf.Parser<CloseTransactionReply> PARSER =
-        new com.google.protobuf.AbstractParser<CloseTransactionReply>() {
-      public CloseTransactionReply parsePartialFrom(
-          com.google.protobuf.CodedInputStream input,
-          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-          throws com.google.protobuf.InvalidProtocolBufferException {
-        return new CloseTransactionReply(input, extensionRegistry);
-      }
-    };
-
-    @java.lang.Override
-    public com.google.protobuf.Parser<CloseTransactionReply> getParserForType() {
-      return PARSER;
-    }
-
-    private void initFields() {
-    }
-    private byte memoizedIsInitialized = -1;
-    public final boolean isInitialized() {
-      byte isInitialized = memoizedIsInitialized;
-      if (isInitialized != -1) return isInitialized == 1;
-
-      memoizedIsInitialized = 1;
-      return true;
-    }
-
-    public void writeTo(com.google.protobuf.CodedOutputStream output)
-                        throws java.io.IOException {
-      getSerializedSize();
-      getUnknownFields().writeTo(output);
-    }
-
-    private int memoizedSerializedSize = -1;
-    public int getSerializedSize() {
-      int size = memoizedSerializedSize;
-      if (size != -1) return size;
-
-      size = 0;
-      size += getUnknownFields().getSerializedSize();
-      memoizedSerializedSize = size;
-      return size;
-    }
-
-    private static final long serialVersionUID = 0L;
-    @java.lang.Override
-    protected java.lang.Object writeReplace()
-        throws java.io.ObjectStreamException {
-      return super.writeReplace();
-    }
-
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply parseFrom(
-        com.google.protobuf.ByteString data)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply parseFrom(
-        com.google.protobuf.ByteString data,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply parseFrom(byte[] data)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply parseFrom(
-        byte[] data,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply parseFrom(java.io.InputStream input)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply parseFrom(
-        java.io.InputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply parseDelimitedFrom(java.io.InputStream input)
-        throws java.io.IOException {
-      return PARSER.parseDelimitedFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply parseDelimitedFrom(
-        java.io.InputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseDelimitedFrom(input, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply parseFrom(
-        com.google.protobuf.CodedInputStream input)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply parseFrom(
-        com.google.protobuf.CodedInputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input, extensionRegistry);
-    }
-
-    public static Builder newBuilder() { return Builder.create(); }
-    public Builder newBuilderForType() { return newBuilder(); }
-    public static Builder newBuilder(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply prototype) {
-      return newBuilder().mergeFrom(prototype);
-    }
-    public Builder toBuilder() { return newBuilder(this); }
-
-    @java.lang.Override
-    protected Builder newBuilderForType(
-        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
-      Builder builder = new Builder(parent);
-      return builder;
-    }
-    /**
-     * Protobuf type {@code org.opendaylight.controller.mdsal.CloseTransactionReply}
-     */
-    public static final class Builder extends
-        com.google.protobuf.GeneratedMessage.Builder<Builder>
-       implements org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReplyOrBuilder {
-      public static final com.google.protobuf.Descriptors.Descriptor
-          getDescriptor() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionReply_descriptor;
-      }
-
-      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
-          internalGetFieldAccessorTable() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionReply_fieldAccessorTable
-            .ensureFieldAccessorsInitialized(
-                org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply.Builder.class);
-      }
-
-      // Construct using org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply.newBuilder()
-      private Builder() {
-        maybeForceBuilderInitialization();
-      }
-
-      private Builder(
-          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
-        super(parent);
-        maybeForceBuilderInitialization();
-      }
-      private void maybeForceBuilderInitialization() {
-        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
-        }
-      }
-      private static Builder create() {
-        return new Builder();
-      }
-
-      public Builder clear() {
-        super.clear();
-        return this;
-      }
-
-      public Builder clone() {
-        return create().mergeFrom(buildPartial());
-      }
-
-      public com.google.protobuf.Descriptors.Descriptor
-          getDescriptorForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionReply_descriptor;
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply getDefaultInstanceForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply.getDefaultInstance();
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply build() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply result = buildPartial();
-        if (!result.isInitialized()) {
-          throw newUninitializedMessageException(result);
-        }
-        return result;
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply buildPartial() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply result = new org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply(this);
-        onBuilt();
-        return result;
-      }
-
-      public Builder mergeFrom(com.google.protobuf.Message other) {
-        if (other instanceof org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply) {
-          return mergeFrom((org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply)other);
-        } else {
-          super.mergeFrom(other);
-          return this;
-        }
-      }
-
-      public Builder mergeFrom(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply other) {
-        if (other == org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply.getDefaultInstance()) return this;
-        this.mergeUnknownFields(other.getUnknownFields());
-        return this;
-      }
-
-      public final boolean isInitialized() {
-        return true;
-      }
-
-      public Builder mergeFrom(
-          com.google.protobuf.CodedInputStream input,
-          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-          throws java.io.IOException {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply parsedMessage = null;
-        try {
-          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
-        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-          parsedMessage = (org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CloseTransactionReply) e.getUnfinishedMessage();
-          throw e;
-        } finally {
-          if (parsedMessage != null) {
-            mergeFrom(parsedMessage);
-          }
-        }
-        return this;
-      }
-
-      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.CloseTransactionReply)
-    }
-
-    static {
-      defaultInstance = new CloseTransactionReply(true);
-      defaultInstance.initFields();
-    }
-
-    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.CloseTransactionReply)
-  }
-
-  public interface CreateTransactionOrBuilder
-      extends com.google.protobuf.MessageOrBuilder {
-  }
-  /**
-   * Protobuf type {@code org.opendaylight.controller.mdsal.CreateTransaction}
-   */
-  public static final class CreateTransaction extends
-      com.google.protobuf.GeneratedMessage
-      implements CreateTransactionOrBuilder {
-    // Use CreateTransaction.newBuilder() to construct.
-    private CreateTransaction(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
-      super(builder);
-      this.unknownFields = builder.getUnknownFields();
-    }
-    private CreateTransaction(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
-
-    private static final CreateTransaction defaultInstance;
-    public static CreateTransaction getDefaultInstance() {
-      return defaultInstance;
-    }
-
-    public CreateTransaction getDefaultInstanceForType() {
-      return defaultInstance;
-    }
-
-    private final com.google.protobuf.UnknownFieldSet unknownFields;
-    @java.lang.Override
-    public final com.google.protobuf.UnknownFieldSet
-        getUnknownFields() {
-      return this.unknownFields;
-    }
-    private CreateTransaction(
-        com.google.protobuf.CodedInputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      initFields();
-      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
-          com.google.protobuf.UnknownFieldSet.newBuilder();
-      try {
-        boolean done = false;
-        while (!done) {
-          int tag = input.readTag();
-          switch (tag) {
-            case 0:
-              done = true;
-              break;
-            default: {
-              if (!parseUnknownField(input, unknownFields,
-                                     extensionRegistry, tag)) {
-                done = true;
-              }
-              break;
-            }
-          }
-        }
-      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-        throw e.setUnfinishedMessage(this);
-      } catch (java.io.IOException e) {
-        throw new com.google.protobuf.InvalidProtocolBufferException(
-            e.getMessage()).setUnfinishedMessage(this);
-      } finally {
-        this.unknownFields = unknownFields.build();
-        makeExtensionsImmutable();
-      }
-    }
-    public static final com.google.protobuf.Descriptors.Descriptor
-        getDescriptor() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransaction_descriptor;
-    }
-
-    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
-        internalGetFieldAccessorTable() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransaction_fieldAccessorTable
-          .ensureFieldAccessorsInitialized(
-              org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction.Builder.class);
-    }
-
-    public static com.google.protobuf.Parser<CreateTransaction> PARSER =
-        new com.google.protobuf.AbstractParser<CreateTransaction>() {
-      public CreateTransaction parsePartialFrom(
-          com.google.protobuf.CodedInputStream input,
-          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-          throws com.google.protobuf.InvalidProtocolBufferException {
-        return new CreateTransaction(input, extensionRegistry);
-      }
-    };
-
-    @java.lang.Override
-    public com.google.protobuf.Parser<CreateTransaction> getParserForType() {
-      return PARSER;
-    }
-
-    private void initFields() {
-    }
-    private byte memoizedIsInitialized = -1;
-    public final boolean isInitialized() {
-      byte isInitialized = memoizedIsInitialized;
-      if (isInitialized != -1) return isInitialized == 1;
-
-      memoizedIsInitialized = 1;
-      return true;
-    }
-
-    public void writeTo(com.google.protobuf.CodedOutputStream output)
-                        throws java.io.IOException {
-      getSerializedSize();
-      getUnknownFields().writeTo(output);
-    }
-
-    private int memoizedSerializedSize = -1;
-    public int getSerializedSize() {
-      int size = memoizedSerializedSize;
-      if (size != -1) return size;
-
-      size = 0;
-      size += getUnknownFields().getSerializedSize();
-      memoizedSerializedSize = size;
-      return size;
-    }
-
-    private static final long serialVersionUID = 0L;
-    @java.lang.Override
-    protected java.lang.Object writeReplace()
-        throws java.io.ObjectStreamException {
-      return super.writeReplace();
-    }
-
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction parseFrom(
-        com.google.protobuf.ByteString data)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction parseFrom(
-        com.google.protobuf.ByteString data,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction parseFrom(byte[] data)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction parseFrom(
-        byte[] data,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction parseFrom(java.io.InputStream input)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction parseFrom(
-        java.io.InputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction parseDelimitedFrom(java.io.InputStream input)
-        throws java.io.IOException {
-      return PARSER.parseDelimitedFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction parseDelimitedFrom(
-        java.io.InputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseDelimitedFrom(input, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction parseFrom(
-        com.google.protobuf.CodedInputStream input)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction parseFrom(
-        com.google.protobuf.CodedInputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input, extensionRegistry);
-    }
-
-    public static Builder newBuilder() { return Builder.create(); }
-    public Builder newBuilderForType() { return newBuilder(); }
-    public static Builder newBuilder(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction prototype) {
-      return newBuilder().mergeFrom(prototype);
-    }
-    public Builder toBuilder() { return newBuilder(this); }
-
-    @java.lang.Override
-    protected Builder newBuilderForType(
-        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
-      Builder builder = new Builder(parent);
-      return builder;
-    }
-    /**
-     * Protobuf type {@code org.opendaylight.controller.mdsal.CreateTransaction}
-     */
-    public static final class Builder extends
-        com.google.protobuf.GeneratedMessage.Builder<Builder>
-       implements org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionOrBuilder {
-      public static final com.google.protobuf.Descriptors.Descriptor
-          getDescriptor() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransaction_descriptor;
-      }
-
-      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
-          internalGetFieldAccessorTable() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransaction_fieldAccessorTable
-            .ensureFieldAccessorsInitialized(
-                org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction.Builder.class);
-      }
-
-      // Construct using org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction.newBuilder()
-      private Builder() {
-        maybeForceBuilderInitialization();
-      }
-
-      private Builder(
-          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
-        super(parent);
-        maybeForceBuilderInitialization();
-      }
-      private void maybeForceBuilderInitialization() {
-        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
-        }
-      }
-      private static Builder create() {
-        return new Builder();
-      }
-
-      public Builder clear() {
-        super.clear();
-        return this;
-      }
-
-      public Builder clone() {
-        return create().mergeFrom(buildPartial());
-      }
-
-      public com.google.protobuf.Descriptors.Descriptor
-          getDescriptorForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransaction_descriptor;
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction getDefaultInstanceForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction.getDefaultInstance();
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction build() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction result = buildPartial();
-        if (!result.isInitialized()) {
-          throw newUninitializedMessageException(result);
-        }
-        return result;
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction buildPartial() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction result = new org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction(this);
-        onBuilt();
-        return result;
-      }
-
-      public Builder mergeFrom(com.google.protobuf.Message other) {
-        if (other instanceof org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction) {
-          return mergeFrom((org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction)other);
-        } else {
-          super.mergeFrom(other);
-          return this;
-        }
-      }
-
-      public Builder mergeFrom(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction other) {
-        if (other == org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction.getDefaultInstance()) return this;
-        this.mergeUnknownFields(other.getUnknownFields());
-        return this;
-      }
-
-      public final boolean isInitialized() {
-        return true;
-      }
-
-      public Builder mergeFrom(
-          com.google.protobuf.CodedInputStream input,
-          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-          throws java.io.IOException {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction parsedMessage = null;
-        try {
-          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
-        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-          parsedMessage = (org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransaction) e.getUnfinishedMessage();
-          throw e;
-        } finally {
-          if (parsedMessage != null) {
-            mergeFrom(parsedMessage);
-          }
-        }
-        return this;
-      }
-
-      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.CreateTransaction)
-    }
-
-    static {
-      defaultInstance = new CreateTransaction(true);
-      defaultInstance.initFields();
-    }
-
-    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.CreateTransaction)
-  }
-
-  public interface CreateTransactionReplyOrBuilder
-      extends com.google.protobuf.MessageOrBuilder {
-
-    // required string transactionPath = 1;
-    /**
-     * <code>required string transactionPath = 1;</code>
-     */
-    boolean hasTransactionPath();
-    /**
-     * <code>required string transactionPath = 1;</code>
-     */
-    java.lang.String getTransactionPath();
-    /**
-     * <code>required string transactionPath = 1;</code>
-     */
-    com.google.protobuf.ByteString
-        getTransactionPathBytes();
-  }
-  /**
-   * Protobuf type {@code org.opendaylight.controller.mdsal.CreateTransactionReply}
-   */
-  public static final class CreateTransactionReply extends
-      com.google.protobuf.GeneratedMessage
-      implements CreateTransactionReplyOrBuilder {
-    // Use CreateTransactionReply.newBuilder() to construct.
-    private CreateTransactionReply(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
-      super(builder);
-      this.unknownFields = builder.getUnknownFields();
-    }
-    private CreateTransactionReply(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
-
-    private static final CreateTransactionReply defaultInstance;
-    public static CreateTransactionReply getDefaultInstance() {
-      return defaultInstance;
-    }
-
-    public CreateTransactionReply getDefaultInstanceForType() {
-      return defaultInstance;
-    }
-
-    private final com.google.protobuf.UnknownFieldSet unknownFields;
-    @java.lang.Override
-    public final com.google.protobuf.UnknownFieldSet
-        getUnknownFields() {
-      return this.unknownFields;
-    }
-    private CreateTransactionReply(
-        com.google.protobuf.CodedInputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      initFields();
-      int mutable_bitField0_ = 0;
-      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
-          com.google.protobuf.UnknownFieldSet.newBuilder();
-      try {
-        boolean done = false;
-        while (!done) {
-          int tag = input.readTag();
-          switch (tag) {
-            case 0:
-              done = true;
-              break;
-            default: {
-              if (!parseUnknownField(input, unknownFields,
-                                     extensionRegistry, tag)) {
-                done = true;
-              }
-              break;
-            }
-            case 10: {
-              bitField0_ |= 0x00000001;
-              transactionPath_ = input.readBytes();
-              break;
-            }
-          }
-        }
-      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-        throw e.setUnfinishedMessage(this);
-      } catch (java.io.IOException e) {
-        throw new com.google.protobuf.InvalidProtocolBufferException(
-            e.getMessage()).setUnfinishedMessage(this);
-      } finally {
-        this.unknownFields = unknownFields.build();
-        makeExtensionsImmutable();
-      }
-    }
-    public static final com.google.protobuf.Descriptors.Descriptor
-        getDescriptor() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_descriptor;
-    }
-
-    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
-        internalGetFieldAccessorTable() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_fieldAccessorTable
-          .ensureFieldAccessorsInitialized(
-              org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply.Builder.class);
-    }
-
-    public static com.google.protobuf.Parser<CreateTransactionReply> PARSER =
-        new com.google.protobuf.AbstractParser<CreateTransactionReply>() {
-      public CreateTransactionReply parsePartialFrom(
-          com.google.protobuf.CodedInputStream input,
-          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-          throws com.google.protobuf.InvalidProtocolBufferException {
-        return new CreateTransactionReply(input, extensionRegistry);
-      }
-    };
-
-    @java.lang.Override
-    public com.google.protobuf.Parser<CreateTransactionReply> getParserForType() {
-      return PARSER;
-    }
-
-    private int bitField0_;
-    // required string transactionPath = 1;
-    public static final int TRANSACTIONPATH_FIELD_NUMBER = 1;
-    private java.lang.Object transactionPath_;
-    /**
-     * <code>required string transactionPath = 1;</code>
-     */
-    public boolean hasTransactionPath() {
-      return ((bitField0_ & 0x00000001) == 0x00000001);
-    }
-    /**
-     * <code>required string transactionPath = 1;</code>
-     */
-    public java.lang.String getTransactionPath() {
-      java.lang.Object ref = transactionPath_;
-      if (ref instanceof java.lang.String) {
-        return (java.lang.String) ref;
-      } else {
-        com.google.protobuf.ByteString bs =
-            (com.google.protobuf.ByteString) ref;
-        java.lang.String s = bs.toStringUtf8();
-        if (bs.isValidUtf8()) {
-          transactionPath_ = s;
-        }
-        return s;
-      }
-    }
-    /**
-     * <code>required string transactionPath = 1;</code>
-     */
-    public com.google.protobuf.ByteString
-        getTransactionPathBytes() {
-      java.lang.Object ref = transactionPath_;
-      if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b =
-            com.google.protobuf.ByteString.copyFromUtf8(
-                (java.lang.String) ref);
-        transactionPath_ = b;
-        return b;
-      } else {
-        return (com.google.protobuf.ByteString) ref;
-      }
-    }
-
-    private void initFields() {
-      transactionPath_ = "";
-    }
-    private byte memoizedIsInitialized = -1;
-    public final boolean isInitialized() {
-      byte isInitialized = memoizedIsInitialized;
-      if (isInitialized != -1) return isInitialized == 1;
-
-      if (!hasTransactionPath()) {
-        memoizedIsInitialized = 0;
-        return false;
-      }
-      memoizedIsInitialized = 1;
-      return true;
-    }
-
-    public void writeTo(com.google.protobuf.CodedOutputStream output)
-                        throws java.io.IOException {
-      getSerializedSize();
-      if (((bitField0_ & 0x00000001) == 0x00000001)) {
-        output.writeBytes(1, getTransactionPathBytes());
-      }
-      getUnknownFields().writeTo(output);
-    }
-
-    private int memoizedSerializedSize = -1;
-    public int getSerializedSize() {
-      int size = memoizedSerializedSize;
-      if (size != -1) return size;
-
-      size = 0;
-      if (((bitField0_ & 0x00000001) == 0x00000001)) {
-        size += com.google.protobuf.CodedOutputStream
-          .computeBytesSize(1, getTransactionPathBytes());
-      }
-      size += getUnknownFields().getSerializedSize();
-      memoizedSerializedSize = size;
-      return size;
-    }
-
-    private static final long serialVersionUID = 0L;
-    @java.lang.Override
-    protected java.lang.Object writeReplace()
-        throws java.io.ObjectStreamException {
-      return super.writeReplace();
-    }
-
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply parseFrom(
-        com.google.protobuf.ByteString data)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply parseFrom(
-        com.google.protobuf.ByteString data,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply parseFrom(byte[] data)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply parseFrom(
-        byte[] data,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply parseFrom(java.io.InputStream input)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply parseFrom(
-        java.io.InputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply parseDelimitedFrom(java.io.InputStream input)
-        throws java.io.IOException {
-      return PARSER.parseDelimitedFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply parseDelimitedFrom(
-        java.io.InputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseDelimitedFrom(input, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply parseFrom(
-        com.google.protobuf.CodedInputStream input)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply parseFrom(
-        com.google.protobuf.CodedInputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input, extensionRegistry);
-    }
-
-    public static Builder newBuilder() { return Builder.create(); }
-    public Builder newBuilderForType() { return newBuilder(); }
-    public static Builder newBuilder(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply prototype) {
-      return newBuilder().mergeFrom(prototype);
-    }
-    public Builder toBuilder() { return newBuilder(this); }
-
-    @java.lang.Override
-    protected Builder newBuilderForType(
-        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
-      Builder builder = new Builder(parent);
-      return builder;
-    }
-    /**
-     * Protobuf type {@code org.opendaylight.controller.mdsal.CreateTransactionReply}
-     */
-    public static final class Builder extends
-        com.google.protobuf.GeneratedMessage.Builder<Builder>
-       implements org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReplyOrBuilder {
-      public static final com.google.protobuf.Descriptors.Descriptor
-          getDescriptor() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_descriptor;
-      }
-
-      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
-          internalGetFieldAccessorTable() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_fieldAccessorTable
-            .ensureFieldAccessorsInitialized(
-                org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply.Builder.class);
-      }
-
-      // Construct using org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply.newBuilder()
-      private Builder() {
-        maybeForceBuilderInitialization();
-      }
-
-      private Builder(
-          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
-        super(parent);
-        maybeForceBuilderInitialization();
-      }
-      private void maybeForceBuilderInitialization() {
-        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
-        }
-      }
-      private static Builder create() {
-        return new Builder();
-      }
-
-      public Builder clear() {
-        super.clear();
-        transactionPath_ = "";
-        bitField0_ = (bitField0_ & ~0x00000001);
-        return this;
-      }
-
-      public Builder clone() {
-        return create().mergeFrom(buildPartial());
-      }
-
-      public com.google.protobuf.Descriptors.Descriptor
-          getDescriptorForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_descriptor;
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply getDefaultInstanceForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply.getDefaultInstance();
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply build() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply result = buildPartial();
-        if (!result.isInitialized()) {
-          throw newUninitializedMessageException(result);
-        }
-        return result;
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply buildPartial() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply result = new org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply(this);
-        int from_bitField0_ = bitField0_;
-        int to_bitField0_ = 0;
-        if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
-          to_bitField0_ |= 0x00000001;
-        }
-        result.transactionPath_ = transactionPath_;
-        result.bitField0_ = to_bitField0_;
-        onBuilt();
-        return result;
-      }
-
-      public Builder mergeFrom(com.google.protobuf.Message other) {
-        if (other instanceof org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply) {
-          return mergeFrom((org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply)other);
-        } else {
-          super.mergeFrom(other);
-          return this;
-        }
-      }
-
-      public Builder mergeFrom(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply other) {
-        if (other == org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply.getDefaultInstance()) return this;
-        if (other.hasTransactionPath()) {
-          bitField0_ |= 0x00000001;
-          transactionPath_ = other.transactionPath_;
-          onChanged();
-        }
-        this.mergeUnknownFields(other.getUnknownFields());
-        return this;
-      }
-
-      public final boolean isInitialized() {
-        if (!hasTransactionPath()) {
-
-          return false;
-        }
-        return true;
-      }
-
-      public Builder mergeFrom(
-          com.google.protobuf.CodedInputStream input,
-          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-          throws java.io.IOException {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply parsedMessage = null;
-        try {
-          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
-        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-          parsedMessage = (org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.CreateTransactionReply) e.getUnfinishedMessage();
-          throw e;
-        } finally {
-          if (parsedMessage != null) {
-            mergeFrom(parsedMessage);
-          }
-        }
-        return this;
-      }
-      private int bitField0_;
-
-      // required string transactionPath = 1;
-      private java.lang.Object transactionPath_ = "";
-      /**
-       * <code>required string transactionPath = 1;</code>
-       */
-      public boolean hasTransactionPath() {
-        return ((bitField0_ & 0x00000001) == 0x00000001);
-      }
-      /**
-       * <code>required string transactionPath = 1;</code>
-       */
-      public java.lang.String getTransactionPath() {
-        java.lang.Object ref = transactionPath_;
-        if (!(ref instanceof java.lang.String)) {
-          java.lang.String s = ((com.google.protobuf.ByteString) ref)
-              .toStringUtf8();
-          transactionPath_ = s;
-          return s;
-        } else {
-          return (java.lang.String) ref;
-        }
-      }
-      /**
-       * <code>required string transactionPath = 1;</code>
-       */
-      public com.google.protobuf.ByteString
-          getTransactionPathBytes() {
-        java.lang.Object ref = transactionPath_;
-        if (ref instanceof String) {
-          com.google.protobuf.ByteString b =
-              com.google.protobuf.ByteString.copyFromUtf8(
-                  (java.lang.String) ref);
-          transactionPath_ = b;
-          return b;
-        } else {
-          return (com.google.protobuf.ByteString) ref;
-        }
-      }
-      /**
-       * <code>required string transactionPath = 1;</code>
-       */
-      public Builder setTransactionPath(
-          java.lang.String value) {
-        if (value == null) {
-    throw new NullPointerException();
-  }
-  bitField0_ |= 0x00000001;
-        transactionPath_ = value;
-        onChanged();
-        return this;
-      }
-      /**
-       * <code>required string transactionPath = 1;</code>
-       */
-      public Builder clearTransactionPath() {
-        bitField0_ = (bitField0_ & ~0x00000001);
-        transactionPath_ = getDefaultInstance().getTransactionPath();
-        onChanged();
-        return this;
-      }
-      /**
-       * <code>required string transactionPath = 1;</code>
-       */
-      public Builder setTransactionPathBytes(
-          com.google.protobuf.ByteString value) {
-        if (value == null) {
-    throw new NullPointerException();
-  }
-  bitField0_ |= 0x00000001;
-        transactionPath_ = value;
-        onChanged();
-        return this;
-      }
-
-      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.CreateTransactionReply)
-    }
-
-    static {
-      defaultInstance = new CreateTransactionReply(true);
-      defaultInstance.initFields();
-    }
-
-    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.CreateTransactionReply)
-  }
-
-  public interface ReadyTransactionOrBuilder
-      extends com.google.protobuf.MessageOrBuilder {
-  }
-  /**
-   * Protobuf type {@code org.opendaylight.controller.mdsal.ReadyTransaction}
-   */
-  public static final class ReadyTransaction extends
-      com.google.protobuf.GeneratedMessage
-      implements ReadyTransactionOrBuilder {
-    // Use ReadyTransaction.newBuilder() to construct.
-    private ReadyTransaction(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
-      super(builder);
-      this.unknownFields = builder.getUnknownFields();
-    }
-    private ReadyTransaction(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
-
-    private static final ReadyTransaction defaultInstance;
-    public static ReadyTransaction getDefaultInstance() {
-      return defaultInstance;
-    }
-
-    public ReadyTransaction getDefaultInstanceForType() {
-      return defaultInstance;
-    }
-
-    private final com.google.protobuf.UnknownFieldSet unknownFields;
-    @java.lang.Override
-    public final com.google.protobuf.UnknownFieldSet
-        getUnknownFields() {
-      return this.unknownFields;
-    }
-    private ReadyTransaction(
-        com.google.protobuf.CodedInputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      initFields();
-      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
-          com.google.protobuf.UnknownFieldSet.newBuilder();
-      try {
-        boolean done = false;
-        while (!done) {
-          int tag = input.readTag();
-          switch (tag) {
-            case 0:
-              done = true;
-              break;
-            default: {
-              if (!parseUnknownField(input, unknownFields,
-                                     extensionRegistry, tag)) {
-                done = true;
-              }
-              break;
-            }
-          }
-        }
-      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-        throw e.setUnfinishedMessage(this);
-      } catch (java.io.IOException e) {
-        throw new com.google.protobuf.InvalidProtocolBufferException(
-            e.getMessage()).setUnfinishedMessage(this);
-      } finally {
-        this.unknownFields = unknownFields.build();
-        makeExtensionsImmutable();
-      }
-    }
-    public static final com.google.protobuf.Descriptors.Descriptor
-        getDescriptor() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_descriptor;
-    }
-
-    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
-        internalGetFieldAccessorTable() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_fieldAccessorTable
-          .ensureFieldAccessorsInitialized(
-              org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction.Builder.class);
-    }
-
-    public static com.google.protobuf.Parser<ReadyTransaction> PARSER =
-        new com.google.protobuf.AbstractParser<ReadyTransaction>() {
-      public ReadyTransaction parsePartialFrom(
-          com.google.protobuf.CodedInputStream input,
-          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-          throws com.google.protobuf.InvalidProtocolBufferException {
-        return new ReadyTransaction(input, extensionRegistry);
-      }
-    };
-
-    @java.lang.Override
-    public com.google.protobuf.Parser<ReadyTransaction> getParserForType() {
-      return PARSER;
-    }
-
-    private void initFields() {
-    }
-    private byte memoizedIsInitialized = -1;
-    public final boolean isInitialized() {
-      byte isInitialized = memoizedIsInitialized;
-      if (isInitialized != -1) return isInitialized == 1;
-
-      memoizedIsInitialized = 1;
-      return true;
-    }
-
-    public void writeTo(com.google.protobuf.CodedOutputStream output)
-                        throws java.io.IOException {
-      getSerializedSize();
-      getUnknownFields().writeTo(output);
-    }
-
-    private int memoizedSerializedSize = -1;
-    public int getSerializedSize() {
-      int size = memoizedSerializedSize;
-      if (size != -1) return size;
-
-      size = 0;
-      size += getUnknownFields().getSerializedSize();
-      memoizedSerializedSize = size;
-      return size;
-    }
-
-    private static final long serialVersionUID = 0L;
-    @java.lang.Override
-    protected java.lang.Object writeReplace()
-        throws java.io.ObjectStreamException {
-      return super.writeReplace();
-    }
-
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction parseFrom(
-        com.google.protobuf.ByteString data)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction parseFrom(
-        com.google.protobuf.ByteString data,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction parseFrom(byte[] data)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction parseFrom(
-        byte[] data,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction parseFrom(java.io.InputStream input)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction parseFrom(
-        java.io.InputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction parseDelimitedFrom(java.io.InputStream input)
-        throws java.io.IOException {
-      return PARSER.parseDelimitedFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction parseDelimitedFrom(
-        java.io.InputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseDelimitedFrom(input, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction parseFrom(
-        com.google.protobuf.CodedInputStream input)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction parseFrom(
-        com.google.protobuf.CodedInputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input, extensionRegistry);
-    }
-
-    public static Builder newBuilder() { return Builder.create(); }
-    public Builder newBuilderForType() { return newBuilder(); }
-    public static Builder newBuilder(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction prototype) {
-      return newBuilder().mergeFrom(prototype);
-    }
-    public Builder toBuilder() { return newBuilder(this); }
-
-    @java.lang.Override
-    protected Builder newBuilderForType(
-        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
-      Builder builder = new Builder(parent);
-      return builder;
-    }
-    /**
-     * Protobuf type {@code org.opendaylight.controller.mdsal.ReadyTransaction}
-     */
-    public static final class Builder extends
-        com.google.protobuf.GeneratedMessage.Builder<Builder>
-       implements org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionOrBuilder {
-      public static final com.google.protobuf.Descriptors.Descriptor
-          getDescriptor() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_descriptor;
-      }
-
-      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
-          internalGetFieldAccessorTable() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_fieldAccessorTable
-            .ensureFieldAccessorsInitialized(
-                org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction.Builder.class);
-      }
-
-      // Construct using org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction.newBuilder()
-      private Builder() {
-        maybeForceBuilderInitialization();
-      }
-
-      private Builder(
-          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
-        super(parent);
-        maybeForceBuilderInitialization();
-      }
-      private void maybeForceBuilderInitialization() {
-        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
-        }
-      }
-      private static Builder create() {
-        return new Builder();
-      }
-
-      public Builder clear() {
-        super.clear();
-        return this;
-      }
-
-      public Builder clone() {
-        return create().mergeFrom(buildPartial());
-      }
-
-      public com.google.protobuf.Descriptors.Descriptor
-          getDescriptorForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_descriptor;
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction getDefaultInstanceForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction.getDefaultInstance();
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction build() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction result = buildPartial();
-        if (!result.isInitialized()) {
-          throw newUninitializedMessageException(result);
-        }
-        return result;
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction buildPartial() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction result = new org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction(this);
-        onBuilt();
-        return result;
-      }
-
-      public Builder mergeFrom(com.google.protobuf.Message other) {
-        if (other instanceof org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction) {
-          return mergeFrom((org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction)other);
-        } else {
-          super.mergeFrom(other);
-          return this;
-        }
-      }
-
-      public Builder mergeFrom(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction other) {
-        if (other == org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction.getDefaultInstance()) return this;
-        this.mergeUnknownFields(other.getUnknownFields());
-        return this;
-      }
-
-      public final boolean isInitialized() {
-        return true;
-      }
-
-      public Builder mergeFrom(
-          com.google.protobuf.CodedInputStream input,
-          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-          throws java.io.IOException {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction parsedMessage = null;
-        try {
-          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
-        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-          parsedMessage = (org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransaction) e.getUnfinishedMessage();
-          throw e;
-        } finally {
-          if (parsedMessage != null) {
-            mergeFrom(parsedMessage);
-          }
-        }
-        return this;
-      }
-
-      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.ReadyTransaction)
-    }
-
-    static {
-      defaultInstance = new ReadyTransaction(true);
-      defaultInstance.initFields();
-    }
-
-    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.ReadyTransaction)
-  }
-
-  public interface ReadyTransactionReplyOrBuilder
-      extends com.google.protobuf.MessageOrBuilder {
-
-    // required string actorPath = 1;
-    /**
-     * <code>required string actorPath = 1;</code>
-     */
-    boolean hasActorPath();
-    /**
-     * <code>required string actorPath = 1;</code>
-     */
-    java.lang.String getActorPath();
-    /**
-     * <code>required string actorPath = 1;</code>
-     */
-    com.google.protobuf.ByteString
-        getActorPathBytes();
-  }
-  /**
-   * Protobuf type {@code org.opendaylight.controller.mdsal.ReadyTransactionReply}
-   */
-  public static final class ReadyTransactionReply extends
-      com.google.protobuf.GeneratedMessage
-      implements ReadyTransactionReplyOrBuilder {
-    // Use ReadyTransactionReply.newBuilder() to construct.
-    private ReadyTransactionReply(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
-      super(builder);
-      this.unknownFields = builder.getUnknownFields();
-    }
-    private ReadyTransactionReply(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
-
-    private static final ReadyTransactionReply defaultInstance;
-    public static ReadyTransactionReply getDefaultInstance() {
-      return defaultInstance;
-    }
-
-    public ReadyTransactionReply getDefaultInstanceForType() {
-      return defaultInstance;
-    }
-
-    private final com.google.protobuf.UnknownFieldSet unknownFields;
-    @java.lang.Override
-    public final com.google.protobuf.UnknownFieldSet
-        getUnknownFields() {
-      return this.unknownFields;
-    }
-    private ReadyTransactionReply(
-        com.google.protobuf.CodedInputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      initFields();
-      int mutable_bitField0_ = 0;
-      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
-          com.google.protobuf.UnknownFieldSet.newBuilder();
-      try {
-        boolean done = false;
-        while (!done) {
-          int tag = input.readTag();
-          switch (tag) {
-            case 0:
-              done = true;
-              break;
-            default: {
-              if (!parseUnknownField(input, unknownFields,
-                                     extensionRegistry, tag)) {
-                done = true;
-              }
-              break;
-            }
-            case 10: {
-              bitField0_ |= 0x00000001;
-              actorPath_ = input.readBytes();
-              break;
-            }
-          }
-        }
-      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-        throw e.setUnfinishedMessage(this);
-      } catch (java.io.IOException e) {
-        throw new com.google.protobuf.InvalidProtocolBufferException(
-            e.getMessage()).setUnfinishedMessage(this);
-      } finally {
-        this.unknownFields = unknownFields.build();
-        makeExtensionsImmutable();
-      }
-    }
-    public static final com.google.protobuf.Descriptors.Descriptor
-        getDescriptor() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadyTransactionReply_descriptor;
-    }
-
-    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
-        internalGetFieldAccessorTable() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadyTransactionReply_fieldAccessorTable
-          .ensureFieldAccessorsInitialized(
-              org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply.Builder.class);
-    }
-
-    public static com.google.protobuf.Parser<ReadyTransactionReply> PARSER =
-        new com.google.protobuf.AbstractParser<ReadyTransactionReply>() {
-      public ReadyTransactionReply parsePartialFrom(
-          com.google.protobuf.CodedInputStream input,
-          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-          throws com.google.protobuf.InvalidProtocolBufferException {
-        return new ReadyTransactionReply(input, extensionRegistry);
-      }
-    };
-
-    @java.lang.Override
-    public com.google.protobuf.Parser<ReadyTransactionReply> getParserForType() {
-      return PARSER;
-    }
-
-    private int bitField0_;
-    // required string actorPath = 1;
-    public static final int ACTORPATH_FIELD_NUMBER = 1;
-    private java.lang.Object actorPath_;
-    /**
-     * <code>required string actorPath = 1;</code>
-     */
-    public boolean hasActorPath() {
-      return ((bitField0_ & 0x00000001) == 0x00000001);
-    }
-    /**
-     * <code>required string actorPath = 1;</code>
-     */
-    public java.lang.String getActorPath() {
-      java.lang.Object ref = actorPath_;
-      if (ref instanceof java.lang.String) {
-        return (java.lang.String) ref;
-      } else {
-        com.google.protobuf.ByteString bs =
-            (com.google.protobuf.ByteString) ref;
-        java.lang.String s = bs.toStringUtf8();
-        if (bs.isValidUtf8()) {
-          actorPath_ = s;
-        }
-        return s;
-      }
-    }
-    /**
-     * <code>required string actorPath = 1;</code>
-     */
-    public com.google.protobuf.ByteString
-        getActorPathBytes() {
-      java.lang.Object ref = actorPath_;
-      if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b =
-            com.google.protobuf.ByteString.copyFromUtf8(
-                (java.lang.String) ref);
-        actorPath_ = b;
-        return b;
-      } else {
-        return (com.google.protobuf.ByteString) ref;
-      }
-    }
-
-    private void initFields() {
-      actorPath_ = "";
-    }
-    private byte memoizedIsInitialized = -1;
-    public final boolean isInitialized() {
-      byte isInitialized = memoizedIsInitialized;
-      if (isInitialized != -1) return isInitialized == 1;
-
-      if (!hasActorPath()) {
-        memoizedIsInitialized = 0;
-        return false;
-      }
-      memoizedIsInitialized = 1;
-      return true;
-    }
-
-    public void writeTo(com.google.protobuf.CodedOutputStream output)
-                        throws java.io.IOException {
-      getSerializedSize();
-      if (((bitField0_ & 0x00000001) == 0x00000001)) {
-        output.writeBytes(1, getActorPathBytes());
-      }
-      getUnknownFields().writeTo(output);
-    }
-
-    private int memoizedSerializedSize = -1;
-    public int getSerializedSize() {
-      int size = memoizedSerializedSize;
-      if (size != -1) return size;
-
-      size = 0;
-      if (((bitField0_ & 0x00000001) == 0x00000001)) {
-        size += com.google.protobuf.CodedOutputStream
-          .computeBytesSize(1, getActorPathBytes());
-      }
-      size += getUnknownFields().getSerializedSize();
-      memoizedSerializedSize = size;
-      return size;
-    }
-
-    private static final long serialVersionUID = 0L;
-    @java.lang.Override
-    protected java.lang.Object writeReplace()
-        throws java.io.ObjectStreamException {
-      return super.writeReplace();
-    }
-
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply parseFrom(
-        com.google.protobuf.ByteString data)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply parseFrom(
-        com.google.protobuf.ByteString data,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply parseFrom(byte[] data)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply parseFrom(
-        byte[] data,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply parseFrom(java.io.InputStream input)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply parseFrom(
-        java.io.InputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply parseDelimitedFrom(java.io.InputStream input)
-        throws java.io.IOException {
-      return PARSER.parseDelimitedFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply parseDelimitedFrom(
-        java.io.InputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseDelimitedFrom(input, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply parseFrom(
-        com.google.protobuf.CodedInputStream input)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply parseFrom(
-        com.google.protobuf.CodedInputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input, extensionRegistry);
-    }
-
-    public static Builder newBuilder() { return Builder.create(); }
-    public Builder newBuilderForType() { return newBuilder(); }
-    public static Builder newBuilder(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply prototype) {
-      return newBuilder().mergeFrom(prototype);
-    }
-    public Builder toBuilder() { return newBuilder(this); }
-
-    @java.lang.Override
-    protected Builder newBuilderForType(
-        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
-      Builder builder = new Builder(parent);
-      return builder;
-    }
-    /**
-     * Protobuf type {@code org.opendaylight.controller.mdsal.ReadyTransactionReply}
-     */
-    public static final class Builder extends
-        com.google.protobuf.GeneratedMessage.Builder<Builder>
-       implements org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReplyOrBuilder {
-      public static final com.google.protobuf.Descriptors.Descriptor
-          getDescriptor() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadyTransactionReply_descriptor;
-      }
-
-      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
-          internalGetFieldAccessorTable() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadyTransactionReply_fieldAccessorTable
-            .ensureFieldAccessorsInitialized(
-                org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply.Builder.class);
-      }
-
-      // Construct using org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply.newBuilder()
-      private Builder() {
-        maybeForceBuilderInitialization();
-      }
-
-      private Builder(
-          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
-        super(parent);
-        maybeForceBuilderInitialization();
-      }
-      private void maybeForceBuilderInitialization() {
-        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
-        }
-      }
-      private static Builder create() {
-        return new Builder();
-      }
-
-      public Builder clear() {
-        super.clear();
-        actorPath_ = "";
-        bitField0_ = (bitField0_ & ~0x00000001);
-        return this;
-      }
-
-      public Builder clone() {
-        return create().mergeFrom(buildPartial());
-      }
-
-      public com.google.protobuf.Descriptors.Descriptor
-          getDescriptorForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadyTransactionReply_descriptor;
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply getDefaultInstanceForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply.getDefaultInstance();
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply build() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply result = buildPartial();
-        if (!result.isInitialized()) {
-          throw newUninitializedMessageException(result);
-        }
-        return result;
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply buildPartial() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply result = new org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply(this);
-        int from_bitField0_ = bitField0_;
-        int to_bitField0_ = 0;
-        if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
-          to_bitField0_ |= 0x00000001;
-        }
-        result.actorPath_ = actorPath_;
-        result.bitField0_ = to_bitField0_;
-        onBuilt();
-        return result;
-      }
-
-      public Builder mergeFrom(com.google.protobuf.Message other) {
-        if (other instanceof org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply) {
-          return mergeFrom((org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply)other);
-        } else {
-          super.mergeFrom(other);
-          return this;
-        }
-      }
-
-      public Builder mergeFrom(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply other) {
-        if (other == org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply.getDefaultInstance()) return this;
-        if (other.hasActorPath()) {
-          bitField0_ |= 0x00000001;
-          actorPath_ = other.actorPath_;
-          onChanged();
-        }
-        this.mergeUnknownFields(other.getUnknownFields());
-        return this;
-      }
-
-      public final boolean isInitialized() {
-        if (!hasActorPath()) {
-
-          return false;
-        }
-        return true;
-      }
-
-      public Builder mergeFrom(
-          com.google.protobuf.CodedInputStream input,
-          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-          throws java.io.IOException {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply parsedMessage = null;
-        try {
-          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
-        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-          parsedMessage = (org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadyTransactionReply) e.getUnfinishedMessage();
-          throw e;
-        } finally {
-          if (parsedMessage != null) {
-            mergeFrom(parsedMessage);
-          }
-        }
-        return this;
-      }
-      private int bitField0_;
-
-      // required string actorPath = 1;
-      private java.lang.Object actorPath_ = "";
-      /**
-       * <code>required string actorPath = 1;</code>
-       */
-      public boolean hasActorPath() {
-        return ((bitField0_ & 0x00000001) == 0x00000001);
-      }
-      /**
-       * <code>required string actorPath = 1;</code>
-       */
-      public java.lang.String getActorPath() {
-        java.lang.Object ref = actorPath_;
-        if (!(ref instanceof java.lang.String)) {
-          java.lang.String s = ((com.google.protobuf.ByteString) ref)
-              .toStringUtf8();
-          actorPath_ = s;
-          return s;
-        } else {
-          return (java.lang.String) ref;
-        }
-      }
-      /**
-       * <code>required string actorPath = 1;</code>
-       */
-      public com.google.protobuf.ByteString
-          getActorPathBytes() {
-        java.lang.Object ref = actorPath_;
-        if (ref instanceof String) {
-          com.google.protobuf.ByteString b =
-              com.google.protobuf.ByteString.copyFromUtf8(
-                  (java.lang.String) ref);
-          actorPath_ = b;
-          return b;
-        } else {
-          return (com.google.protobuf.ByteString) ref;
-        }
-      }
-      /**
-       * <code>required string actorPath = 1;</code>
-       */
-      public Builder setActorPath(
-          java.lang.String value) {
-        if (value == null) {
-    throw new NullPointerException();
-  }
-  bitField0_ |= 0x00000001;
-        actorPath_ = value;
-        onChanged();
-        return this;
-      }
-      /**
-       * <code>required string actorPath = 1;</code>
-       */
-      public Builder clearActorPath() {
-        bitField0_ = (bitField0_ & ~0x00000001);
-        actorPath_ = getDefaultInstance().getActorPath();
-        onChanged();
-        return this;
-      }
-      /**
-       * <code>required string actorPath = 1;</code>
-       */
-      public Builder setActorPathBytes(
-          com.google.protobuf.ByteString value) {
-        if (value == null) {
-    throw new NullPointerException();
-  }
-  bitField0_ |= 0x00000001;
-        actorPath_ = value;
-        onChanged();
-        return this;
-      }
-
-      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.ReadyTransactionReply)
-    }
-
-    static {
-      defaultInstance = new ReadyTransactionReply(true);
-      defaultInstance.initFields();
-    }
-
-    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.ReadyTransactionReply)
-  }
-
-  public interface DeleteDataOrBuilder
-      extends com.google.protobuf.MessageOrBuilder {
-
-    // required string instanceIdentifierPath = 1;
-    /**
-     * <code>required string instanceIdentifierPath = 1;</code>
-     */
-    boolean hasInstanceIdentifierPath();
-    /**
-     * <code>required string instanceIdentifierPath = 1;</code>
-     */
-    java.lang.String getInstanceIdentifierPath();
-    /**
-     * <code>required string instanceIdentifierPath = 1;</code>
-     */
-    com.google.protobuf.ByteString
-        getInstanceIdentifierPathBytes();
-  }
-  /**
-   * Protobuf type {@code org.opendaylight.controller.mdsal.DeleteData}
-   */
-  public static final class DeleteData extends
-      com.google.protobuf.GeneratedMessage
-      implements DeleteDataOrBuilder {
-    // Use DeleteData.newBuilder() to construct.
-    private DeleteData(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
-      super(builder);
-      this.unknownFields = builder.getUnknownFields();
-    }
-    private DeleteData(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
-
-    private static final DeleteData defaultInstance;
-    public static DeleteData getDefaultInstance() {
-      return defaultInstance;
-    }
-
-    public DeleteData getDefaultInstanceForType() {
-      return defaultInstance;
-    }
-
-    private final com.google.protobuf.UnknownFieldSet unknownFields;
-    @java.lang.Override
-    public final com.google.protobuf.UnknownFieldSet
-        getUnknownFields() {
-      return this.unknownFields;
-    }
-    private DeleteData(
-        com.google.protobuf.CodedInputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      initFields();
-      int mutable_bitField0_ = 0;
-      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
-          com.google.protobuf.UnknownFieldSet.newBuilder();
-      try {
-        boolean done = false;
-        while (!done) {
-          int tag = input.readTag();
-          switch (tag) {
-            case 0:
-              done = true;
-              break;
-            default: {
-              if (!parseUnknownField(input, unknownFields,
-                                     extensionRegistry, tag)) {
-                done = true;
-              }
-              break;
-            }
-            case 10: {
-              bitField0_ |= 0x00000001;
-              instanceIdentifierPath_ = input.readBytes();
-              break;
-            }
-          }
-        }
-      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-        throw e.setUnfinishedMessage(this);
-      } catch (java.io.IOException e) {
-        throw new com.google.protobuf.InvalidProtocolBufferException(
-            e.getMessage()).setUnfinishedMessage(this);
-      } finally {
-        this.unknownFields = unknownFields.build();
-        makeExtensionsImmutable();
-      }
-    }
-    public static final com.google.protobuf.Descriptors.Descriptor
-        getDescriptor() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_DeleteData_descriptor;
-    }
-
-    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
-        internalGetFieldAccessorTable() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_DeleteData_fieldAccessorTable
-          .ensureFieldAccessorsInitialized(
-              org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData.Builder.class);
-    }
-
-    public static com.google.protobuf.Parser<DeleteData> PARSER =
-        new com.google.protobuf.AbstractParser<DeleteData>() {
-      public DeleteData parsePartialFrom(
-          com.google.protobuf.CodedInputStream input,
-          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-          throws com.google.protobuf.InvalidProtocolBufferException {
-        return new DeleteData(input, extensionRegistry);
-      }
-    };
-
-    @java.lang.Override
-    public com.google.protobuf.Parser<DeleteData> getParserForType() {
-      return PARSER;
-    }
-
-    private int bitField0_;
-    // required string instanceIdentifierPath = 1;
-    public static final int INSTANCEIDENTIFIERPATH_FIELD_NUMBER = 1;
-    private java.lang.Object instanceIdentifierPath_;
-    /**
-     * <code>required string instanceIdentifierPath = 1;</code>
-     */
-    public boolean hasInstanceIdentifierPath() {
-      return ((bitField0_ & 0x00000001) == 0x00000001);
-    }
-    /**
-     * <code>required string instanceIdentifierPath = 1;</code>
-     */
-    public java.lang.String getInstanceIdentifierPath() {
-      java.lang.Object ref = instanceIdentifierPath_;
-      if (ref instanceof java.lang.String) {
-        return (java.lang.String) ref;
-      } else {
-        com.google.protobuf.ByteString bs =
-            (com.google.protobuf.ByteString) ref;
-        java.lang.String s = bs.toStringUtf8();
-        if (bs.isValidUtf8()) {
-          instanceIdentifierPath_ = s;
-        }
-        return s;
-      }
-    }
-    /**
-     * <code>required string instanceIdentifierPath = 1;</code>
-     */
-    public com.google.protobuf.ByteString
-        getInstanceIdentifierPathBytes() {
-      java.lang.Object ref = instanceIdentifierPath_;
-      if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b =
-            com.google.protobuf.ByteString.copyFromUtf8(
-                (java.lang.String) ref);
-        instanceIdentifierPath_ = b;
-        return b;
-      } else {
-        return (com.google.protobuf.ByteString) ref;
-      }
-    }
-
-    private void initFields() {
-      instanceIdentifierPath_ = "";
-    }
-    private byte memoizedIsInitialized = -1;
-    public final boolean isInitialized() {
-      byte isInitialized = memoizedIsInitialized;
-      if (isInitialized != -1) return isInitialized == 1;
-
-      if (!hasInstanceIdentifierPath()) {
-        memoizedIsInitialized = 0;
-        return false;
-      }
-      memoizedIsInitialized = 1;
-      return true;
-    }
-
-    public void writeTo(com.google.protobuf.CodedOutputStream output)
-                        throws java.io.IOException {
-      getSerializedSize();
-      if (((bitField0_ & 0x00000001) == 0x00000001)) {
-        output.writeBytes(1, getInstanceIdentifierPathBytes());
-      }
-      getUnknownFields().writeTo(output);
-    }
-
-    private int memoizedSerializedSize = -1;
-    public int getSerializedSize() {
-      int size = memoizedSerializedSize;
-      if (size != -1) return size;
-
-      size = 0;
-      if (((bitField0_ & 0x00000001) == 0x00000001)) {
-        size += com.google.protobuf.CodedOutputStream
-          .computeBytesSize(1, getInstanceIdentifierPathBytes());
-      }
-      size += getUnknownFields().getSerializedSize();
-      memoizedSerializedSize = size;
-      return size;
-    }
-
-    private static final long serialVersionUID = 0L;
-    @java.lang.Override
-    protected java.lang.Object writeReplace()
-        throws java.io.ObjectStreamException {
-      return super.writeReplace();
-    }
-
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData parseFrom(
-        com.google.protobuf.ByteString data)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData parseFrom(
-        com.google.protobuf.ByteString data,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData parseFrom(byte[] data)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData parseFrom(
-        byte[] data,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData parseFrom(java.io.InputStream input)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData parseFrom(
-        java.io.InputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData parseDelimitedFrom(java.io.InputStream input)
-        throws java.io.IOException {
-      return PARSER.parseDelimitedFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData parseDelimitedFrom(
-        java.io.InputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseDelimitedFrom(input, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData parseFrom(
-        com.google.protobuf.CodedInputStream input)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData parseFrom(
-        com.google.protobuf.CodedInputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input, extensionRegistry);
-    }
-
-    public static Builder newBuilder() { return Builder.create(); }
-    public Builder newBuilderForType() { return newBuilder(); }
-    public static Builder newBuilder(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData prototype) {
-      return newBuilder().mergeFrom(prototype);
-    }
-    public Builder toBuilder() { return newBuilder(this); }
-
-    @java.lang.Override
-    protected Builder newBuilderForType(
-        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
-      Builder builder = new Builder(parent);
-      return builder;
-    }
-    /**
-     * Protobuf type {@code org.opendaylight.controller.mdsal.DeleteData}
-     */
-    public static final class Builder extends
-        com.google.protobuf.GeneratedMessage.Builder<Builder>
-       implements org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataOrBuilder {
-      public static final com.google.protobuf.Descriptors.Descriptor
-          getDescriptor() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_DeleteData_descriptor;
-      }
-
-      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
-          internalGetFieldAccessorTable() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_DeleteData_fieldAccessorTable
-            .ensureFieldAccessorsInitialized(
-                org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData.Builder.class);
-      }
-
-      // Construct using org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData.newBuilder()
-      private Builder() {
-        maybeForceBuilderInitialization();
-      }
-
-      private Builder(
-          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
-        super(parent);
-        maybeForceBuilderInitialization();
-      }
-      private void maybeForceBuilderInitialization() {
-        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
-        }
-      }
-      private static Builder create() {
-        return new Builder();
-      }
-
-      public Builder clear() {
-        super.clear();
-        instanceIdentifierPath_ = "";
-        bitField0_ = (bitField0_ & ~0x00000001);
-        return this;
-      }
-
-      public Builder clone() {
-        return create().mergeFrom(buildPartial());
-      }
-
-      public com.google.protobuf.Descriptors.Descriptor
-          getDescriptorForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_DeleteData_descriptor;
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData getDefaultInstanceForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData.getDefaultInstance();
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData build() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData result = buildPartial();
-        if (!result.isInitialized()) {
-          throw newUninitializedMessageException(result);
-        }
-        return result;
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData buildPartial() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData result = new org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData(this);
-        int from_bitField0_ = bitField0_;
-        int to_bitField0_ = 0;
-        if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
-          to_bitField0_ |= 0x00000001;
-        }
-        result.instanceIdentifierPath_ = instanceIdentifierPath_;
-        result.bitField0_ = to_bitField0_;
-        onBuilt();
-        return result;
-      }
-
-      public Builder mergeFrom(com.google.protobuf.Message other) {
-        if (other instanceof org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData) {
-          return mergeFrom((org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData)other);
-        } else {
-          super.mergeFrom(other);
-          return this;
-        }
-      }
-
-      public Builder mergeFrom(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData other) {
-        if (other == org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData.getDefaultInstance()) return this;
-        if (other.hasInstanceIdentifierPath()) {
-          bitField0_ |= 0x00000001;
-          instanceIdentifierPath_ = other.instanceIdentifierPath_;
-          onChanged();
-        }
-        this.mergeUnknownFields(other.getUnknownFields());
-        return this;
-      }
-
-      public final boolean isInitialized() {
-        if (!hasInstanceIdentifierPath()) {
-
-          return false;
-        }
-        return true;
-      }
-
-      public Builder mergeFrom(
-          com.google.protobuf.CodedInputStream input,
-          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-          throws java.io.IOException {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData parsedMessage = null;
-        try {
-          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
-        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-          parsedMessage = (org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteData) e.getUnfinishedMessage();
-          throw e;
-        } finally {
-          if (parsedMessage != null) {
-            mergeFrom(parsedMessage);
-          }
-        }
-        return this;
-      }
-      private int bitField0_;
-
-      // required string instanceIdentifierPath = 1;
-      private java.lang.Object instanceIdentifierPath_ = "";
-      /**
-       * <code>required string instanceIdentifierPath = 1;</code>
-       */
-      public boolean hasInstanceIdentifierPath() {
-        return ((bitField0_ & 0x00000001) == 0x00000001);
-      }
-      /**
-       * <code>required string instanceIdentifierPath = 1;</code>
-       */
-      public java.lang.String getInstanceIdentifierPath() {
-        java.lang.Object ref = instanceIdentifierPath_;
-        if (!(ref instanceof java.lang.String)) {
-          java.lang.String s = ((com.google.protobuf.ByteString) ref)
-              .toStringUtf8();
-          instanceIdentifierPath_ = s;
-          return s;
-        } else {
-          return (java.lang.String) ref;
-        }
-      }
-      /**
-       * <code>required string instanceIdentifierPath = 1;</code>
-       */
-      public com.google.protobuf.ByteString
-          getInstanceIdentifierPathBytes() {
-        java.lang.Object ref = instanceIdentifierPath_;
-        if (ref instanceof String) {
-          com.google.protobuf.ByteString b =
-              com.google.protobuf.ByteString.copyFromUtf8(
-                  (java.lang.String) ref);
-          instanceIdentifierPath_ = b;
-          return b;
-        } else {
-          return (com.google.protobuf.ByteString) ref;
-        }
-      }
-      /**
-       * <code>required string instanceIdentifierPath = 1;</code>
-       */
-      public Builder setInstanceIdentifierPath(
-          java.lang.String value) {
-        if (value == null) {
-    throw new NullPointerException();
-  }
-  bitField0_ |= 0x00000001;
-        instanceIdentifierPath_ = value;
-        onChanged();
-        return this;
-      }
-      /**
-       * <code>required string instanceIdentifierPath = 1;</code>
-       */
-      public Builder clearInstanceIdentifierPath() {
-        bitField0_ = (bitField0_ & ~0x00000001);
-        instanceIdentifierPath_ = getDefaultInstance().getInstanceIdentifierPath();
-        onChanged();
-        return this;
-      }
-      /**
-       * <code>required string instanceIdentifierPath = 1;</code>
-       */
-      public Builder setInstanceIdentifierPathBytes(
-          com.google.protobuf.ByteString value) {
-        if (value == null) {
-    throw new NullPointerException();
-  }
-  bitField0_ |= 0x00000001;
-        instanceIdentifierPath_ = value;
-        onChanged();
-        return this;
-      }
-
-      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.DeleteData)
-    }
-
-    static {
-      defaultInstance = new DeleteData(true);
-      defaultInstance.initFields();
-    }
-
-    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.DeleteData)
-  }
-
-  public interface DeleteDataReplyOrBuilder
-      extends com.google.protobuf.MessageOrBuilder {
-  }
-  /**
-   * Protobuf type {@code org.opendaylight.controller.mdsal.DeleteDataReply}
-   */
-  public static final class DeleteDataReply extends
-      com.google.protobuf.GeneratedMessage
-      implements DeleteDataReplyOrBuilder {
-    // Use DeleteDataReply.newBuilder() to construct.
-    private DeleteDataReply(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
-      super(builder);
-      this.unknownFields = builder.getUnknownFields();
-    }
-    private DeleteDataReply(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
-
-    private static final DeleteDataReply defaultInstance;
-    public static DeleteDataReply getDefaultInstance() {
-      return defaultInstance;
-    }
-
-    public DeleteDataReply getDefaultInstanceForType() {
-      return defaultInstance;
-    }
-
-    private final com.google.protobuf.UnknownFieldSet unknownFields;
-    @java.lang.Override
-    public final com.google.protobuf.UnknownFieldSet
-        getUnknownFields() {
-      return this.unknownFields;
-    }
-    private DeleteDataReply(
-        com.google.protobuf.CodedInputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      initFields();
-      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
-          com.google.protobuf.UnknownFieldSet.newBuilder();
-      try {
-        boolean done = false;
-        while (!done) {
-          int tag = input.readTag();
-          switch (tag) {
-            case 0:
-              done = true;
-              break;
-            default: {
-              if (!parseUnknownField(input, unknownFields,
-                                     extensionRegistry, tag)) {
-                done = true;
-              }
-              break;
-            }
-          }
-        }
-      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-        throw e.setUnfinishedMessage(this);
-      } catch (java.io.IOException e) {
-        throw new com.google.protobuf.InvalidProtocolBufferException(
-            e.getMessage()).setUnfinishedMessage(this);
-      } finally {
-        this.unknownFields = unknownFields.build();
-        makeExtensionsImmutable();
-      }
-    }
-    public static final com.google.protobuf.Descriptors.Descriptor
-        getDescriptor() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_DeleteDataReply_descriptor;
-    }
-
-    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
-        internalGetFieldAccessorTable() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_DeleteDataReply_fieldAccessorTable
-          .ensureFieldAccessorsInitialized(
-              org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply.Builder.class);
-    }
-
-    public static com.google.protobuf.Parser<DeleteDataReply> PARSER =
-        new com.google.protobuf.AbstractParser<DeleteDataReply>() {
-      public DeleteDataReply parsePartialFrom(
-          com.google.protobuf.CodedInputStream input,
-          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-          throws com.google.protobuf.InvalidProtocolBufferException {
-        return new DeleteDataReply(input, extensionRegistry);
-      }
-    };
-
-    @java.lang.Override
-    public com.google.protobuf.Parser<DeleteDataReply> getParserForType() {
-      return PARSER;
-    }
-
-    private void initFields() {
-    }
-    private byte memoizedIsInitialized = -1;
-    public final boolean isInitialized() {
-      byte isInitialized = memoizedIsInitialized;
-      if (isInitialized != -1) return isInitialized == 1;
-
-      memoizedIsInitialized = 1;
-      return true;
-    }
-
-    public void writeTo(com.google.protobuf.CodedOutputStream output)
-                        throws java.io.IOException {
-      getSerializedSize();
-      getUnknownFields().writeTo(output);
-    }
-
-    private int memoizedSerializedSize = -1;
-    public int getSerializedSize() {
-      int size = memoizedSerializedSize;
-      if (size != -1) return size;
-
-      size = 0;
-      size += getUnknownFields().getSerializedSize();
-      memoizedSerializedSize = size;
-      return size;
-    }
-
-    private static final long serialVersionUID = 0L;
-    @java.lang.Override
-    protected java.lang.Object writeReplace()
-        throws java.io.ObjectStreamException {
-      return super.writeReplace();
-    }
-
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply parseFrom(
-        com.google.protobuf.ByteString data)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply parseFrom(
-        com.google.protobuf.ByteString data,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply parseFrom(byte[] data)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply parseFrom(
-        byte[] data,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply parseFrom(java.io.InputStream input)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply parseFrom(
-        java.io.InputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply parseDelimitedFrom(java.io.InputStream input)
-        throws java.io.IOException {
-      return PARSER.parseDelimitedFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply parseDelimitedFrom(
-        java.io.InputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseDelimitedFrom(input, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply parseFrom(
-        com.google.protobuf.CodedInputStream input)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply parseFrom(
-        com.google.protobuf.CodedInputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input, extensionRegistry);
-    }
-
-    public static Builder newBuilder() { return Builder.create(); }
-    public Builder newBuilderForType() { return newBuilder(); }
-    public static Builder newBuilder(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply prototype) {
-      return newBuilder().mergeFrom(prototype);
-    }
-    public Builder toBuilder() { return newBuilder(this); }
-
-    @java.lang.Override
-    protected Builder newBuilderForType(
-        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
-      Builder builder = new Builder(parent);
-      return builder;
-    }
-    /**
-     * Protobuf type {@code org.opendaylight.controller.mdsal.DeleteDataReply}
-     */
-    public static final class Builder extends
-        com.google.protobuf.GeneratedMessage.Builder<Builder>
-       implements org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReplyOrBuilder {
-      public static final com.google.protobuf.Descriptors.Descriptor
-          getDescriptor() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_DeleteDataReply_descriptor;
-      }
-
-      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
-          internalGetFieldAccessorTable() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_DeleteDataReply_fieldAccessorTable
-            .ensureFieldAccessorsInitialized(
-                org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply.Builder.class);
-      }
-
-      // Construct using org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply.newBuilder()
-      private Builder() {
-        maybeForceBuilderInitialization();
-      }
-
-      private Builder(
-          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
-        super(parent);
-        maybeForceBuilderInitialization();
-      }
-      private void maybeForceBuilderInitialization() {
-        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
-        }
-      }
-      private static Builder create() {
-        return new Builder();
-      }
-
-      public Builder clear() {
-        super.clear();
-        return this;
-      }
-
-      public Builder clone() {
-        return create().mergeFrom(buildPartial());
-      }
-
-      public com.google.protobuf.Descriptors.Descriptor
-          getDescriptorForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_DeleteDataReply_descriptor;
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply getDefaultInstanceForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply.getDefaultInstance();
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply build() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply result = buildPartial();
-        if (!result.isInitialized()) {
-          throw newUninitializedMessageException(result);
-        }
-        return result;
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply buildPartial() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply result = new org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply(this);
-        onBuilt();
-        return result;
-      }
-
-      public Builder mergeFrom(com.google.protobuf.Message other) {
-        if (other instanceof org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply) {
-          return mergeFrom((org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply)other);
-        } else {
-          super.mergeFrom(other);
-          return this;
-        }
-      }
-
-      public Builder mergeFrom(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply other) {
-        if (other == org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply.getDefaultInstance()) return this;
-        this.mergeUnknownFields(other.getUnknownFields());
-        return this;
-      }
-
-      public final boolean isInitialized() {
-        return true;
-      }
-
-      public Builder mergeFrom(
-          com.google.protobuf.CodedInputStream input,
-          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-          throws java.io.IOException {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply parsedMessage = null;
-        try {
-          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
-        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-          parsedMessage = (org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.DeleteDataReply) e.getUnfinishedMessage();
-          throw e;
-        } finally {
-          if (parsedMessage != null) {
-            mergeFrom(parsedMessage);
-          }
-        }
-        return this;
-      }
-
-      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.DeleteDataReply)
-    }
-
-    static {
-      defaultInstance = new DeleteDataReply(true);
-      defaultInstance.initFields();
-    }
-
-    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.DeleteDataReply)
-  }
-
-  public interface ReadDataOrBuilder
-      extends com.google.protobuf.MessageOrBuilder {
-
-    // required string intanceIdentifier = 1;
-    /**
-     * <code>required string intanceIdentifier = 1;</code>
-     */
-    boolean hasIntanceIdentifier();
-    /**
-     * <code>required string intanceIdentifier = 1;</code>
-     */
-    java.lang.String getIntanceIdentifier();
-    /**
-     * <code>required string intanceIdentifier = 1;</code>
-     */
-    com.google.protobuf.ByteString
-        getIntanceIdentifierBytes();
-  }
-  /**
-   * Protobuf type {@code org.opendaylight.controller.mdsal.ReadData}
-   */
-  public static final class ReadData extends
-      com.google.protobuf.GeneratedMessage
-      implements ReadDataOrBuilder {
-    // Use ReadData.newBuilder() to construct.
-    private ReadData(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
-      super(builder);
-      this.unknownFields = builder.getUnknownFields();
-    }
-    private ReadData(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
-
-    private static final ReadData defaultInstance;
-    public static ReadData getDefaultInstance() {
-      return defaultInstance;
-    }
-
-    public ReadData getDefaultInstanceForType() {
-      return defaultInstance;
-    }
-
-    private final com.google.protobuf.UnknownFieldSet unknownFields;
-    @java.lang.Override
-    public final com.google.protobuf.UnknownFieldSet
-        getUnknownFields() {
-      return this.unknownFields;
-    }
-    private ReadData(
-        com.google.protobuf.CodedInputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      initFields();
-      int mutable_bitField0_ = 0;
-      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
-          com.google.protobuf.UnknownFieldSet.newBuilder();
-      try {
-        boolean done = false;
-        while (!done) {
-          int tag = input.readTag();
-          switch (tag) {
-            case 0:
-              done = true;
-              break;
-            default: {
-              if (!parseUnknownField(input, unknownFields,
-                                     extensionRegistry, tag)) {
-                done = true;
-              }
-              break;
-            }
-            case 10: {
-              bitField0_ |= 0x00000001;
-              intanceIdentifier_ = input.readBytes();
-              break;
-            }
-          }
-        }
-      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-        throw e.setUnfinishedMessage(this);
-      } catch (java.io.IOException e) {
-        throw new com.google.protobuf.InvalidProtocolBufferException(
-            e.getMessage()).setUnfinishedMessage(this);
-      } finally {
-        this.unknownFields = unknownFields.build();
-        makeExtensionsImmutable();
-      }
-    }
-    public static final com.google.protobuf.Descriptors.Descriptor
-        getDescriptor() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadData_descriptor;
-    }
-
-    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
-        internalGetFieldAccessorTable() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadData_fieldAccessorTable
-          .ensureFieldAccessorsInitialized(
-              org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData.Builder.class);
-    }
-
-    public static com.google.protobuf.Parser<ReadData> PARSER =
-        new com.google.protobuf.AbstractParser<ReadData>() {
-      public ReadData parsePartialFrom(
-          com.google.protobuf.CodedInputStream input,
-          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-          throws com.google.protobuf.InvalidProtocolBufferException {
-        return new ReadData(input, extensionRegistry);
-      }
-    };
-
-    @java.lang.Override
-    public com.google.protobuf.Parser<ReadData> getParserForType() {
-      return PARSER;
-    }
-
-    private int bitField0_;
-    // required string intanceIdentifier = 1;
-    public static final int INTANCEIDENTIFIER_FIELD_NUMBER = 1;
-    private java.lang.Object intanceIdentifier_;
-    /**
-     * <code>required string intanceIdentifier = 1;</code>
-     */
-    public boolean hasIntanceIdentifier() {
-      return ((bitField0_ & 0x00000001) == 0x00000001);
-    }
-    /**
-     * <code>required string intanceIdentifier = 1;</code>
-     */
-    public java.lang.String getIntanceIdentifier() {
-      java.lang.Object ref = intanceIdentifier_;
-      if (ref instanceof java.lang.String) {
-        return (java.lang.String) ref;
-      } else {
-        com.google.protobuf.ByteString bs =
-            (com.google.protobuf.ByteString) ref;
-        java.lang.String s = bs.toStringUtf8();
-        if (bs.isValidUtf8()) {
-          intanceIdentifier_ = s;
-        }
-        return s;
-      }
-    }
-    /**
-     * <code>required string intanceIdentifier = 1;</code>
-     */
-    public com.google.protobuf.ByteString
-        getIntanceIdentifierBytes() {
-      java.lang.Object ref = intanceIdentifier_;
-      if (ref instanceof java.lang.String) {
-        com.google.protobuf.ByteString b =
-            com.google.protobuf.ByteString.copyFromUtf8(
-                (java.lang.String) ref);
-        intanceIdentifier_ = b;
-        return b;
-      } else {
-        return (com.google.protobuf.ByteString) ref;
-      }
-    }
-
-    private void initFields() {
-      intanceIdentifier_ = "";
-    }
-    private byte memoizedIsInitialized = -1;
-    public final boolean isInitialized() {
-      byte isInitialized = memoizedIsInitialized;
-      if (isInitialized != -1) return isInitialized == 1;
-
-      if (!hasIntanceIdentifier()) {
-        memoizedIsInitialized = 0;
-        return false;
-      }
-      memoizedIsInitialized = 1;
-      return true;
-    }
-
-    public void writeTo(com.google.protobuf.CodedOutputStream output)
-                        throws java.io.IOException {
-      getSerializedSize();
-      if (((bitField0_ & 0x00000001) == 0x00000001)) {
-        output.writeBytes(1, getIntanceIdentifierBytes());
-      }
-      getUnknownFields().writeTo(output);
-    }
-
-    private int memoizedSerializedSize = -1;
-    public int getSerializedSize() {
-      int size = memoizedSerializedSize;
-      if (size != -1) return size;
-
-      size = 0;
-      if (((bitField0_ & 0x00000001) == 0x00000001)) {
-        size += com.google.protobuf.CodedOutputStream
-          .computeBytesSize(1, getIntanceIdentifierBytes());
-      }
-      size += getUnknownFields().getSerializedSize();
-      memoizedSerializedSize = size;
-      return size;
-    }
-
-    private static final long serialVersionUID = 0L;
-    @java.lang.Override
-    protected java.lang.Object writeReplace()
-        throws java.io.ObjectStreamException {
-      return super.writeReplace();
-    }
-
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData parseFrom(
-        com.google.protobuf.ByteString data)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData parseFrom(
-        com.google.protobuf.ByteString data,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData parseFrom(byte[] data)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData parseFrom(
-        byte[] data,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws com.google.protobuf.InvalidProtocolBufferException {
-      return PARSER.parseFrom(data, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData parseFrom(java.io.InputStream input)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData parseFrom(
-        java.io.InputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData parseDelimitedFrom(java.io.InputStream input)
-        throws java.io.IOException {
-      return PARSER.parseDelimitedFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData parseDelimitedFrom(
-        java.io.InputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseDelimitedFrom(input, extensionRegistry);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData parseFrom(
-        com.google.protobuf.CodedInputStream input)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input);
-    }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData parseFrom(
-        com.google.protobuf.CodedInputStream input,
-        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-        throws java.io.IOException {
-      return PARSER.parseFrom(input, extensionRegistry);
-    }
-
-    public static Builder newBuilder() { return Builder.create(); }
-    public Builder newBuilderForType() { return newBuilder(); }
-    public static Builder newBuilder(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData prototype) {
-      return newBuilder().mergeFrom(prototype);
-    }
-    public Builder toBuilder() { return newBuilder(this); }
-
-    @java.lang.Override
-    protected Builder newBuilderForType(
-        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
-      Builder builder = new Builder(parent);
-      return builder;
-    }
-    /**
-     * Protobuf type {@code org.opendaylight.controller.mdsal.ReadData}
-     */
-    public static final class Builder extends
-        com.google.protobuf.GeneratedMessage.Builder<Builder>
-       implements org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadDataOrBuilder {
-      public static final com.google.protobuf.Descriptors.Descriptor
-          getDescriptor() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadData_descriptor;
-      }
-
-      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
-          internalGetFieldAccessorTable() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadData_fieldAccessorTable
-            .ensureFieldAccessorsInitialized(
-                org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData.Builder.class);
-      }
-
-      // Construct using org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData.newBuilder()
-      private Builder() {
-        maybeForceBuilderInitialization();
-      }
-
-      private Builder(
-          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
-        super(parent);
-        maybeForceBuilderInitialization();
-      }
-      private void maybeForceBuilderInitialization() {
-        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
-        }
-      }
-      private static Builder create() {
-        return new Builder();
-      }
-
-      public Builder clear() {
-        super.clear();
-        intanceIdentifier_ = "";
-        bitField0_ = (bitField0_ & ~0x00000001);
-        return this;
-      }
-
-      public Builder clone() {
-        return create().mergeFrom(buildPartial());
-      }
-
-      public com.google.protobuf.Descriptors.Descriptor
-          getDescriptorForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadData_descriptor;
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData getDefaultInstanceForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData.getDefaultInstance();
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData build() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData result = buildPartial();
-        if (!result.isInitialized()) {
-          throw newUninitializedMessageException(result);
-        }
-        return result;
-      }
-
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData buildPartial() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData result = new org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData(this);
-        int from_bitField0_ = bitField0_;
-        int to_bitField0_ = 0;
-        if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
-          to_bitField0_ |= 0x00000001;
-        }
-        result.intanceIdentifier_ = intanceIdentifier_;
-        result.bitField0_ = to_bitField0_;
-        onBuilt();
-        return result;
-      }
-
-      public Builder mergeFrom(com.google.protobuf.Message other) {
-        if (other instanceof org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData) {
-          return mergeFrom((org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData)other);
-        } else {
-          super.mergeFrom(other);
-          return this;
-        }
-      }
-
-      public Builder mergeFrom(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData other) {
-        if (other == org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData.getDefaultInstance()) return this;
-        if (other.hasIntanceIdentifier()) {
-          bitField0_ |= 0x00000001;
-          intanceIdentifier_ = other.intanceIdentifier_;
-          onChanged();
-        }
-        this.mergeUnknownFields(other.getUnknownFields());
-        return this;
-      }
-
-      public final boolean isInitialized() {
-        if (!hasIntanceIdentifier()) {
-          return false;
-        }
-        return true;
-      }
-
-      public Builder mergeFrom(
-          com.google.protobuf.CodedInputStream input,
-          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
-          throws java.io.IOException {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData parsedMessage = null;
-        try {
-          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
-        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-          parsedMessage = (org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionMessages.ReadData) e.getUnfinishedMessage();
-          throw e;
-        } finally {
-          if (parsedMessage != null) {
-            mergeFrom(parsedMessage);
-          }
-        }
-        return this;
-      }
-      private int bitField0_;
-
-      // required string intanceIdentifier = 1;
-      private java.lang.Object intanceIdentifier_ = "";
-      /**
-       * <code>required string intanceIdentifier = 1;</code>
-       */
-      public boolean hasIntanceIdentifier() {
-        return ((bitField0_ & 0x00000001) == 0x00000001);
-      }
-      /**
-       * <code>required string intanceIdentifier = 1;</code>
-       */
-      public java.lang.String getIntanceIdentifier() {
-        java.lang.Object ref = intanceIdentifier_;
-        if (!(ref instanceof java.lang.String)) {
-          java.lang.String s = ((com.google.protobuf.ByteString) ref)
-              .toStringUtf8();
-          intanceIdentifier_ = s;
-          return s;
-        } else {
-          return (java.lang.String) ref;
-        }
-      }
-      /**
-       * <code>required string intanceIdentifier = 1;</code>
-       */
-      public com.google.protobuf.ByteString
-          getIntanceIdentifierBytes() {
-        java.lang.Object ref = intanceIdentifier_;
-        if (ref instanceof String) {
-          com.google.protobuf.ByteString b =
-              com.google.protobuf.ByteString.copyFromUtf8(
-                  (java.lang.String) ref);
-          intanceIdentifier_ = b;
-          return b;
-        } else {
-          return (com.google.protobuf.ByteString) ref;
-        }
-      }
-      /**
-       * <code>required string intanceIdentifier = 1;</code>
-       */
-      public Builder setIntanceIdentifier(
-          java.lang.String value) {
-        if (value == null) {
-    throw new NullPointerException();
-  }
-  bitField0_ |= 0x00000001;
-        intanceIdentifier_ = value;
-        onChanged();
-        return this;
-      }
-      /**
-       * <code>required string intanceIdentifier = 1;</code>
-       */
-      public Builder clearIntanceIdentifier() {
-        bitField0_ = (bitField0_ & ~0x00000001);
-        intanceIdentifier_ = getDefaultInstance().getIntanceIdentifier();
-        onChanged();
-        return this;
-      }
-      /**
-       * <code>required string intanceIdentifier = 1;</code>
-       */
-      public Builder setIntanceIdentifierBytes(
-          com.google.protobuf.ByteString value) {
-        if (value == null) {
-    throw new NullPointerException();
-  }
-  bitField0_ |= 0x00000001;
-        intanceIdentifier_ = value;
-        onChanged();
-        return this;
-      }
-
-      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.ReadData)
-    }
-
-    static {
-      defaultInstance = new ReadData(true);
-      defaultInstance.initFields();
-    }
-
-    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.ReadData)
-  }
-
-  private static com.google.protobuf.Descriptors.Descriptor
-    internal_static_org_opendaylight_controller_mdsal_CloseTransaction_descriptor;
-  private static
-    com.google.protobuf.GeneratedMessage.FieldAccessorTable
-      internal_static_org_opendaylight_controller_mdsal_CloseTransaction_fieldAccessorTable;
-  private static com.google.protobuf.Descriptors.Descriptor
-    internal_static_org_opendaylight_controller_mdsal_CloseTransactionReply_descriptor;
-  private static
-    com.google.protobuf.GeneratedMessage.FieldAccessorTable
-      internal_static_org_opendaylight_controller_mdsal_CloseTransactionReply_fieldAccessorTable;
-  private static com.google.protobuf.Descriptors.Descriptor
-    internal_static_org_opendaylight_controller_mdsal_CreateTransaction_descriptor;
-  private static
-    com.google.protobuf.GeneratedMessage.FieldAccessorTable
-      internal_static_org_opendaylight_controller_mdsal_CreateTransaction_fieldAccessorTable;
-  private static com.google.protobuf.Descriptors.Descriptor
-    internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_descriptor;
-  private static
-    com.google.protobuf.GeneratedMessage.FieldAccessorTable
-      internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_fieldAccessorTable;
-  private static com.google.protobuf.Descriptors.Descriptor
-    internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_descriptor;
-  private static
-    com.google.protobuf.GeneratedMessage.FieldAccessorTable
-      internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_fieldAccessorTable;
-  private static com.google.protobuf.Descriptors.Descriptor
-    internal_static_org_opendaylight_controller_mdsal_ReadyTransactionReply_descriptor;
-  private static
-    com.google.protobuf.GeneratedMessage.FieldAccessorTable
-      internal_static_org_opendaylight_controller_mdsal_ReadyTransactionReply_fieldAccessorTable;
-  private static com.google.protobuf.Descriptors.Descriptor
-    internal_static_org_opendaylight_controller_mdsal_DeleteData_descriptor;
-  private static
-    com.google.protobuf.GeneratedMessage.FieldAccessorTable
-      internal_static_org_opendaylight_controller_mdsal_DeleteData_fieldAccessorTable;
-  private static com.google.protobuf.Descriptors.Descriptor
-    internal_static_org_opendaylight_controller_mdsal_DeleteDataReply_descriptor;
-  private static
-    com.google.protobuf.GeneratedMessage.FieldAccessorTable
-      internal_static_org_opendaylight_controller_mdsal_DeleteDataReply_fieldAccessorTable;
-  private static com.google.protobuf.Descriptors.Descriptor
-    internal_static_org_opendaylight_controller_mdsal_ReadData_descriptor;
-  private static
-    com.google.protobuf.GeneratedMessage.FieldAccessorTable
-      internal_static_org_opendaylight_controller_mdsal_ReadData_fieldAccessorTable;
-
-  public static com.google.protobuf.Descriptors.FileDescriptor
-      getDescriptor() {
-    return descriptor;
-  }
-  private static com.google.protobuf.Descriptors.FileDescriptor
-      descriptor;
-  static {
-    java.lang.String[] descriptorData = {
-      "\n\036ShardTransactionMessages.proto\022!org.op" +
-      "endaylight.controller.mdsal\"\022\n\020CloseTran" +
-      "saction\"\027\n\025CloseTransactionReply\"\023\n\021Crea" +
-      "teTransaction\"1\n\026CreateTransactionReply\022" +
-      "\027\n\017transactionPath\030\001 \002(\t\"\022\n\020ReadyTransac" +
-      "tion\"*\n\025ReadyTransactionReply\022\021\n\tactorPa" +
-      "th\030\001 \002(\t\",\n\nDeleteData\022\036\n\026instanceIdenti" +
-      "fierPath\030\001 \002(\t\"\021\n\017DeleteDataReply\"%\n\010Rea" +
-      "dData\022\031\n\021intanceIdentifier\030\001 \002(\tBU\n9org." +
-      "opendaylight.controller.cluster.datastor",
-      "e.transactionB\030ShardTransactionMessages"
-    };
-    com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
-      new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
-        public com.google.protobuf.ExtensionRegistry assignDescriptors(
-            com.google.protobuf.Descriptors.FileDescriptor root) {
-          descriptor = root;
-          internal_static_org_opendaylight_controller_mdsal_CloseTransaction_descriptor =
-            getDescriptor().getMessageTypes().get(0);
-          internal_static_org_opendaylight_controller_mdsal_CloseTransaction_fieldAccessorTable = new
-            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
-              internal_static_org_opendaylight_controller_mdsal_CloseTransaction_descriptor,
-              new java.lang.String[] { });
-          internal_static_org_opendaylight_controller_mdsal_CloseTransactionReply_descriptor =
-            getDescriptor().getMessageTypes().get(1);
-          internal_static_org_opendaylight_controller_mdsal_CloseTransactionReply_fieldAccessorTable = new
-            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
-              internal_static_org_opendaylight_controller_mdsal_CloseTransactionReply_descriptor,
-              new java.lang.String[] { });
-          internal_static_org_opendaylight_controller_mdsal_CreateTransaction_descriptor =
-            getDescriptor().getMessageTypes().get(2);
-          internal_static_org_opendaylight_controller_mdsal_CreateTransaction_fieldAccessorTable = new
-            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
-              internal_static_org_opendaylight_controller_mdsal_CreateTransaction_descriptor,
-              new java.lang.String[] { });
-          internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_descriptor =
-            getDescriptor().getMessageTypes().get(3);
-          internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_fieldAccessorTable = new
-            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
-              internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_descriptor,
-              new java.lang.String[] { "TransactionPath", });
-          internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_descriptor =
-            getDescriptor().getMessageTypes().get(4);
-          internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_fieldAccessorTable = new
-            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
-              internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_descriptor,
-              new java.lang.String[] { });
-          internal_static_org_opendaylight_controller_mdsal_ReadyTransactionReply_descriptor =
-            getDescriptor().getMessageTypes().get(5);
-          internal_static_org_opendaylight_controller_mdsal_ReadyTransactionReply_fieldAccessorTable = new
-            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
-              internal_static_org_opendaylight_controller_mdsal_ReadyTransactionReply_descriptor,
-              new java.lang.String[] { "ActorPath", });
-          internal_static_org_opendaylight_controller_mdsal_DeleteData_descriptor =
-            getDescriptor().getMessageTypes().get(6);
-          internal_static_org_opendaylight_controller_mdsal_DeleteData_fieldAccessorTable = new
-            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
-              internal_static_org_opendaylight_controller_mdsal_DeleteData_descriptor,
-              new java.lang.String[] { "InstanceIdentifierPath", });
-          internal_static_org_opendaylight_controller_mdsal_DeleteDataReply_descriptor =
-            getDescriptor().getMessageTypes().get(7);
-          internal_static_org_opendaylight_controller_mdsal_DeleteDataReply_fieldAccessorTable = new
-            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
-              internal_static_org_opendaylight_controller_mdsal_DeleteDataReply_descriptor,
-              new java.lang.String[] { });
-          internal_static_org_opendaylight_controller_mdsal_ReadData_descriptor =
-            getDescriptor().getMessageTypes().get(8);
-          internal_static_org_opendaylight_controller_mdsal_ReadData_fieldAccessorTable = new
-            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
-              internal_static_org_opendaylight_controller_mdsal_ReadData_descriptor,
-              new java.lang.String[] { "IntanceIdentifier", });
-          return null;
-        }
-      };
-    com.google.protobuf.Descriptors.FileDescriptor
-      .internalBuildGeneratedFileFrom(descriptorData,
-        new com.google.protobuf.Descriptors.FileDescriptor[] {
-        }, assigner);
-  }
-
-  // @@protoc_insertion_point(outer_class_scope)
-}
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/util/EncoderDecoderUtil.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/cluster/datastore/util/EncoderDecoderUtil.java
new file mode 100644 (file)
index 0000000..41eb2e6
--- /dev/null
@@ -0,0 +1,190 @@
+package org.opendaylight.controller.cluster.datastore.util;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.serializer.DomFromNormalizedNodeSerializerFactory;
+import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.TransformerFactoryConfigurationError;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import java.io.ByteArrayInputStream;
+import java.io.StringWriter;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+
+/*
+ * 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
+ * protobuf message containing the XML representation of the NormalizeNode
+ *
+ * @author: syedbahm
+ */
+public class EncoderDecoderUtil {
+  static DocumentBuilderFactory factory;
+  static {
+    factory = DocumentBuilderFactory.newInstance();
+    factory.setNamespaceAware(true);
+    factory.setCoalescing(true);
+    factory.setIgnoringElementContentWhitespace(true);
+    factory.setIgnoringComments(true);
+  }
+
+  private static DataSchemaNode findChildNode(Set<DataSchemaNode> children,
+      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;
+  }
+
+  private static DataSchemaNode getSchemaNode(SchemaContext context, QName qname) {
+
+    for (Module module : context.findModuleByNamespace(qname.getNamespace())) {
+      // we will take the first child as the start of the
+      if (module.getChildNodes() != null || !module.getChildNodes().isEmpty()) {
+
+        DataSchemaNode found =
+            findChildNode(module.getChildNodes(), qname.getLocalName());
+        return found;
+      }
+    }
+    return null;
+  }
+
+  private static String toString(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);
+    }
+  }
+
+  /**
+   * Helps in generation of NormalizedNodeXml message for the supplied NormalizedNode
+   *
+   * @param sc --SchemaContext
+   * @param normalizedNode -- Normalized Node to be encoded
+   * @return SimpleNormalizedNodeMessage.NormalizedNodeXml
+   */
+  public static SimpleNormalizedNodeMessage.NormalizedNodeXml encode(
+      SchemaContext sc, NormalizedNode<?, ?> normalizedNode) {
+    Preconditions.checkArgument(sc != null, "Schema context found null");
+    Preconditions.checkArgument(normalizedNode != null,
+        "normalized node found null");
+    ContainerSchemaNode containerNode =
+        (ContainerSchemaNode) getSchemaNode(sc, normalizedNode.getIdentifier()
+            .getNodeType());
+    Preconditions.checkState(containerNode != null,
+        "Couldn't find schema node for " + normalizedNode.getIdentifier());
+    Iterable<Element> els =
+        DomFromNormalizedNodeSerializerFactory
+            .getInstance(XmlDocumentUtils.getDocument(),
+                DomUtils.defaultValueCodecProvider())
+            .getContainerNodeSerializer()
+            .serialize(containerNode, (ContainerNode) normalizedNode);
+    String xmlString = toString(els.iterator().next());
+    SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder builder =
+        SimpleNormalizedNodeMessage.NormalizedNodeXml.newBuilder();
+    builder.setXmlString(xmlString);
+    builder.setNodeIdentifier(((ContainerNode) normalizedNode).getIdentifier()
+        .getNodeType().toString());
+    return builder.build();
+
+  }
+
+  /**
+   * Utilizes the SimpleNormalizedNodeMessage.NormalizedNodeXml to convert into NormalizedNode
+   *
+   * @param sc -- schema context
+   * @param normalizedNodeXml -- containing the normalized Node XML
+   * @return NormalizedNode return
+   * @throws Exception
+   */
+
+  public static NormalizedNode decode(SchemaContext sc,
+      SimpleNormalizedNodeMessage.NormalizedNodeXml normalizedNodeXml)
+      throws Exception {
+    Preconditions.checkArgument(sc != null, "schema context seems to be null");
+    Preconditions.checkArgument(normalizedNodeXml != null,
+        "SimpleNormalizedNodeMessage.NormalizedNodeXml found to be null");
+    QName qname = QName.create(normalizedNodeXml.getNodeIdentifier());
+
+    // here we will try to get back the NormalizedNode
+    ContainerSchemaNode containerSchemaNode =
+        (ContainerSchemaNode) getSchemaNode(sc, qname);
+
+    // now we need to read the XML
+
+    Document doc =
+        factory.newDocumentBuilder().parse(
+            new ByteArrayInputStream(normalizedNodeXml.getXmlString().getBytes(
+                "utf-8")));
+    doc.getDocumentElement().normalize();
+
+    ContainerNode result =
+        DomToNormalizedNodeParserFactory
+            .getInstance(DomUtils.defaultValueCodecProvider())
+            .getContainerNodeParser()
+            .parse(Collections.singletonList(doc.getDocumentElement()),
+                containerSchemaNode);
+
+    return (NormalizedNode) result;
+
+  }
+
+
+
+}
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/common/SimpleNormalizedNodeMessage.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/common/SimpleNormalizedNodeMessage.java
new file mode 100644 (file)
index 0000000..67ab472
--- /dev/null
@@ -0,0 +1,696 @@
+// Generated by the protocol buffer compiler.  DO NOT EDIT!
+// source: SimpleNormalizedNode.proto
+
+package org.opendaylight.controller.protobuff.messages.common;
+
+public final class SimpleNormalizedNodeMessage {
+  private SimpleNormalizedNodeMessage() {}
+  public static void registerAllExtensions(
+      com.google.protobuf.ExtensionRegistry registry) {
+  }
+  public interface NormalizedNodeXmlOrBuilder
+      extends com.google.protobuf.MessageOrBuilder {
+
+    // required string nodeIdentifier = 1;
+    /**
+     * <code>required string nodeIdentifier = 1;</code>
+     */
+    boolean hasNodeIdentifier();
+    /**
+     * <code>required string nodeIdentifier = 1;</code>
+     */
+    java.lang.String getNodeIdentifier();
+    /**
+     * <code>required string nodeIdentifier = 1;</code>
+     */
+    com.google.protobuf.ByteString
+        getNodeIdentifierBytes();
+
+    // required string xmlString = 2;
+    /**
+     * <code>required string xmlString = 2;</code>
+     */
+    boolean hasXmlString();
+    /**
+     * <code>required string xmlString = 2;</code>
+     */
+    java.lang.String getXmlString();
+    /**
+     * <code>required string xmlString = 2;</code>
+     */
+    com.google.protobuf.ByteString
+        getXmlStringBytes();
+  }
+  /**
+   * Protobuf type {@code org.opendaylight.controller.mdsal.NormalizedNodeXml}
+   */
+  public static final class NormalizedNodeXml extends
+      com.google.protobuf.GeneratedMessage
+      implements NormalizedNodeXmlOrBuilder {
+    // Use NormalizedNodeXml.newBuilder() to construct.
+    private NormalizedNodeXml(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
+      super(builder);
+      this.unknownFields = builder.getUnknownFields();
+    }
+    private NormalizedNodeXml(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+    private static final NormalizedNodeXml defaultInstance;
+    public static NormalizedNodeXml getDefaultInstance() {
+      return defaultInstance;
+    }
+
+    public NormalizedNodeXml getDefaultInstanceForType() {
+      return defaultInstance;
+    }
+
+    private final com.google.protobuf.UnknownFieldSet unknownFields;
+    @java.lang.Override
+    public final com.google.protobuf.UnknownFieldSet
+        getUnknownFields() {
+      return this.unknownFields;
+    }
+    private NormalizedNodeXml(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      initFields();
+      int mutable_bitField0_ = 0;
+      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+          com.google.protobuf.UnknownFieldSet.newBuilder();
+      try {
+        boolean done = false;
+        while (!done) {
+          int tag = input.readTag();
+          switch (tag) {
+            case 0:
+              done = true;
+              break;
+            default: {
+              if (!parseUnknownField(input, unknownFields,
+                                     extensionRegistry, tag)) {
+                done = true;
+              }
+              break;
+            }
+            case 10: {
+              bitField0_ |= 0x00000001;
+              nodeIdentifier_ = input.readBytes();
+              break;
+            }
+            case 18: {
+              bitField0_ |= 0x00000002;
+              xmlString_ = input.readBytes();
+              break;
+            }
+          }
+        }
+      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+        throw e.setUnfinishedMessage(this);
+      } catch (java.io.IOException e) {
+        throw new com.google.protobuf.InvalidProtocolBufferException(
+            e.getMessage()).setUnfinishedMessage(this);
+      } finally {
+        this.unknownFields = unknownFields.build();
+        makeExtensionsImmutable();
+      }
+    }
+    public static final com.google.protobuf.Descriptors.Descriptor
+        getDescriptor() {
+      return org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.internal_static_org_opendaylight_controller_mdsal_NormalizedNodeXml_descriptor;
+    }
+
+    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+        internalGetFieldAccessorTable() {
+      return org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.internal_static_org_opendaylight_controller_mdsal_NormalizedNodeXml_fieldAccessorTable
+          .ensureFieldAccessorsInitialized(
+              org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.class, org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder.class);
+    }
+
+    public static com.google.protobuf.Parser<NormalizedNodeXml> PARSER =
+        new com.google.protobuf.AbstractParser<NormalizedNodeXml>() {
+      public NormalizedNodeXml parsePartialFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws com.google.protobuf.InvalidProtocolBufferException {
+        return new NormalizedNodeXml(input, extensionRegistry);
+      }
+    };
+
+    @java.lang.Override
+    public com.google.protobuf.Parser<NormalizedNodeXml> getParserForType() {
+      return PARSER;
+    }
+
+    private int bitField0_;
+    // required string nodeIdentifier = 1;
+    public static final int NODEIDENTIFIER_FIELD_NUMBER = 1;
+    private java.lang.Object nodeIdentifier_;
+    /**
+     * <code>required string nodeIdentifier = 1;</code>
+     */
+    public boolean hasNodeIdentifier() {
+      return ((bitField0_ & 0x00000001) == 0x00000001);
+    }
+    /**
+     * <code>required string nodeIdentifier = 1;</code>
+     */
+    public java.lang.String getNodeIdentifier() {
+      java.lang.Object ref = nodeIdentifier_;
+      if (ref instanceof java.lang.String) {
+        return (java.lang.String) ref;
+      } else {
+        com.google.protobuf.ByteString bs =
+            (com.google.protobuf.ByteString) ref;
+        java.lang.String s = bs.toStringUtf8();
+        if (bs.isValidUtf8()) {
+          nodeIdentifier_ = s;
+        }
+        return s;
+      }
+    }
+    /**
+     * <code>required string nodeIdentifier = 1;</code>
+     */
+    public com.google.protobuf.ByteString
+        getNodeIdentifierBytes() {
+      java.lang.Object ref = nodeIdentifier_;
+      if (ref instanceof java.lang.String) {
+        com.google.protobuf.ByteString b =
+            com.google.protobuf.ByteString.copyFromUtf8(
+                (java.lang.String) ref);
+        nodeIdentifier_ = b;
+        return b;
+      } else {
+        return (com.google.protobuf.ByteString) ref;
+      }
+    }
+
+    // required string xmlString = 2;
+    public static final int XMLSTRING_FIELD_NUMBER = 2;
+    private java.lang.Object xmlString_;
+    /**
+     * <code>required string xmlString = 2;</code>
+     */
+    public boolean hasXmlString() {
+      return ((bitField0_ & 0x00000002) == 0x00000002);
+    }
+    /**
+     * <code>required string xmlString = 2;</code>
+     */
+    public java.lang.String getXmlString() {
+      java.lang.Object ref = xmlString_;
+      if (ref instanceof java.lang.String) {
+        return (java.lang.String) ref;
+      } else {
+        com.google.protobuf.ByteString bs =
+            (com.google.protobuf.ByteString) ref;
+        java.lang.String s = bs.toStringUtf8();
+        if (bs.isValidUtf8()) {
+          xmlString_ = s;
+        }
+        return s;
+      }
+    }
+    /**
+     * <code>required string xmlString = 2;</code>
+     */
+    public com.google.protobuf.ByteString
+        getXmlStringBytes() {
+      java.lang.Object ref = xmlString_;
+      if (ref instanceof java.lang.String) {
+        com.google.protobuf.ByteString b =
+            com.google.protobuf.ByteString.copyFromUtf8(
+                (java.lang.String) ref);
+        xmlString_ = b;
+        return b;
+      } else {
+        return (com.google.protobuf.ByteString) ref;
+      }
+    }
+
+    private void initFields() {
+      nodeIdentifier_ = "";
+      xmlString_ = "";
+    }
+    private byte memoizedIsInitialized = -1;
+    public final boolean isInitialized() {
+      byte isInitialized = memoizedIsInitialized;
+      if (isInitialized != -1) return isInitialized == 1;
+
+      if (!hasNodeIdentifier()) {
+        memoizedIsInitialized = 0;
+        return false;
+      }
+      if (!hasXmlString()) {
+        memoizedIsInitialized = 0;
+        return false;
+      }
+      memoizedIsInitialized = 1;
+      return true;
+    }
+
+    public void writeTo(com.google.protobuf.CodedOutputStream output)
+                        throws java.io.IOException {
+      getSerializedSize();
+      if (((bitField0_ & 0x00000001) == 0x00000001)) {
+        output.writeBytes(1, getNodeIdentifierBytes());
+      }
+      if (((bitField0_ & 0x00000002) == 0x00000002)) {
+        output.writeBytes(2, getXmlStringBytes());
+      }
+      getUnknownFields().writeTo(output);
+    }
+
+    private int memoizedSerializedSize = -1;
+    public int getSerializedSize() {
+      int size = memoizedSerializedSize;
+      if (size != -1) return size;
+
+      size = 0;
+      if (((bitField0_ & 0x00000001) == 0x00000001)) {
+        size += com.google.protobuf.CodedOutputStream
+          .computeBytesSize(1, getNodeIdentifierBytes());
+      }
+      if (((bitField0_ & 0x00000002) == 0x00000002)) {
+        size += com.google.protobuf.CodedOutputStream
+          .computeBytesSize(2, getXmlStringBytes());
+      }
+      size += getUnknownFields().getSerializedSize();
+      memoizedSerializedSize = size;
+      return size;
+    }
+
+    private static final long serialVersionUID = 0L;
+    @java.lang.Override
+    protected java.lang.Object writeReplace()
+        throws java.io.ObjectStreamException {
+      return super.writeReplace();
+    }
+
+    public static org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml parseFrom(
+        com.google.protobuf.ByteString data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml parseFrom(
+        com.google.protobuf.ByteString data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml parseFrom(byte[] data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml parseFrom(
+        byte[] data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml parseFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml parseFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml parseDelimitedFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml parseDelimitedFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml parseFrom(
+        com.google.protobuf.CodedInputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml parseFrom(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+
+    public static Builder newBuilder() { return Builder.create(); }
+    public Builder newBuilderForType() { return newBuilder(); }
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml prototype) {
+      return newBuilder().mergeFrom(prototype);
+    }
+    public Builder toBuilder() { return newBuilder(this); }
+
+    @java.lang.Override
+    protected Builder newBuilderForType(
+        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+      Builder builder = new Builder(parent);
+      return builder;
+    }
+    /**
+     * Protobuf type {@code org.opendaylight.controller.mdsal.NormalizedNodeXml}
+     */
+    public static final class Builder extends
+        com.google.protobuf.GeneratedMessage.Builder<Builder>
+       implements org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXmlOrBuilder {
+      public static final com.google.protobuf.Descriptors.Descriptor
+          getDescriptor() {
+        return org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.internal_static_org_opendaylight_controller_mdsal_NormalizedNodeXml_descriptor;
+      }
+
+      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+          internalGetFieldAccessorTable() {
+        return org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.internal_static_org_opendaylight_controller_mdsal_NormalizedNodeXml_fieldAccessorTable
+            .ensureFieldAccessorsInitialized(
+                org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.class, org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder.class);
+      }
+
+      // Construct using org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.newBuilder()
+      private Builder() {
+        maybeForceBuilderInitialization();
+      }
+
+      private Builder(
+          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+        super(parent);
+        maybeForceBuilderInitialization();
+      }
+      private void maybeForceBuilderInitialization() {
+        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+        }
+      }
+      private static Builder create() {
+        return new Builder();
+      }
+
+      public Builder clear() {
+        super.clear();
+        nodeIdentifier_ = "";
+        bitField0_ = (bitField0_ & ~0x00000001);
+        xmlString_ = "";
+        bitField0_ = (bitField0_ & ~0x00000002);
+        return this;
+      }
+
+      public Builder clone() {
+        return create().mergeFrom(buildPartial());
+      }
+
+      public com.google.protobuf.Descriptors.Descriptor
+          getDescriptorForType() {
+        return org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.internal_static_org_opendaylight_controller_mdsal_NormalizedNodeXml_descriptor;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.getDefaultInstance();
+      }
+
+      public org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml build() {
+        org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml result = buildPartial();
+        if (!result.isInitialized()) {
+          throw newUninitializedMessageException(result);
+        }
+        return result;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml buildPartial() {
+        org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml result = new org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml(this);
+        int from_bitField0_ = bitField0_;
+        int to_bitField0_ = 0;
+        if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
+          to_bitField0_ |= 0x00000001;
+        }
+        result.nodeIdentifier_ = nodeIdentifier_;
+        if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
+          to_bitField0_ |= 0x00000002;
+        }
+        result.xmlString_ = xmlString_;
+        result.bitField0_ = to_bitField0_;
+        onBuilt();
+        return result;
+      }
+
+      public Builder mergeFrom(com.google.protobuf.Message other) {
+        if (other instanceof org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml)other);
+        } else {
+          super.mergeFrom(other);
+          return this;
+        }
+      }
+
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml other) {
+        if (other == org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.getDefaultInstance()) return this;
+        if (other.hasNodeIdentifier()) {
+          bitField0_ |= 0x00000001;
+          nodeIdentifier_ = other.nodeIdentifier_;
+          onChanged();
+        }
+        if (other.hasXmlString()) {
+          bitField0_ |= 0x00000002;
+          xmlString_ = other.xmlString_;
+          onChanged();
+        }
+        this.mergeUnknownFields(other.getUnknownFields());
+        return this;
+      }
+
+      public final boolean isInitialized() {
+        if (!hasNodeIdentifier()) {
+
+          return false;
+        }
+        if (!hasXmlString()) {
+
+          return false;
+        }
+        return true;
+      }
+
+      public Builder mergeFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws java.io.IOException {
+        org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml parsedMessage = null;
+        try {
+          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml) e.getUnfinishedMessage();
+          throw e;
+        } finally {
+          if (parsedMessage != null) {
+            mergeFrom(parsedMessage);
+          }
+        }
+        return this;
+      }
+      private int bitField0_;
+
+      // required string nodeIdentifier = 1;
+      private java.lang.Object nodeIdentifier_ = "";
+      /**
+       * <code>required string nodeIdentifier = 1;</code>
+       */
+      public boolean hasNodeIdentifier() {
+        return ((bitField0_ & 0x00000001) == 0x00000001);
+      }
+      /**
+       * <code>required string nodeIdentifier = 1;</code>
+       */
+      public java.lang.String getNodeIdentifier() {
+        java.lang.Object ref = nodeIdentifier_;
+        if (!(ref instanceof java.lang.String)) {
+          java.lang.String s = ((com.google.protobuf.ByteString) ref)
+              .toStringUtf8();
+          nodeIdentifier_ = s;
+          return s;
+        } else {
+          return (java.lang.String) ref;
+        }
+      }
+      /**
+       * <code>required string nodeIdentifier = 1;</code>
+       */
+      public com.google.protobuf.ByteString
+          getNodeIdentifierBytes() {
+        java.lang.Object ref = nodeIdentifier_;
+        if (ref instanceof String) {
+          com.google.protobuf.ByteString b =
+              com.google.protobuf.ByteString.copyFromUtf8(
+                  (java.lang.String) ref);
+          nodeIdentifier_ = b;
+          return b;
+        } else {
+          return (com.google.protobuf.ByteString) ref;
+        }
+      }
+      /**
+       * <code>required string nodeIdentifier = 1;</code>
+       */
+      public Builder setNodeIdentifier(
+          java.lang.String value) {
+        if (value == null) {
+    throw new NullPointerException();
+  }
+  bitField0_ |= 0x00000001;
+        nodeIdentifier_ = value;
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>required string nodeIdentifier = 1;</code>
+       */
+      public Builder clearNodeIdentifier() {
+        bitField0_ = (bitField0_ & ~0x00000001);
+        nodeIdentifier_ = getDefaultInstance().getNodeIdentifier();
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>required string nodeIdentifier = 1;</code>
+       */
+      public Builder setNodeIdentifierBytes(
+          com.google.protobuf.ByteString value) {
+        if (value == null) {
+    throw new NullPointerException();
+  }
+  bitField0_ |= 0x00000001;
+        nodeIdentifier_ = value;
+        onChanged();
+        return this;
+      }
+
+      // required string xmlString = 2;
+      private java.lang.Object xmlString_ = "";
+      /**
+       * <code>required string xmlString = 2;</code>
+       */
+      public boolean hasXmlString() {
+        return ((bitField0_ & 0x00000002) == 0x00000002);
+      }
+      /**
+       * <code>required string xmlString = 2;</code>
+       */
+      public java.lang.String getXmlString() {
+        java.lang.Object ref = xmlString_;
+        if (!(ref instanceof java.lang.String)) {
+          java.lang.String s = ((com.google.protobuf.ByteString) ref)
+              .toStringUtf8();
+          xmlString_ = s;
+          return s;
+        } else {
+          return (java.lang.String) ref;
+        }
+      }
+      /**
+       * <code>required string xmlString = 2;</code>
+       */
+      public com.google.protobuf.ByteString
+          getXmlStringBytes() {
+        java.lang.Object ref = xmlString_;
+        if (ref instanceof String) {
+          com.google.protobuf.ByteString b =
+              com.google.protobuf.ByteString.copyFromUtf8(
+                  (java.lang.String) ref);
+          xmlString_ = b;
+          return b;
+        } else {
+          return (com.google.protobuf.ByteString) ref;
+        }
+      }
+      /**
+       * <code>required string xmlString = 2;</code>
+       */
+      public Builder setXmlString(
+          java.lang.String value) {
+        if (value == null) {
+    throw new NullPointerException();
+  }
+  bitField0_ |= 0x00000002;
+        xmlString_ = value;
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>required string xmlString = 2;</code>
+       */
+      public Builder clearXmlString() {
+        bitField0_ = (bitField0_ & ~0x00000002);
+        xmlString_ = getDefaultInstance().getXmlString();
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>required string xmlString = 2;</code>
+       */
+      public Builder setXmlStringBytes(
+          com.google.protobuf.ByteString value) {
+        if (value == null) {
+    throw new NullPointerException();
+  }
+  bitField0_ |= 0x00000002;
+        xmlString_ = value;
+        onChanged();
+        return this;
+      }
+
+      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.NormalizedNodeXml)
+    }
+
+    static {
+      defaultInstance = new NormalizedNodeXml(true);
+      defaultInstance.initFields();
+    }
+
+    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.NormalizedNodeXml)
+  }
+
+  private static com.google.protobuf.Descriptors.Descriptor
+    internal_static_org_opendaylight_controller_mdsal_NormalizedNodeXml_descriptor;
+  private static
+    com.google.protobuf.GeneratedMessage.FieldAccessorTable
+      internal_static_org_opendaylight_controller_mdsal_NormalizedNodeXml_fieldAccessorTable;
+
+  public static com.google.protobuf.Descriptors.FileDescriptor
+      getDescriptor() {
+    return descriptor;
+  }
+  private static com.google.protobuf.Descriptors.FileDescriptor
+      descriptor;
+  static {
+    java.lang.String[] descriptorData = {
+      "\n\032SimpleNormalizedNode.proto\022!org.openda" +
+      "ylight.controller.mdsal\">\n\021NormalizedNod" +
+      "eXml\022\026\n\016nodeIdentifier\030\001 \002(\t\022\021\n\txmlStrin" +
+      "g\030\002 \002(\tBT\n5org.opendaylight.controller.p" +
+      "rotobuff.messages.commonB\033SimpleNormaliz" +
+      "edNodeMessage"
+    };
+    com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
+      new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
+        public com.google.protobuf.ExtensionRegistry assignDescriptors(
+            com.google.protobuf.Descriptors.FileDescriptor root) {
+          descriptor = root;
+          internal_static_org_opendaylight_controller_mdsal_NormalizedNodeXml_descriptor =
+            getDescriptor().getMessageTypes().get(0);
+          internal_static_org_opendaylight_controller_mdsal_NormalizedNodeXml_fieldAccessorTable = new
+            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+              internal_static_org_opendaylight_controller_mdsal_NormalizedNodeXml_descriptor,
+              new java.lang.String[] { "NodeIdentifier", "XmlString", });
+          return null;
+        }
+      };
+    com.google.protobuf.Descriptors.FileDescriptor
+      .internalBuildGeneratedFileFrom(descriptorData,
+        new com.google.protobuf.Descriptors.FileDescriptor[] {
+        }, assigner);
+  }
+
+  // @@protoc_insertion_point(outer_class_scope)
+}
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/datachange/notification/DataChangeListenerMessages.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/datachange/notification/DataChangeListenerMessages.java
new file mode 100644 (file)
index 0000000..391107e
--- /dev/null
@@ -0,0 +1,1085 @@
+// Generated by the protocol buffer compiler.  DO NOT EDIT!
+// source: DataChangeListener.proto
+
+package org.opendaylight.controller.protobuff.messages.datachange.notification;
+
+public final class DataChangeListenerMessages {
+  private DataChangeListenerMessages() {}
+  public static void registerAllExtensions(
+      com.google.protobuf.ExtensionRegistry registry) {
+  }
+  public interface DataChangedOrBuilder
+      extends com.google.protobuf.MessageOrBuilder {
+
+    // repeated string instanceIdentifierPathArguments = 1;
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    java.util.List<java.lang.String>
+    getInstanceIdentifierPathArgumentsList();
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    int getInstanceIdentifierPathArgumentsCount();
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    java.lang.String getInstanceIdentifierPathArguments(int index);
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    com.google.protobuf.ByteString
+        getInstanceIdentifierPathArgumentsBytes(int index);
+
+    // required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNodeXml = 2;
+    /**
+     * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNodeXml = 2;</code>
+     */
+    boolean hasNormalizedNodeXml();
+    /**
+     * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNodeXml = 2;</code>
+     */
+    org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml getNormalizedNodeXml();
+    /**
+     * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNodeXml = 2;</code>
+     */
+    org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXmlOrBuilder getNormalizedNodeXmlOrBuilder();
+  }
+  /**
+   * Protobuf type {@code org.opendaylight.controller.mdsal.DataChanged}
+   */
+  public static final class DataChanged extends
+      com.google.protobuf.GeneratedMessage
+      implements DataChangedOrBuilder {
+    // Use DataChanged.newBuilder() to construct.
+    private DataChanged(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
+      super(builder);
+      this.unknownFields = builder.getUnknownFields();
+    }
+    private DataChanged(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+    private static final DataChanged defaultInstance;
+    public static DataChanged getDefaultInstance() {
+      return defaultInstance;
+    }
+
+    public DataChanged getDefaultInstanceForType() {
+      return defaultInstance;
+    }
+
+    private final com.google.protobuf.UnknownFieldSet unknownFields;
+    @java.lang.Override
+    public final com.google.protobuf.UnknownFieldSet
+        getUnknownFields() {
+      return this.unknownFields;
+    }
+    private DataChanged(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      initFields();
+      int mutable_bitField0_ = 0;
+      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+          com.google.protobuf.UnknownFieldSet.newBuilder();
+      try {
+        boolean done = false;
+        while (!done) {
+          int tag = input.readTag();
+          switch (tag) {
+            case 0:
+              done = true;
+              break;
+            default: {
+              if (!parseUnknownField(input, unknownFields,
+                                     extensionRegistry, tag)) {
+                done = true;
+              }
+              break;
+            }
+            case 10: {
+              if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
+                instanceIdentifierPathArguments_ = new com.google.protobuf.LazyStringArrayList();
+                mutable_bitField0_ |= 0x00000001;
+              }
+              instanceIdentifierPathArguments_.add(input.readBytes());
+              break;
+            }
+            case 18: {
+              org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder subBuilder = null;
+              if (((bitField0_ & 0x00000001) == 0x00000001)) {
+                subBuilder = normalizedNodeXml_.toBuilder();
+              }
+              normalizedNodeXml_ = input.readMessage(org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.PARSER, extensionRegistry);
+              if (subBuilder != null) {
+                subBuilder.mergeFrom(normalizedNodeXml_);
+                normalizedNodeXml_ = subBuilder.buildPartial();
+              }
+              bitField0_ |= 0x00000001;
+              break;
+            }
+          }
+        }
+      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+        throw e.setUnfinishedMessage(this);
+      } catch (java.io.IOException e) {
+        throw new com.google.protobuf.InvalidProtocolBufferException(
+            e.getMessage()).setUnfinishedMessage(this);
+      } finally {
+        if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
+          instanceIdentifierPathArguments_ = new com.google.protobuf.UnmodifiableLazyStringList(instanceIdentifierPathArguments_);
+        }
+        this.unknownFields = unknownFields.build();
+        makeExtensionsImmutable();
+      }
+    }
+    public static final com.google.protobuf.Descriptors.Descriptor
+        getDescriptor() {
+      return org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.internal_static_org_opendaylight_controller_mdsal_DataChanged_descriptor;
+    }
+
+    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+        internalGetFieldAccessorTable() {
+      return org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.internal_static_org_opendaylight_controller_mdsal_DataChanged_fieldAccessorTable
+          .ensureFieldAccessorsInitialized(
+              org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged.class, org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged.Builder.class);
+    }
+
+    public static com.google.protobuf.Parser<DataChanged> PARSER =
+        new com.google.protobuf.AbstractParser<DataChanged>() {
+      public DataChanged parsePartialFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws com.google.protobuf.InvalidProtocolBufferException {
+        return new DataChanged(input, extensionRegistry);
+      }
+    };
+
+    @java.lang.Override
+    public com.google.protobuf.Parser<DataChanged> getParserForType() {
+      return PARSER;
+    }
+
+    private int bitField0_;
+    // repeated string instanceIdentifierPathArguments = 1;
+    public static final int INSTANCEIDENTIFIERPATHARGUMENTS_FIELD_NUMBER = 1;
+    private com.google.protobuf.LazyStringList instanceIdentifierPathArguments_;
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    public java.util.List<java.lang.String>
+        getInstanceIdentifierPathArgumentsList() {
+      return instanceIdentifierPathArguments_;
+    }
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    public int getInstanceIdentifierPathArgumentsCount() {
+      return instanceIdentifierPathArguments_.size();
+    }
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    public java.lang.String getInstanceIdentifierPathArguments(int index) {
+      return instanceIdentifierPathArguments_.get(index);
+    }
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    public com.google.protobuf.ByteString
+        getInstanceIdentifierPathArgumentsBytes(int index) {
+      return instanceIdentifierPathArguments_.getByteString(index);
+    }
+
+    // required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNodeXml = 2;
+    public static final int NORMALIZEDNODEXML_FIELD_NUMBER = 2;
+    private org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml normalizedNodeXml_;
+    /**
+     * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNodeXml = 2;</code>
+     */
+    public boolean hasNormalizedNodeXml() {
+      return ((bitField0_ & 0x00000001) == 0x00000001);
+    }
+    /**
+     * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNodeXml = 2;</code>
+     */
+    public org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml getNormalizedNodeXml() {
+      return normalizedNodeXml_;
+    }
+    /**
+     * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNodeXml = 2;</code>
+     */
+    public org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXmlOrBuilder getNormalizedNodeXmlOrBuilder() {
+      return normalizedNodeXml_;
+    }
+
+    private void initFields() {
+      instanceIdentifierPathArguments_ = com.google.protobuf.LazyStringArrayList.EMPTY;
+      normalizedNodeXml_ = org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.getDefaultInstance();
+    }
+    private byte memoizedIsInitialized = -1;
+    public final boolean isInitialized() {
+      byte isInitialized = memoizedIsInitialized;
+      if (isInitialized != -1) return isInitialized == 1;
+
+      if (!hasNormalizedNodeXml()) {
+        memoizedIsInitialized = 0;
+        return false;
+      }
+      if (!getNormalizedNodeXml().isInitialized()) {
+        memoizedIsInitialized = 0;
+        return false;
+      }
+      memoizedIsInitialized = 1;
+      return true;
+    }
+
+    public void writeTo(com.google.protobuf.CodedOutputStream output)
+                        throws java.io.IOException {
+      getSerializedSize();
+      for (int i = 0; i < instanceIdentifierPathArguments_.size(); i++) {
+        output.writeBytes(1, instanceIdentifierPathArguments_.getByteString(i));
+      }
+      if (((bitField0_ & 0x00000001) == 0x00000001)) {
+        output.writeMessage(2, normalizedNodeXml_);
+      }
+      getUnknownFields().writeTo(output);
+    }
+
+    private int memoizedSerializedSize = -1;
+    public int getSerializedSize() {
+      int size = memoizedSerializedSize;
+      if (size != -1) return size;
+
+      size = 0;
+      {
+        int dataSize = 0;
+        for (int i = 0; i < instanceIdentifierPathArguments_.size(); i++) {
+          dataSize += com.google.protobuf.CodedOutputStream
+            .computeBytesSizeNoTag(instanceIdentifierPathArguments_.getByteString(i));
+        }
+        size += dataSize;
+        size += 1 * getInstanceIdentifierPathArgumentsList().size();
+      }
+      if (((bitField0_ & 0x00000001) == 0x00000001)) {
+        size += com.google.protobuf.CodedOutputStream
+          .computeMessageSize(2, normalizedNodeXml_);
+      }
+      size += getUnknownFields().getSerializedSize();
+      memoizedSerializedSize = size;
+      return size;
+    }
+
+    private static final long serialVersionUID = 0L;
+    @java.lang.Override
+    protected java.lang.Object writeReplace()
+        throws java.io.ObjectStreamException {
+      return super.writeReplace();
+    }
+
+    public static org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged parseFrom(
+        com.google.protobuf.ByteString data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged parseFrom(
+        com.google.protobuf.ByteString data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged parseFrom(byte[] data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged parseFrom(
+        byte[] data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged parseFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged parseFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged parseDelimitedFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged parseDelimitedFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged parseFrom(
+        com.google.protobuf.CodedInputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged parseFrom(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+
+    public static Builder newBuilder() { return Builder.create(); }
+    public Builder newBuilderForType() { return newBuilder(); }
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged prototype) {
+      return newBuilder().mergeFrom(prototype);
+    }
+    public Builder toBuilder() { return newBuilder(this); }
+
+    @java.lang.Override
+    protected Builder newBuilderForType(
+        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+      Builder builder = new Builder(parent);
+      return builder;
+    }
+    /**
+     * Protobuf type {@code org.opendaylight.controller.mdsal.DataChanged}
+     */
+    public static final class Builder extends
+        com.google.protobuf.GeneratedMessage.Builder<Builder>
+       implements org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedOrBuilder {
+      public static final com.google.protobuf.Descriptors.Descriptor
+          getDescriptor() {
+        return org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.internal_static_org_opendaylight_controller_mdsal_DataChanged_descriptor;
+      }
+
+      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+          internalGetFieldAccessorTable() {
+        return org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.internal_static_org_opendaylight_controller_mdsal_DataChanged_fieldAccessorTable
+            .ensureFieldAccessorsInitialized(
+                org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged.class, org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged.Builder.class);
+      }
+
+      // Construct using org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged.newBuilder()
+      private Builder() {
+        maybeForceBuilderInitialization();
+      }
+
+      private Builder(
+          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+        super(parent);
+        maybeForceBuilderInitialization();
+      }
+      private void maybeForceBuilderInitialization() {
+        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+          getNormalizedNodeXmlFieldBuilder();
+        }
+      }
+      private static Builder create() {
+        return new Builder();
+      }
+
+      public Builder clear() {
+        super.clear();
+        instanceIdentifierPathArguments_ = com.google.protobuf.LazyStringArrayList.EMPTY;
+        bitField0_ = (bitField0_ & ~0x00000001);
+        if (normalizedNodeXmlBuilder_ == null) {
+          normalizedNodeXml_ = org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.getDefaultInstance();
+        } else {
+          normalizedNodeXmlBuilder_.clear();
+        }
+        bitField0_ = (bitField0_ & ~0x00000002);
+        return this;
+      }
+
+      public Builder clone() {
+        return create().mergeFrom(buildPartial());
+      }
+
+      public com.google.protobuf.Descriptors.Descriptor
+          getDescriptorForType() {
+        return org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.internal_static_org_opendaylight_controller_mdsal_DataChanged_descriptor;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged.getDefaultInstance();
+      }
+
+      public org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged build() {
+        org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged result = buildPartial();
+        if (!result.isInitialized()) {
+          throw newUninitializedMessageException(result);
+        }
+        return result;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged buildPartial() {
+        org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged result = new org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged(this);
+        int from_bitField0_ = bitField0_;
+        int to_bitField0_ = 0;
+        if (((bitField0_ & 0x00000001) == 0x00000001)) {
+          instanceIdentifierPathArguments_ = new com.google.protobuf.UnmodifiableLazyStringList(
+              instanceIdentifierPathArguments_);
+          bitField0_ = (bitField0_ & ~0x00000001);
+        }
+        result.instanceIdentifierPathArguments_ = instanceIdentifierPathArguments_;
+        if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
+          to_bitField0_ |= 0x00000001;
+        }
+        if (normalizedNodeXmlBuilder_ == null) {
+          result.normalizedNodeXml_ = normalizedNodeXml_;
+        } else {
+          result.normalizedNodeXml_ = normalizedNodeXmlBuilder_.build();
+        }
+        result.bitField0_ = to_bitField0_;
+        onBuilt();
+        return result;
+      }
+
+      public Builder mergeFrom(com.google.protobuf.Message other) {
+        if (other instanceof org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged)other);
+        } else {
+          super.mergeFrom(other);
+          return this;
+        }
+      }
+
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged other) {
+        if (other == org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged.getDefaultInstance()) return this;
+        if (!other.instanceIdentifierPathArguments_.isEmpty()) {
+          if (instanceIdentifierPathArguments_.isEmpty()) {
+            instanceIdentifierPathArguments_ = other.instanceIdentifierPathArguments_;
+            bitField0_ = (bitField0_ & ~0x00000001);
+          } else {
+            ensureInstanceIdentifierPathArgumentsIsMutable();
+            instanceIdentifierPathArguments_.addAll(other.instanceIdentifierPathArguments_);
+          }
+          onChanged();
+        }
+        if (other.hasNormalizedNodeXml()) {
+          mergeNormalizedNodeXml(other.getNormalizedNodeXml());
+        }
+        this.mergeUnknownFields(other.getUnknownFields());
+        return this;
+      }
+
+      public final boolean isInitialized() {
+        if (!hasNormalizedNodeXml()) {
+
+          return false;
+        }
+        if (!getNormalizedNodeXml().isInitialized()) {
+
+          return false;
+        }
+        return true;
+      }
+
+      public Builder mergeFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws java.io.IOException {
+        org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged parsedMessage = null;
+        try {
+          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChanged) e.getUnfinishedMessage();
+          throw e;
+        } finally {
+          if (parsedMessage != null) {
+            mergeFrom(parsedMessage);
+          }
+        }
+        return this;
+      }
+      private int bitField0_;
+
+      // repeated string instanceIdentifierPathArguments = 1;
+      private com.google.protobuf.LazyStringList instanceIdentifierPathArguments_ = com.google.protobuf.LazyStringArrayList.EMPTY;
+      private void ensureInstanceIdentifierPathArgumentsIsMutable() {
+        if (!((bitField0_ & 0x00000001) == 0x00000001)) {
+          instanceIdentifierPathArguments_ = new com.google.protobuf.LazyStringArrayList(instanceIdentifierPathArguments_);
+          bitField0_ |= 0x00000001;
+         }
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public java.util.List<java.lang.String>
+          getInstanceIdentifierPathArgumentsList() {
+        return java.util.Collections.unmodifiableList(instanceIdentifierPathArguments_);
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public int getInstanceIdentifierPathArgumentsCount() {
+        return instanceIdentifierPathArguments_.size();
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public java.lang.String getInstanceIdentifierPathArguments(int index) {
+        return instanceIdentifierPathArguments_.get(index);
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public com.google.protobuf.ByteString
+          getInstanceIdentifierPathArgumentsBytes(int index) {
+        return instanceIdentifierPathArguments_.getByteString(index);
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public Builder setInstanceIdentifierPathArguments(
+          int index, java.lang.String value) {
+        if (value == null) {
+    throw new NullPointerException();
+  }
+  ensureInstanceIdentifierPathArgumentsIsMutable();
+        instanceIdentifierPathArguments_.set(index, value);
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public Builder addInstanceIdentifierPathArguments(
+          java.lang.String value) {
+        if (value == null) {
+    throw new NullPointerException();
+  }
+  ensureInstanceIdentifierPathArgumentsIsMutable();
+        instanceIdentifierPathArguments_.add(value);
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public Builder addAllInstanceIdentifierPathArguments(
+          java.lang.Iterable<java.lang.String> values) {
+        ensureInstanceIdentifierPathArgumentsIsMutable();
+        super.addAll(values, instanceIdentifierPathArguments_);
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public Builder clearInstanceIdentifierPathArguments() {
+        instanceIdentifierPathArguments_ = com.google.protobuf.LazyStringArrayList.EMPTY;
+        bitField0_ = (bitField0_ & ~0x00000001);
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public Builder addInstanceIdentifierPathArgumentsBytes(
+          com.google.protobuf.ByteString value) {
+        if (value == null) {
+    throw new NullPointerException();
+  }
+  ensureInstanceIdentifierPathArgumentsIsMutable();
+        instanceIdentifierPathArguments_.add(value);
+        onChanged();
+        return this;
+      }
+
+      // required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNodeXml = 2;
+      private org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml normalizedNodeXml_ = org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.getDefaultInstance();
+      private com.google.protobuf.SingleFieldBuilder<
+          org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml, org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder, org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXmlOrBuilder> normalizedNodeXmlBuilder_;
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNodeXml = 2;</code>
+       */
+      public boolean hasNormalizedNodeXml() {
+        return ((bitField0_ & 0x00000002) == 0x00000002);
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNodeXml = 2;</code>
+       */
+      public org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml getNormalizedNodeXml() {
+        if (normalizedNodeXmlBuilder_ == null) {
+          return normalizedNodeXml_;
+        } else {
+          return normalizedNodeXmlBuilder_.getMessage();
+        }
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNodeXml = 2;</code>
+       */
+      public Builder setNormalizedNodeXml(org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml value) {
+        if (normalizedNodeXmlBuilder_ == null) {
+          if (value == null) {
+            throw new NullPointerException();
+          }
+          normalizedNodeXml_ = value;
+          onChanged();
+        } else {
+          normalizedNodeXmlBuilder_.setMessage(value);
+        }
+        bitField0_ |= 0x00000002;
+        return this;
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNodeXml = 2;</code>
+       */
+      public Builder setNormalizedNodeXml(
+          org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder builderForValue) {
+        if (normalizedNodeXmlBuilder_ == null) {
+          normalizedNodeXml_ = builderForValue.build();
+          onChanged();
+        } else {
+          normalizedNodeXmlBuilder_.setMessage(builderForValue.build());
+        }
+        bitField0_ |= 0x00000002;
+        return this;
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNodeXml = 2;</code>
+       */
+      public Builder mergeNormalizedNodeXml(org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml value) {
+        if (normalizedNodeXmlBuilder_ == null) {
+          if (((bitField0_ & 0x00000002) == 0x00000002) &&
+              normalizedNodeXml_ != org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.getDefaultInstance()) {
+            normalizedNodeXml_ =
+              org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.newBuilder(normalizedNodeXml_).mergeFrom(value).buildPartial();
+          } else {
+            normalizedNodeXml_ = value;
+          }
+          onChanged();
+        } else {
+          normalizedNodeXmlBuilder_.mergeFrom(value);
+        }
+        bitField0_ |= 0x00000002;
+        return this;
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNodeXml = 2;</code>
+       */
+      public Builder clearNormalizedNodeXml() {
+        if (normalizedNodeXmlBuilder_ == null) {
+          normalizedNodeXml_ = org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.getDefaultInstance();
+          onChanged();
+        } else {
+          normalizedNodeXmlBuilder_.clear();
+        }
+        bitField0_ = (bitField0_ & ~0x00000002);
+        return this;
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNodeXml = 2;</code>
+       */
+      public org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder getNormalizedNodeXmlBuilder() {
+        bitField0_ |= 0x00000002;
+        onChanged();
+        return getNormalizedNodeXmlFieldBuilder().getBuilder();
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNodeXml = 2;</code>
+       */
+      public org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXmlOrBuilder getNormalizedNodeXmlOrBuilder() {
+        if (normalizedNodeXmlBuilder_ != null) {
+          return normalizedNodeXmlBuilder_.getMessageOrBuilder();
+        } else {
+          return normalizedNodeXml_;
+        }
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNodeXml = 2;</code>
+       */
+      private com.google.protobuf.SingleFieldBuilder<
+          org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml, org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder, org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXmlOrBuilder>
+          getNormalizedNodeXmlFieldBuilder() {
+        if (normalizedNodeXmlBuilder_ == null) {
+          normalizedNodeXmlBuilder_ = new com.google.protobuf.SingleFieldBuilder<
+              org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml, org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder, org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXmlOrBuilder>(
+                  normalizedNodeXml_,
+                  getParentForChildren(),
+                  isClean());
+          normalizedNodeXml_ = null;
+        }
+        return normalizedNodeXmlBuilder_;
+      }
+
+      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.DataChanged)
+    }
+
+    static {
+      defaultInstance = new DataChanged(true);
+      defaultInstance.initFields();
+    }
+
+    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.DataChanged)
+  }
+
+  public interface DataChangedReplyOrBuilder
+      extends com.google.protobuf.MessageOrBuilder {
+  }
+  /**
+   * Protobuf type {@code org.opendaylight.controller.mdsal.DataChangedReply}
+   */
+  public static final class DataChangedReply extends
+      com.google.protobuf.GeneratedMessage
+      implements DataChangedReplyOrBuilder {
+    // Use DataChangedReply.newBuilder() to construct.
+    private DataChangedReply(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
+      super(builder);
+      this.unknownFields = builder.getUnknownFields();
+    }
+    private DataChangedReply(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+    private static final DataChangedReply defaultInstance;
+    public static DataChangedReply getDefaultInstance() {
+      return defaultInstance;
+    }
+
+    public DataChangedReply getDefaultInstanceForType() {
+      return defaultInstance;
+    }
+
+    private final com.google.protobuf.UnknownFieldSet unknownFields;
+    @java.lang.Override
+    public final com.google.protobuf.UnknownFieldSet
+        getUnknownFields() {
+      return this.unknownFields;
+    }
+    private DataChangedReply(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      initFields();
+      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+          com.google.protobuf.UnknownFieldSet.newBuilder();
+      try {
+        boolean done = false;
+        while (!done) {
+          int tag = input.readTag();
+          switch (tag) {
+            case 0:
+              done = true;
+              break;
+            default: {
+              if (!parseUnknownField(input, unknownFields,
+                                     extensionRegistry, tag)) {
+                done = true;
+              }
+              break;
+            }
+          }
+        }
+      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+        throw e.setUnfinishedMessage(this);
+      } catch (java.io.IOException e) {
+        throw new com.google.protobuf.InvalidProtocolBufferException(
+            e.getMessage()).setUnfinishedMessage(this);
+      } finally {
+        this.unknownFields = unknownFields.build();
+        makeExtensionsImmutable();
+      }
+    }
+    public static final com.google.protobuf.Descriptors.Descriptor
+        getDescriptor() {
+      return org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.internal_static_org_opendaylight_controller_mdsal_DataChangedReply_descriptor;
+    }
+
+    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+        internalGetFieldAccessorTable() {
+      return org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.internal_static_org_opendaylight_controller_mdsal_DataChangedReply_fieldAccessorTable
+          .ensureFieldAccessorsInitialized(
+              org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply.class, org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply.Builder.class);
+    }
+
+    public static com.google.protobuf.Parser<DataChangedReply> PARSER =
+        new com.google.protobuf.AbstractParser<DataChangedReply>() {
+      public DataChangedReply parsePartialFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws com.google.protobuf.InvalidProtocolBufferException {
+        return new DataChangedReply(input, extensionRegistry);
+      }
+    };
+
+    @java.lang.Override
+    public com.google.protobuf.Parser<DataChangedReply> getParserForType() {
+      return PARSER;
+    }
+
+    private void initFields() {
+    }
+    private byte memoizedIsInitialized = -1;
+    public final boolean isInitialized() {
+      byte isInitialized = memoizedIsInitialized;
+      if (isInitialized != -1) return isInitialized == 1;
+
+      memoizedIsInitialized = 1;
+      return true;
+    }
+
+    public void writeTo(com.google.protobuf.CodedOutputStream output)
+                        throws java.io.IOException {
+      getSerializedSize();
+      getUnknownFields().writeTo(output);
+    }
+
+    private int memoizedSerializedSize = -1;
+    public int getSerializedSize() {
+      int size = memoizedSerializedSize;
+      if (size != -1) return size;
+
+      size = 0;
+      size += getUnknownFields().getSerializedSize();
+      memoizedSerializedSize = size;
+      return size;
+    }
+
+    private static final long serialVersionUID = 0L;
+    @java.lang.Override
+    protected java.lang.Object writeReplace()
+        throws java.io.ObjectStreamException {
+      return super.writeReplace();
+    }
+
+    public static org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply parseFrom(
+        com.google.protobuf.ByteString data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply parseFrom(
+        com.google.protobuf.ByteString data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply parseFrom(byte[] data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply parseFrom(
+        byte[] data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply parseFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply parseFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply parseDelimitedFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply parseDelimitedFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply parseFrom(
+        com.google.protobuf.CodedInputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply parseFrom(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+
+    public static Builder newBuilder() { return Builder.create(); }
+    public Builder newBuilderForType() { return newBuilder(); }
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply prototype) {
+      return newBuilder().mergeFrom(prototype);
+    }
+    public Builder toBuilder() { return newBuilder(this); }
+
+    @java.lang.Override
+    protected Builder newBuilderForType(
+        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+      Builder builder = new Builder(parent);
+      return builder;
+    }
+    /**
+     * Protobuf type {@code org.opendaylight.controller.mdsal.DataChangedReply}
+     */
+    public static final class Builder extends
+        com.google.protobuf.GeneratedMessage.Builder<Builder>
+       implements org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReplyOrBuilder {
+      public static final com.google.protobuf.Descriptors.Descriptor
+          getDescriptor() {
+        return org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.internal_static_org_opendaylight_controller_mdsal_DataChangedReply_descriptor;
+      }
+
+      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+          internalGetFieldAccessorTable() {
+        return org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.internal_static_org_opendaylight_controller_mdsal_DataChangedReply_fieldAccessorTable
+            .ensureFieldAccessorsInitialized(
+                org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply.class, org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply.Builder.class);
+      }
+
+      // Construct using org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply.newBuilder()
+      private Builder() {
+        maybeForceBuilderInitialization();
+      }
+
+      private Builder(
+          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+        super(parent);
+        maybeForceBuilderInitialization();
+      }
+      private void maybeForceBuilderInitialization() {
+        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+        }
+      }
+      private static Builder create() {
+        return new Builder();
+      }
+
+      public Builder clear() {
+        super.clear();
+        return this;
+      }
+
+      public Builder clone() {
+        return create().mergeFrom(buildPartial());
+      }
+
+      public com.google.protobuf.Descriptors.Descriptor
+          getDescriptorForType() {
+        return org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.internal_static_org_opendaylight_controller_mdsal_DataChangedReply_descriptor;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply.getDefaultInstance();
+      }
+
+      public org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply build() {
+        org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply result = buildPartial();
+        if (!result.isInitialized()) {
+          throw newUninitializedMessageException(result);
+        }
+        return result;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply buildPartial() {
+        org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply result = new org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply(this);
+        onBuilt();
+        return result;
+      }
+
+      public Builder mergeFrom(com.google.protobuf.Message other) {
+        if (other instanceof org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply)other);
+        } else {
+          super.mergeFrom(other);
+          return this;
+        }
+      }
+
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply other) {
+        if (other == org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply.getDefaultInstance()) return this;
+        this.mergeUnknownFields(other.getUnknownFields());
+        return this;
+      }
+
+      public final boolean isInitialized() {
+        return true;
+      }
+
+      public Builder mergeFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws java.io.IOException {
+        org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply parsedMessage = null;
+        try {
+          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.datachange.notification.DataChangeListenerMessages.DataChangedReply) e.getUnfinishedMessage();
+          throw e;
+        } finally {
+          if (parsedMessage != null) {
+            mergeFrom(parsedMessage);
+          }
+        }
+        return this;
+      }
+
+      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.DataChangedReply)
+    }
+
+    static {
+      defaultInstance = new DataChangedReply(true);
+      defaultInstance.initFields();
+    }
+
+    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.DataChangedReply)
+  }
+
+  private static com.google.protobuf.Descriptors.Descriptor
+    internal_static_org_opendaylight_controller_mdsal_DataChanged_descriptor;
+  private static
+    com.google.protobuf.GeneratedMessage.FieldAccessorTable
+      internal_static_org_opendaylight_controller_mdsal_DataChanged_fieldAccessorTable;
+  private static com.google.protobuf.Descriptors.Descriptor
+    internal_static_org_opendaylight_controller_mdsal_DataChangedReply_descriptor;
+  private static
+    com.google.protobuf.GeneratedMessage.FieldAccessorTable
+      internal_static_org_opendaylight_controller_mdsal_DataChangedReply_fieldAccessorTable;
+
+  public static com.google.protobuf.Descriptors.FileDescriptor
+      getDescriptor() {
+    return descriptor;
+  }
+  private static com.google.protobuf.Descriptors.FileDescriptor
+      descriptor;
+  static {
+    java.lang.String[] descriptorData = {
+      "\n\030DataChangeListener.proto\022!org.opendayl" +
+      "ight.controller.mdsal\032\032SimpleNormalizedN" +
+      "ode.proto\"\207\001\n\013DataChanged\022\'\n\037instanceIde" +
+      "ntifierPathArguments\030\001 \003(\t\022O\n\021normalized" +
+      "NodeXml\030\002 \002(\01324.org.opendaylight.control" +
+      "ler.mdsal.NormalizedNodeXml\"\022\n\020DataChang" +
+      "edReplyBd\nForg.opendaylight.controller.p" +
+      "rotobuff.messages.datachange.notificatio" +
+      "nB\032DataChangeListenerMessages"
+    };
+    com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
+      new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
+        public com.google.protobuf.ExtensionRegistry assignDescriptors(
+            com.google.protobuf.Descriptors.FileDescriptor root) {
+          descriptor = root;
+          internal_static_org_opendaylight_controller_mdsal_DataChanged_descriptor =
+            getDescriptor().getMessageTypes().get(0);
+          internal_static_org_opendaylight_controller_mdsal_DataChanged_fieldAccessorTable = new
+            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+              internal_static_org_opendaylight_controller_mdsal_DataChanged_descriptor,
+              new java.lang.String[] { "InstanceIdentifierPathArguments", "NormalizedNodeXml", });
+          internal_static_org_opendaylight_controller_mdsal_DataChangedReply_descriptor =
+            getDescriptor().getMessageTypes().get(1);
+          internal_static_org_opendaylight_controller_mdsal_DataChangedReply_fieldAccessorTable = new
+            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+              internal_static_org_opendaylight_controller_mdsal_DataChangedReply_descriptor,
+              new java.lang.String[] { });
+          return null;
+        }
+      };
+    com.google.protobuf.Descriptors.FileDescriptor
+      .internalBuildGeneratedFileFrom(descriptorData,
+        new com.google.protobuf.Descriptors.FileDescriptor[] {
+          org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.getDescriptor(),
+        }, assigner);
+  }
+
+  // @@protoc_insertion_point(outer_class_scope)
+}
@@ -1,7 +1,7 @@
 // Generated by the protocol buffer compiler.  DO NOT EDIT!
 // source: ListenerRegistration.proto
 
-package org.opendaylight.controller.cluster.datastore.registration;
+package org.opendaylight.controller.protobuff.messages.registration;
 
 public final class ListenerRegistrationMessages {
   private ListenerRegistrationMessages() {}
@@ -75,14 +75,14 @@ public final class ListenerRegistrationMessages {
     }
     public static final com.google.protobuf.Descriptors.Descriptor
         getDescriptor() {
-      return org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.internal_static_org_opendaylight_controller_mdsal_Close_descriptor;
+      return org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.internal_static_org_opendaylight_controller_mdsal_Close_descriptor;
     }
 
     protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
         internalGetFieldAccessorTable() {
-      return org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.internal_static_org_opendaylight_controller_mdsal_Close_fieldAccessorTable
+      return org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.internal_static_org_opendaylight_controller_mdsal_Close_fieldAccessorTable
           .ensureFieldAccessorsInitialized(
-              org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close.class, org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close.Builder.class);
+              org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close.class, org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close.Builder.class);
     }
 
     public static com.google.protobuf.Parser<Close> PARSER =
@@ -135,53 +135,53 @@ public final class ListenerRegistrationMessages {
       return super.writeReplace();
     }
 
-    public static org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close parseFrom(
         com.google.protobuf.ByteString data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
-    public static org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close parseFrom(
         com.google.protobuf.ByteString data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close parseFrom(byte[] data)
+    public static org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close parseFrom(byte[] data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
-    public static org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close parseFrom(
         byte[] data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close parseFrom(java.io.InputStream input)
+    public static org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close parseFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close parseFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseFrom(input, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close parseDelimitedFrom(java.io.InputStream input)
+    public static org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close parseDelimitedFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close parseDelimitedFrom(
+    public static org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close parseDelimitedFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close parseFrom(
         com.google.protobuf.CodedInputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close parseFrom(
         com.google.protobuf.CodedInputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
@@ -190,7 +190,7 @@ public final class ListenerRegistrationMessages {
 
     public static Builder newBuilder() { return Builder.create(); }
     public Builder newBuilderForType() { return newBuilder(); }
-    public static Builder newBuilder(org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close prototype) {
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close prototype) {
       return newBuilder().mergeFrom(prototype);
     }
     public Builder toBuilder() { return newBuilder(this); }
@@ -206,20 +206,20 @@ public final class ListenerRegistrationMessages {
      */
     public static final class Builder extends
         com.google.protobuf.GeneratedMessage.Builder<Builder>
-       implements org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseOrBuilder {
+       implements org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseOrBuilder {
       public static final com.google.protobuf.Descriptors.Descriptor
           getDescriptor() {
-        return org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.internal_static_org_opendaylight_controller_mdsal_Close_descriptor;
+        return org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.internal_static_org_opendaylight_controller_mdsal_Close_descriptor;
       }
 
       protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
           internalGetFieldAccessorTable() {
-        return org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.internal_static_org_opendaylight_controller_mdsal_Close_fieldAccessorTable
+        return org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.internal_static_org_opendaylight_controller_mdsal_Close_fieldAccessorTable
             .ensureFieldAccessorsInitialized(
-                org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close.class, org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close.Builder.class);
+                org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close.class, org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close.Builder.class);
       }
 
-      // Construct using org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close.newBuilder()
+      // Construct using org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close.newBuilder()
       private Builder() {
         maybeForceBuilderInitialization();
       }
@@ -248,38 +248,38 @@ public final class ListenerRegistrationMessages {
 
       public com.google.protobuf.Descriptors.Descriptor
           getDescriptorForType() {
-        return org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.internal_static_org_opendaylight_controller_mdsal_Close_descriptor;
+        return org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.internal_static_org_opendaylight_controller_mdsal_Close_descriptor;
       }
 
-      public org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close getDefaultInstanceForType() {
-        return org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close.getDefaultInstance();
+      public org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close.getDefaultInstance();
       }
 
-      public org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close build() {
-        org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close result = buildPartial();
+      public org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close build() {
+        org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close result = buildPartial();
         if (!result.isInitialized()) {
           throw newUninitializedMessageException(result);
         }
         return result;
       }
 
-      public org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close buildPartial() {
-        org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close result = new org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close(this);
+      public org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close buildPartial() {
+        org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close result = new org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close(this);
         onBuilt();
         return result;
       }
 
       public Builder mergeFrom(com.google.protobuf.Message other) {
-        if (other instanceof org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close) {
-          return mergeFrom((org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close)other);
+        if (other instanceof org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close)other);
         } else {
           super.mergeFrom(other);
           return this;
         }
       }
 
-      public Builder mergeFrom(org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close other) {
-        if (other == org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close.getDefaultInstance()) return this;
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close other) {
+        if (other == org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close.getDefaultInstance()) return this;
         this.mergeUnknownFields(other.getUnknownFields());
         return this;
       }
@@ -292,11 +292,11 @@ public final class ListenerRegistrationMessages {
           com.google.protobuf.CodedInputStream input,
           com.google.protobuf.ExtensionRegistryLite extensionRegistry)
           throws java.io.IOException {
-        org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close parsedMessage = null;
+        org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close parsedMessage = null;
         try {
           parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
         } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-          parsedMessage = (org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.Close) e.getUnfinishedMessage();
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.Close) e.getUnfinishedMessage();
           throw e;
         } finally {
           if (parsedMessage != null) {
@@ -384,14 +384,14 @@ public final class ListenerRegistrationMessages {
     }
     public static final com.google.protobuf.Descriptors.Descriptor
         getDescriptor() {
-      return org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.internal_static_org_opendaylight_controller_mdsal_CloseReply_descriptor;
+      return org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.internal_static_org_opendaylight_controller_mdsal_CloseReply_descriptor;
     }
 
     protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
         internalGetFieldAccessorTable() {
-      return org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.internal_static_org_opendaylight_controller_mdsal_CloseReply_fieldAccessorTable
+      return org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.internal_static_org_opendaylight_controller_mdsal_CloseReply_fieldAccessorTable
           .ensureFieldAccessorsInitialized(
-              org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply.class, org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply.Builder.class);
+              org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply.class, org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply.Builder.class);
     }
 
     public static com.google.protobuf.Parser<CloseReply> PARSER =
@@ -444,53 +444,53 @@ public final class ListenerRegistrationMessages {
       return super.writeReplace();
     }
 
-    public static org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply parseFrom(
         com.google.protobuf.ByteString data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
-    public static org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply parseFrom(
         com.google.protobuf.ByteString data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply parseFrom(byte[] data)
+    public static org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply parseFrom(byte[] data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
-    public static org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply parseFrom(
         byte[] data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply parseFrom(java.io.InputStream input)
+    public static org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply parseFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply parseFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseFrom(input, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply parseDelimitedFrom(java.io.InputStream input)
+    public static org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply parseDelimitedFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply parseDelimitedFrom(
+    public static org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply parseDelimitedFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply parseFrom(
         com.google.protobuf.CodedInputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply parseFrom(
         com.google.protobuf.CodedInputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
@@ -499,7 +499,7 @@ public final class ListenerRegistrationMessages {
 
     public static Builder newBuilder() { return Builder.create(); }
     public Builder newBuilderForType() { return newBuilder(); }
-    public static Builder newBuilder(org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply prototype) {
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply prototype) {
       return newBuilder().mergeFrom(prototype);
     }
     public Builder toBuilder() { return newBuilder(this); }
@@ -515,20 +515,20 @@ public final class ListenerRegistrationMessages {
      */
     public static final class Builder extends
         com.google.protobuf.GeneratedMessage.Builder<Builder>
-       implements org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReplyOrBuilder {
+       implements org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReplyOrBuilder {
       public static final com.google.protobuf.Descriptors.Descriptor
           getDescriptor() {
-        return org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.internal_static_org_opendaylight_controller_mdsal_CloseReply_descriptor;
+        return org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.internal_static_org_opendaylight_controller_mdsal_CloseReply_descriptor;
       }
 
       protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
           internalGetFieldAccessorTable() {
-        return org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.internal_static_org_opendaylight_controller_mdsal_CloseReply_fieldAccessorTable
+        return org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.internal_static_org_opendaylight_controller_mdsal_CloseReply_fieldAccessorTable
             .ensureFieldAccessorsInitialized(
-                org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply.class, org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply.Builder.class);
+                org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply.class, org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply.Builder.class);
       }
 
-      // Construct using org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply.newBuilder()
+      // Construct using org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply.newBuilder()
       private Builder() {
         maybeForceBuilderInitialization();
       }
@@ -557,38 +557,38 @@ public final class ListenerRegistrationMessages {
 
       public com.google.protobuf.Descriptors.Descriptor
           getDescriptorForType() {
-        return org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.internal_static_org_opendaylight_controller_mdsal_CloseReply_descriptor;
+        return org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.internal_static_org_opendaylight_controller_mdsal_CloseReply_descriptor;
       }
 
-      public org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply getDefaultInstanceForType() {
-        return org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply.getDefaultInstance();
+      public org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply.getDefaultInstance();
       }
 
-      public org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply build() {
-        org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply result = buildPartial();
+      public org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply build() {
+        org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply result = buildPartial();
         if (!result.isInitialized()) {
           throw newUninitializedMessageException(result);
         }
         return result;
       }
 
-      public org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply buildPartial() {
-        org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply result = new org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply(this);
+      public org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply buildPartial() {
+        org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply result = new org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply(this);
         onBuilt();
         return result;
       }
 
       public Builder mergeFrom(com.google.protobuf.Message other) {
-        if (other instanceof org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply) {
-          return mergeFrom((org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply)other);
+        if (other instanceof org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply)other);
         } else {
           super.mergeFrom(other);
           return this;
         }
       }
 
-      public Builder mergeFrom(org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply other) {
-        if (other == org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply.getDefaultInstance()) return this;
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply other) {
+        if (other == org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply.getDefaultInstance()) return this;
         this.mergeUnknownFields(other.getUnknownFields());
         return this;
       }
@@ -601,11 +601,11 @@ public final class ListenerRegistrationMessages {
           com.google.protobuf.CodedInputStream input,
           com.google.protobuf.ExtensionRegistryLite extensionRegistry)
           throws java.io.IOException {
-        org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply parsedMessage = null;
+        org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply parsedMessage = null;
         try {
           parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
         } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-          parsedMessage = (org.opendaylight.controller.cluster.datastore.registration.ListenerRegistrationMessages.CloseReply) e.getUnfinishedMessage();
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.registration.ListenerRegistrationMessages.CloseReply) e.getUnfinishedMessage();
           throw e;
         } finally {
           if (parsedMessage != null) {
@@ -647,9 +647,9 @@ public final class ListenerRegistrationMessages {
     java.lang.String[] descriptorData = {
       "\n\032ListenerRegistration.proto\022!org.openda" +
       "ylight.controller.mdsal\"\007\n\005Close\"\014\n\nClos" +
-      "eReplyBZ\n:org.opendaylight.controller.cl" +
-      "uster.datastore.registrationB\034ListenerRe" +
-      "gistrationMessages"
+      "eReplyB[\n;org.opendaylight.controller.pr" +
+      "otobuff.messages.registrationB\034ListenerR" +
+      "egistrationMessages"
     };
     com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
       new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
@@ -1,7 +1,7 @@
 // Generated by the protocol buffer compiler.  DO NOT EDIT!
 // source: ShardManager.proto
 
-package org.opendaylight.controller.cluster.datastore.shard;
+package org.opendaylight.controller.protobuff.messages.shard;
 
 public final class ShardManagerMessages {
   private ShardManagerMessages() {}
@@ -96,14 +96,14 @@ public final class ShardManagerMessages {
     }
     public static final com.google.protobuf.Descriptors.Descriptor
         getDescriptor() {
-      return org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_FindPrimary_descriptor;
+      return org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_FindPrimary_descriptor;
     }
 
     protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
         internalGetFieldAccessorTable() {
-      return org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_FindPrimary_fieldAccessorTable
+      return org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_FindPrimary_fieldAccessorTable
           .ensureFieldAccessorsInitialized(
-              org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary.class, org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary.Builder.class);
+              org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary.class, org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary.Builder.class);
     }
 
     public static com.google.protobuf.Parser<FindPrimary> PARSER =
@@ -212,53 +212,53 @@ public final class ShardManagerMessages {
       return super.writeReplace();
     }
 
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary parseFrom(
         com.google.protobuf.ByteString data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary parseFrom(
         com.google.protobuf.ByteString data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary parseFrom(byte[] data)
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary parseFrom(byte[] data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary parseFrom(
         byte[] data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary parseFrom(java.io.InputStream input)
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary parseFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary parseFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseFrom(input, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary parseDelimitedFrom(java.io.InputStream input)
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary parseDelimitedFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary parseDelimitedFrom(
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary parseDelimitedFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary parseFrom(
         com.google.protobuf.CodedInputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary parseFrom(
         com.google.protobuf.CodedInputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
@@ -267,7 +267,7 @@ public final class ShardManagerMessages {
 
     public static Builder newBuilder() { return Builder.create(); }
     public Builder newBuilderForType() { return newBuilder(); }
-    public static Builder newBuilder(org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary prototype) {
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary prototype) {
       return newBuilder().mergeFrom(prototype);
     }
     public Builder toBuilder() { return newBuilder(this); }
@@ -283,20 +283,20 @@ public final class ShardManagerMessages {
      */
     public static final class Builder extends
         com.google.protobuf.GeneratedMessage.Builder<Builder>
-       implements org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimaryOrBuilder {
+       implements org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimaryOrBuilder {
       public static final com.google.protobuf.Descriptors.Descriptor
           getDescriptor() {
-        return org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_FindPrimary_descriptor;
+        return org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_FindPrimary_descriptor;
       }
 
       protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
           internalGetFieldAccessorTable() {
-        return org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_FindPrimary_fieldAccessorTable
+        return org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_FindPrimary_fieldAccessorTable
             .ensureFieldAccessorsInitialized(
-                org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary.class, org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary.Builder.class);
+                org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary.class, org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary.Builder.class);
       }
 
-      // Construct using org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary.newBuilder()
+      // Construct using org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary.newBuilder()
       private Builder() {
         maybeForceBuilderInitialization();
       }
@@ -327,23 +327,23 @@ public final class ShardManagerMessages {
 
       public com.google.protobuf.Descriptors.Descriptor
           getDescriptorForType() {
-        return org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_FindPrimary_descriptor;
+        return org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_FindPrimary_descriptor;
       }
 
-      public org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary getDefaultInstanceForType() {
-        return org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary.getDefaultInstance();
+      public org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary.getDefaultInstance();
       }
 
-      public org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary build() {
-        org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary result = buildPartial();
+      public org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary build() {
+        org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary result = buildPartial();
         if (!result.isInitialized()) {
           throw newUninitializedMessageException(result);
         }
         return result;
       }
 
-      public org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary buildPartial() {
-        org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary result = new org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary(this);
+      public org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary buildPartial() {
+        org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary result = new org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary(this);
         int from_bitField0_ = bitField0_;
         int to_bitField0_ = 0;
         if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
@@ -356,16 +356,16 @@ public final class ShardManagerMessages {
       }
 
       public Builder mergeFrom(com.google.protobuf.Message other) {
-        if (other instanceof org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary) {
-          return mergeFrom((org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary)other);
+        if (other instanceof org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary)other);
         } else {
           super.mergeFrom(other);
           return this;
         }
       }
 
-      public Builder mergeFrom(org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary other) {
-        if (other == org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary.getDefaultInstance()) return this;
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary other) {
+        if (other == org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary.getDefaultInstance()) return this;
         if (other.hasShardName()) {
           bitField0_ |= 0x00000001;
           shardName_ = other.shardName_;
@@ -387,11 +387,11 @@ public final class ShardManagerMessages {
           com.google.protobuf.CodedInputStream input,
           com.google.protobuf.ExtensionRegistryLite extensionRegistry)
           throws java.io.IOException {
-        org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary parsedMessage = null;
+        org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary parsedMessage = null;
         try {
           parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
         } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-          parsedMessage = (org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.FindPrimary) e.getUnfinishedMessage();
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.FindPrimary) e.getUnfinishedMessage();
           throw e;
         } finally {
           if (parsedMessage != null) {
@@ -554,14 +554,14 @@ public final class ShardManagerMessages {
     }
     public static final com.google.protobuf.Descriptors.Descriptor
         getDescriptor() {
-      return org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_PrimaryFound_descriptor;
+      return org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_PrimaryFound_descriptor;
     }
 
     protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
         internalGetFieldAccessorTable() {
-      return org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_PrimaryFound_fieldAccessorTable
+      return org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_PrimaryFound_fieldAccessorTable
           .ensureFieldAccessorsInitialized(
-              org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound.class, org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound.Builder.class);
+              org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound.class, org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound.Builder.class);
     }
 
     public static com.google.protobuf.Parser<PrimaryFound> PARSER =
@@ -614,53 +614,53 @@ public final class ShardManagerMessages {
       return super.writeReplace();
     }
 
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound parseFrom(
         com.google.protobuf.ByteString data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound parseFrom(
         com.google.protobuf.ByteString data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound parseFrom(byte[] data)
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound parseFrom(byte[] data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound parseFrom(
         byte[] data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound parseFrom(java.io.InputStream input)
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound parseFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound parseFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseFrom(input, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound parseDelimitedFrom(java.io.InputStream input)
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound parseDelimitedFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound parseDelimitedFrom(
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound parseDelimitedFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound parseFrom(
         com.google.protobuf.CodedInputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound parseFrom(
         com.google.protobuf.CodedInputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
@@ -669,7 +669,7 @@ public final class ShardManagerMessages {
 
     public static Builder newBuilder() { return Builder.create(); }
     public Builder newBuilderForType() { return newBuilder(); }
-    public static Builder newBuilder(org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound prototype) {
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound prototype) {
       return newBuilder().mergeFrom(prototype);
     }
     public Builder toBuilder() { return newBuilder(this); }
@@ -685,20 +685,20 @@ public final class ShardManagerMessages {
      */
     public static final class Builder extends
         com.google.protobuf.GeneratedMessage.Builder<Builder>
-       implements org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFoundOrBuilder {
+       implements org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFoundOrBuilder {
       public static final com.google.protobuf.Descriptors.Descriptor
           getDescriptor() {
-        return org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_PrimaryFound_descriptor;
+        return org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_PrimaryFound_descriptor;
       }
 
       protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
           internalGetFieldAccessorTable() {
-        return org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_PrimaryFound_fieldAccessorTable
+        return org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_PrimaryFound_fieldAccessorTable
             .ensureFieldAccessorsInitialized(
-                org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound.class, org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound.Builder.class);
+                org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound.class, org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound.Builder.class);
       }
 
-      // Construct using org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound.newBuilder()
+      // Construct using org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound.newBuilder()
       private Builder() {
         maybeForceBuilderInitialization();
       }
@@ -727,38 +727,38 @@ public final class ShardManagerMessages {
 
       public com.google.protobuf.Descriptors.Descriptor
           getDescriptorForType() {
-        return org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_PrimaryFound_descriptor;
+        return org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_PrimaryFound_descriptor;
       }
 
-      public org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound getDefaultInstanceForType() {
-        return org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound.getDefaultInstance();
+      public org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound.getDefaultInstance();
       }
 
-      public org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound build() {
-        org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound result = buildPartial();
+      public org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound build() {
+        org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound result = buildPartial();
         if (!result.isInitialized()) {
           throw newUninitializedMessageException(result);
         }
         return result;
       }
 
-      public org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound buildPartial() {
-        org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound result = new org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound(this);
+      public org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound buildPartial() {
+        org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound result = new org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound(this);
         onBuilt();
         return result;
       }
 
       public Builder mergeFrom(com.google.protobuf.Message other) {
-        if (other instanceof org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound) {
-          return mergeFrom((org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound)other);
+        if (other instanceof org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound)other);
         } else {
           super.mergeFrom(other);
           return this;
         }
       }
 
-      public Builder mergeFrom(org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound other) {
-        if (other == org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound.getDefaultInstance()) return this;
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound other) {
+        if (other == org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound.getDefaultInstance()) return this;
         this.mergeUnknownFields(other.getUnknownFields());
         return this;
       }
@@ -771,11 +771,11 @@ public final class ShardManagerMessages {
           com.google.protobuf.CodedInputStream input,
           com.google.protobuf.ExtensionRegistryLite extensionRegistry)
           throws java.io.IOException {
-        org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound parsedMessage = null;
+        org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound parsedMessage = null;
         try {
           parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
         } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-          parsedMessage = (org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryFound) e.getUnfinishedMessage();
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryFound) e.getUnfinishedMessage();
           throw e;
         } finally {
           if (parsedMessage != null) {
@@ -863,14 +863,14 @@ public final class ShardManagerMessages {
     }
     public static final com.google.protobuf.Descriptors.Descriptor
         getDescriptor() {
-      return org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_PrimaryNotFound_descriptor;
+      return org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_PrimaryNotFound_descriptor;
     }
 
     protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
         internalGetFieldAccessorTable() {
-      return org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_PrimaryNotFound_fieldAccessorTable
+      return org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_PrimaryNotFound_fieldAccessorTable
           .ensureFieldAccessorsInitialized(
-              org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound.class, org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound.Builder.class);
+              org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound.class, org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound.Builder.class);
     }
 
     public static com.google.protobuf.Parser<PrimaryNotFound> PARSER =
@@ -923,53 +923,53 @@ public final class ShardManagerMessages {
       return super.writeReplace();
     }
 
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound parseFrom(
         com.google.protobuf.ByteString data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound parseFrom(
         com.google.protobuf.ByteString data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound parseFrom(byte[] data)
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound parseFrom(byte[] data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound parseFrom(
         byte[] data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound parseFrom(java.io.InputStream input)
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound parseFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound parseFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseFrom(input, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound parseDelimitedFrom(java.io.InputStream input)
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound parseDelimitedFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound parseDelimitedFrom(
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound parseDelimitedFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound parseFrom(
         com.google.protobuf.CodedInputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound parseFrom(
         com.google.protobuf.CodedInputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
@@ -978,7 +978,7 @@ public final class ShardManagerMessages {
 
     public static Builder newBuilder() { return Builder.create(); }
     public Builder newBuilderForType() { return newBuilder(); }
-    public static Builder newBuilder(org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound prototype) {
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound prototype) {
       return newBuilder().mergeFrom(prototype);
     }
     public Builder toBuilder() { return newBuilder(this); }
@@ -994,20 +994,20 @@ public final class ShardManagerMessages {
      */
     public static final class Builder extends
         com.google.protobuf.GeneratedMessage.Builder<Builder>
-       implements org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFoundOrBuilder {
+       implements org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFoundOrBuilder {
       public static final com.google.protobuf.Descriptors.Descriptor
           getDescriptor() {
-        return org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_PrimaryNotFound_descriptor;
+        return org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_PrimaryNotFound_descriptor;
       }
 
       protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
           internalGetFieldAccessorTable() {
-        return org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_PrimaryNotFound_fieldAccessorTable
+        return org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_PrimaryNotFound_fieldAccessorTable
             .ensureFieldAccessorsInitialized(
-                org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound.class, org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound.Builder.class);
+                org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound.class, org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound.Builder.class);
       }
 
-      // Construct using org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound.newBuilder()
+      // Construct using org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound.newBuilder()
       private Builder() {
         maybeForceBuilderInitialization();
       }
@@ -1036,38 +1036,38 @@ public final class ShardManagerMessages {
 
       public com.google.protobuf.Descriptors.Descriptor
           getDescriptorForType() {
-        return org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_PrimaryNotFound_descriptor;
+        return org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.internal_static_org_opendaylight_controller_mdsal_PrimaryNotFound_descriptor;
       }
 
-      public org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound getDefaultInstanceForType() {
-        return org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound.getDefaultInstance();
+      public org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound.getDefaultInstance();
       }
 
-      public org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound build() {
-        org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound result = buildPartial();
+      public org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound build() {
+        org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound result = buildPartial();
         if (!result.isInitialized()) {
           throw newUninitializedMessageException(result);
         }
         return result;
       }
 
-      public org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound buildPartial() {
-        org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound result = new org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound(this);
+      public org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound buildPartial() {
+        org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound result = new org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound(this);
         onBuilt();
         return result;
       }
 
       public Builder mergeFrom(com.google.protobuf.Message other) {
-        if (other instanceof org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound) {
-          return mergeFrom((org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound)other);
+        if (other instanceof org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound)other);
         } else {
           super.mergeFrom(other);
           return this;
         }
       }
 
-      public Builder mergeFrom(org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound other) {
-        if (other == org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound.getDefaultInstance()) return this;
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound other) {
+        if (other == org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound.getDefaultInstance()) return this;
         this.mergeUnknownFields(other.getUnknownFields());
         return this;
       }
@@ -1080,11 +1080,11 @@ public final class ShardManagerMessages {
           com.google.protobuf.CodedInputStream input,
           com.google.protobuf.ExtensionRegistryLite extensionRegistry)
           throws java.io.IOException {
-        org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound parsedMessage = null;
+        org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound parsedMessage = null;
         try {
           parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
         } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-          parsedMessage = (org.opendaylight.controller.cluster.datastore.shard.ShardManagerMessages.PrimaryNotFound) e.getUnfinishedMessage();
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.shard.ShardManagerMessages.PrimaryNotFound) e.getUnfinishedMessage();
           throw e;
         } finally {
           if (parsedMessage != null) {
@@ -1132,9 +1132,9 @@ public final class ShardManagerMessages {
       "\n\022ShardManager.proto\022!org.opendaylight.c" +
       "ontroller.mdsal\" \n\013FindPrimary\022\021\n\tshardN" +
       "ame\030\001 \002(\t\"\016\n\014PrimaryFound\"\021\n\017PrimaryNotF" +
-      "oundBK\n3org.opendaylight.controller.clus" +
-      "ter.datastore.shardB\024ShardManagerMessage" +
-      "s"
+      "oundBL\n4org.opendaylight.controller.prot" +
+      "obuff.messages.shardB\024ShardManagerMessag" +
+      "es"
     };
     com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
       new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
@@ -1,7 +1,7 @@
 // Generated by the protocol buffer compiler.  DO NOT EDIT!
-// source: ShardTransactionChainMessages.proto
+// source: ShardTransactionChain.proto
 
-package org.opendaylight.controller.cluster.datastore.transaction;
+package org.opendaylight.controller.protobuff.messages.transaction;
 
 public final class ShardTransactionChainMessages {
   private ShardTransactionChainMessages() {}
@@ -75,14 +75,14 @@ public final class ShardTransactionChainMessages {
     }
     public static final com.google.protobuf.Descriptors.Descriptor
         getDescriptor() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionChain_descriptor;
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionChain_descriptor;
     }
 
     protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
         internalGetFieldAccessorTable() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionChain_fieldAccessorTable
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionChain_fieldAccessorTable
           .ensureFieldAccessorsInitialized(
-              org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain.Builder.class);
+              org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain.Builder.class);
     }
 
     public static com.google.protobuf.Parser<CloseTransactionChain> PARSER =
@@ -135,53 +135,53 @@ public final class ShardTransactionChainMessages {
       return super.writeReplace();
     }
 
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain parseFrom(
         com.google.protobuf.ByteString data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain parseFrom(
         com.google.protobuf.ByteString data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain parseFrom(byte[] data)
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain parseFrom(byte[] data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain parseFrom(
         byte[] data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain parseFrom(java.io.InputStream input)
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain parseFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain parseFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseFrom(input, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain parseDelimitedFrom(java.io.InputStream input)
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain parseDelimitedFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain parseDelimitedFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain parseDelimitedFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain parseFrom(
         com.google.protobuf.CodedInputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain parseFrom(
         com.google.protobuf.CodedInputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
@@ -190,7 +190,7 @@ public final class ShardTransactionChainMessages {
 
     public static Builder newBuilder() { return Builder.create(); }
     public Builder newBuilderForType() { return newBuilder(); }
-    public static Builder newBuilder(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain prototype) {
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain prototype) {
       return newBuilder().mergeFrom(prototype);
     }
     public Builder toBuilder() { return newBuilder(this); }
@@ -206,20 +206,20 @@ public final class ShardTransactionChainMessages {
      */
     public static final class Builder extends
         com.google.protobuf.GeneratedMessage.Builder<Builder>
-       implements org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainOrBuilder {
+       implements org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainOrBuilder {
       public static final com.google.protobuf.Descriptors.Descriptor
           getDescriptor() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionChain_descriptor;
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionChain_descriptor;
       }
 
       protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
           internalGetFieldAccessorTable() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionChain_fieldAccessorTable
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionChain_fieldAccessorTable
             .ensureFieldAccessorsInitialized(
-                org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain.Builder.class);
+                org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain.Builder.class);
       }
 
-      // Construct using org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain.newBuilder()
+      // Construct using org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain.newBuilder()
       private Builder() {
         maybeForceBuilderInitialization();
       }
@@ -248,38 +248,38 @@ public final class ShardTransactionChainMessages {
 
       public com.google.protobuf.Descriptors.Descriptor
           getDescriptorForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionChain_descriptor;
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionChain_descriptor;
       }
 
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain getDefaultInstanceForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain.getDefaultInstance();
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain.getDefaultInstance();
       }
 
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain build() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain result = buildPartial();
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain build() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain result = buildPartial();
         if (!result.isInitialized()) {
           throw newUninitializedMessageException(result);
         }
         return result;
       }
 
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain buildPartial() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain result = new org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain(this);
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain buildPartial() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain result = new org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain(this);
         onBuilt();
         return result;
       }
 
       public Builder mergeFrom(com.google.protobuf.Message other) {
-        if (other instanceof org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain) {
-          return mergeFrom((org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain)other);
+        if (other instanceof org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain)other);
         } else {
           super.mergeFrom(other);
           return this;
         }
       }
 
-      public Builder mergeFrom(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain other) {
-        if (other == org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain.getDefaultInstance()) return this;
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain other) {
+        if (other == org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain.getDefaultInstance()) return this;
         this.mergeUnknownFields(other.getUnknownFields());
         return this;
       }
@@ -292,11 +292,11 @@ public final class ShardTransactionChainMessages {
           com.google.protobuf.CodedInputStream input,
           com.google.protobuf.ExtensionRegistryLite extensionRegistry)
           throws java.io.IOException {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain parsedMessage = null;
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain parsedMessage = null;
         try {
           parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
         } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-          parsedMessage = (org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChain) e.getUnfinishedMessage();
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChain) e.getUnfinishedMessage();
           throw e;
         } finally {
           if (parsedMessage != null) {
@@ -384,14 +384,14 @@ public final class ShardTransactionChainMessages {
     }
     public static final com.google.protobuf.Descriptors.Descriptor
         getDescriptor() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionChainReply_descriptor;
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionChainReply_descriptor;
     }
 
     protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
         internalGetFieldAccessorTable() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionChainReply_fieldAccessorTable
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionChainReply_fieldAccessorTable
           .ensureFieldAccessorsInitialized(
-              org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply.Builder.class);
+              org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply.Builder.class);
     }
 
     public static com.google.protobuf.Parser<CloseTransactionChainReply> PARSER =
@@ -444,53 +444,53 @@ public final class ShardTransactionChainMessages {
       return super.writeReplace();
     }
 
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parseFrom(
         com.google.protobuf.ByteString data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parseFrom(
         com.google.protobuf.ByteString data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parseFrom(byte[] data)
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parseFrom(byte[] data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parseFrom(
         byte[] data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parseFrom(java.io.InputStream input)
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parseFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parseFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseFrom(input, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parseDelimitedFrom(java.io.InputStream input)
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parseDelimitedFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parseDelimitedFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parseDelimitedFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parseFrom(
         com.google.protobuf.CodedInputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parseFrom(
         com.google.protobuf.CodedInputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
@@ -499,7 +499,7 @@ public final class ShardTransactionChainMessages {
 
     public static Builder newBuilder() { return Builder.create(); }
     public Builder newBuilderForType() { return newBuilder(); }
-    public static Builder newBuilder(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply prototype) {
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply prototype) {
       return newBuilder().mergeFrom(prototype);
     }
     public Builder toBuilder() { return newBuilder(this); }
@@ -515,20 +515,20 @@ public final class ShardTransactionChainMessages {
      */
     public static final class Builder extends
         com.google.protobuf.GeneratedMessage.Builder<Builder>
-       implements org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReplyOrBuilder {
+       implements org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReplyOrBuilder {
       public static final com.google.protobuf.Descriptors.Descriptor
           getDescriptor() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionChainReply_descriptor;
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionChainReply_descriptor;
       }
 
       protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
           internalGetFieldAccessorTable() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionChainReply_fieldAccessorTable
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionChainReply_fieldAccessorTable
             .ensureFieldAccessorsInitialized(
-                org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply.Builder.class);
+                org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply.Builder.class);
       }
 
-      // Construct using org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply.newBuilder()
+      // Construct using org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply.newBuilder()
       private Builder() {
         maybeForceBuilderInitialization();
       }
@@ -557,38 +557,38 @@ public final class ShardTransactionChainMessages {
 
       public com.google.protobuf.Descriptors.Descriptor
           getDescriptorForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionChainReply_descriptor;
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionChainReply_descriptor;
       }
 
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply getDefaultInstanceForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply.getDefaultInstance();
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply.getDefaultInstance();
       }
 
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply build() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply result = buildPartial();
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply build() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply result = buildPartial();
         if (!result.isInitialized()) {
           throw newUninitializedMessageException(result);
         }
         return result;
       }
 
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply buildPartial() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply result = new org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply(this);
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply buildPartial() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply result = new org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply(this);
         onBuilt();
         return result;
       }
 
       public Builder mergeFrom(com.google.protobuf.Message other) {
-        if (other instanceof org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply) {
-          return mergeFrom((org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply)other);
+        if (other instanceof org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply)other);
         } else {
           super.mergeFrom(other);
           return this;
         }
       }
 
-      public Builder mergeFrom(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply other) {
-        if (other == org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply.getDefaultInstance()) return this;
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply other) {
+        if (other == org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply.getDefaultInstance()) return this;
         this.mergeUnknownFields(other.getUnknownFields());
         return this;
       }
@@ -601,11 +601,11 @@ public final class ShardTransactionChainMessages {
           com.google.protobuf.CodedInputStream input,
           com.google.protobuf.ExtensionRegistryLite extensionRegistry)
           throws java.io.IOException {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parsedMessage = null;
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply parsedMessage = null;
         try {
           parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
         } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-          parsedMessage = (org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CloseTransactionChainReply) e.getUnfinishedMessage();
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CloseTransactionChainReply) e.getUnfinishedMessage();
           throw e;
         } finally {
           if (parsedMessage != null) {
@@ -693,14 +693,14 @@ public final class ShardTransactionChainMessages {
     }
     public static final com.google.protobuf.Descriptors.Descriptor
         getDescriptor() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionChain_descriptor;
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionChain_descriptor;
     }
 
     protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
         internalGetFieldAccessorTable() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionChain_fieldAccessorTable
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionChain_fieldAccessorTable
           .ensureFieldAccessorsInitialized(
-              org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain.Builder.class);
+              org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain.Builder.class);
     }
 
     public static com.google.protobuf.Parser<CreateTransactionChain> PARSER =
@@ -753,53 +753,53 @@ public final class ShardTransactionChainMessages {
       return super.writeReplace();
     }
 
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain parseFrom(
         com.google.protobuf.ByteString data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain parseFrom(
         com.google.protobuf.ByteString data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain parseFrom(byte[] data)
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain parseFrom(byte[] data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain parseFrom(
         byte[] data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain parseFrom(java.io.InputStream input)
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain parseFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain parseFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseFrom(input, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain parseDelimitedFrom(java.io.InputStream input)
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain parseDelimitedFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain parseDelimitedFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain parseDelimitedFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain parseFrom(
         com.google.protobuf.CodedInputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain parseFrom(
         com.google.protobuf.CodedInputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
@@ -808,7 +808,7 @@ public final class ShardTransactionChainMessages {
 
     public static Builder newBuilder() { return Builder.create(); }
     public Builder newBuilderForType() { return newBuilder(); }
-    public static Builder newBuilder(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain prototype) {
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain prototype) {
       return newBuilder().mergeFrom(prototype);
     }
     public Builder toBuilder() { return newBuilder(this); }
@@ -824,20 +824,20 @@ public final class ShardTransactionChainMessages {
      */
     public static final class Builder extends
         com.google.protobuf.GeneratedMessage.Builder<Builder>
-       implements org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainOrBuilder {
+       implements org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainOrBuilder {
       public static final com.google.protobuf.Descriptors.Descriptor
           getDescriptor() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionChain_descriptor;
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionChain_descriptor;
       }
 
       protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
           internalGetFieldAccessorTable() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionChain_fieldAccessorTable
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionChain_fieldAccessorTable
             .ensureFieldAccessorsInitialized(
-                org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain.Builder.class);
+                org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain.Builder.class);
       }
 
-      // Construct using org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain.newBuilder()
+      // Construct using org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain.newBuilder()
       private Builder() {
         maybeForceBuilderInitialization();
       }
@@ -866,38 +866,38 @@ public final class ShardTransactionChainMessages {
 
       public com.google.protobuf.Descriptors.Descriptor
           getDescriptorForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionChain_descriptor;
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionChain_descriptor;
       }
 
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain getDefaultInstanceForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain.getDefaultInstance();
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain.getDefaultInstance();
       }
 
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain build() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain result = buildPartial();
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain build() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain result = buildPartial();
         if (!result.isInitialized()) {
           throw newUninitializedMessageException(result);
         }
         return result;
       }
 
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain buildPartial() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain result = new org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain(this);
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain buildPartial() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain result = new org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain(this);
         onBuilt();
         return result;
       }
 
       public Builder mergeFrom(com.google.protobuf.Message other) {
-        if (other instanceof org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain) {
-          return mergeFrom((org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain)other);
+        if (other instanceof org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain)other);
         } else {
           super.mergeFrom(other);
           return this;
         }
       }
 
-      public Builder mergeFrom(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain other) {
-        if (other == org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain.getDefaultInstance()) return this;
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain other) {
+        if (other == org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain.getDefaultInstance()) return this;
         this.mergeUnknownFields(other.getUnknownFields());
         return this;
       }
@@ -910,11 +910,11 @@ public final class ShardTransactionChainMessages {
           com.google.protobuf.CodedInputStream input,
           com.google.protobuf.ExtensionRegistryLite extensionRegistry)
           throws java.io.IOException {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain parsedMessage = null;
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain parsedMessage = null;
         try {
           parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
         } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-          parsedMessage = (org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChain) e.getUnfinishedMessage();
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChain) e.getUnfinishedMessage();
           throw e;
         } finally {
           if (parsedMessage != null) {
@@ -1023,14 +1023,14 @@ public final class ShardTransactionChainMessages {
     }
     public static final com.google.protobuf.Descriptors.Descriptor
         getDescriptor() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionChainReply_descriptor;
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionChainReply_descriptor;
     }
 
     protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
         internalGetFieldAccessorTable() {
-      return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionChainReply_fieldAccessorTable
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionChainReply_fieldAccessorTable
           .ensureFieldAccessorsInitialized(
-              org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply.Builder.class);
+              org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply.Builder.class);
     }
 
     public static com.google.protobuf.Parser<CreateTransactionChainReply> PARSER =
@@ -1139,53 +1139,53 @@ public final class ShardTransactionChainMessages {
       return super.writeReplace();
     }
 
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parseFrom(
         com.google.protobuf.ByteString data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parseFrom(
         com.google.protobuf.ByteString data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parseFrom(byte[] data)
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parseFrom(byte[] data)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parseFrom(
         byte[] data,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws com.google.protobuf.InvalidProtocolBufferException {
       return PARSER.parseFrom(data, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parseFrom(java.io.InputStream input)
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parseFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parseFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseFrom(input, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parseDelimitedFrom(java.io.InputStream input)
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parseDelimitedFrom(java.io.InputStream input)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parseDelimitedFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parseDelimitedFrom(
         java.io.InputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
       return PARSER.parseDelimitedFrom(input, extensionRegistry);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parseFrom(
         com.google.protobuf.CodedInputStream input)
         throws java.io.IOException {
       return PARSER.parseFrom(input);
     }
-    public static org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parseFrom(
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parseFrom(
         com.google.protobuf.CodedInputStream input,
         com.google.protobuf.ExtensionRegistryLite extensionRegistry)
         throws java.io.IOException {
@@ -1194,7 +1194,7 @@ public final class ShardTransactionChainMessages {
 
     public static Builder newBuilder() { return Builder.create(); }
     public Builder newBuilderForType() { return newBuilder(); }
-    public static Builder newBuilder(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply prototype) {
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply prototype) {
       return newBuilder().mergeFrom(prototype);
     }
     public Builder toBuilder() { return newBuilder(this); }
@@ -1210,20 +1210,20 @@ public final class ShardTransactionChainMessages {
      */
     public static final class Builder extends
         com.google.protobuf.GeneratedMessage.Builder<Builder>
-       implements org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReplyOrBuilder {
+       implements org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReplyOrBuilder {
       public static final com.google.protobuf.Descriptors.Descriptor
           getDescriptor() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionChainReply_descriptor;
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionChainReply_descriptor;
       }
 
       protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
           internalGetFieldAccessorTable() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionChainReply_fieldAccessorTable
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionChainReply_fieldAccessorTable
             .ensureFieldAccessorsInitialized(
-                org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply.class, org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply.Builder.class);
+                org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply.Builder.class);
       }
 
-      // Construct using org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply.newBuilder()
+      // Construct using org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply.newBuilder()
       private Builder() {
         maybeForceBuilderInitialization();
       }
@@ -1254,23 +1254,23 @@ public final class ShardTransactionChainMessages {
 
       public com.google.protobuf.Descriptors.Descriptor
           getDescriptorForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionChainReply_descriptor;
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionChainReply_descriptor;
       }
 
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply getDefaultInstanceForType() {
-        return org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply.getDefaultInstance();
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply.getDefaultInstance();
       }
 
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply build() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply result = buildPartial();
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply build() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply result = buildPartial();
         if (!result.isInitialized()) {
           throw newUninitializedMessageException(result);
         }
         return result;
       }
 
-      public org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply buildPartial() {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply result = new org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply(this);
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply buildPartial() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply result = new org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply(this);
         int from_bitField0_ = bitField0_;
         int to_bitField0_ = 0;
         if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
@@ -1283,16 +1283,16 @@ public final class ShardTransactionChainMessages {
       }
 
       public Builder mergeFrom(com.google.protobuf.Message other) {
-        if (other instanceof org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply) {
-          return mergeFrom((org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply)other);
+        if (other instanceof org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply)other);
         } else {
           super.mergeFrom(other);
           return this;
         }
       }
 
-      public Builder mergeFrom(org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply other) {
-        if (other == org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply.getDefaultInstance()) return this;
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply other) {
+        if (other == org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply.getDefaultInstance()) return this;
         if (other.hasTransactionChainPath()) {
           bitField0_ |= 0x00000001;
           transactionChainPath_ = other.transactionChainPath_;
@@ -1303,7 +1303,8 @@ public final class ShardTransactionChainMessages {
       }
 
       public final boolean isInitialized() {
-        if (!hasTransactionChainPath()){
+        if (!hasTransactionChainPath()) {
+
           return false;
         }
         return true;
@@ -1313,11 +1314,11 @@ public final class ShardTransactionChainMessages {
           com.google.protobuf.CodedInputStream input,
           com.google.protobuf.ExtensionRegistryLite extensionRegistry)
           throws java.io.IOException {
-        org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parsedMessage = null;
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply parsedMessage = null;
         try {
           parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
         } catch (com.google.protobuf.InvalidProtocolBufferException e) {
-          parsedMessage = (org.opendaylight.controller.cluster.datastore.transaction.ShardTransactionChainMessages.CreateTransactionChainReply) e.getUnfinishedMessage();
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionChainMessages.CreateTransactionChainReply) e.getUnfinishedMessage();
           throw e;
         } finally {
           if (parsedMessage != null) {
@@ -1442,14 +1443,14 @@ public final class ShardTransactionChainMessages {
       descriptor;
   static {
     java.lang.String[] descriptorData = {
-      "\n#ShardTransactionChainMessages.proto\022!o" +
-      "rg.opendaylight.controller.mdsal\"\027\n\025Clos" +
-      "eTransactionChain\"\034\n\032CloseTransactionCha" +
-      "inReply\"\030\n\026CreateTransactionChain\";\n\033Cre" +
-      "ateTransactionChainReply\022\034\n\024transactionC" +
-      "hainPath\030\001 \002(\tBZ\n9org.opendaylight.contr" +
-      "oller.cluster.datastore.transactionB\035Sha" +
-      "rdTransactionChainMessages"
+      "\n\033ShardTransactionChain.proto\022!org.opend" +
+      "aylight.controller.mdsal\"\027\n\025CloseTransac" +
+      "tionChain\"\034\n\032CloseTransactionChainReply\"" +
+      "\030\n\026CreateTransactionChain\";\n\033CreateTrans" +
+      "actionChainReply\022\034\n\024transactionChainPath" +
+      "\030\001 \002(\tB[\n:org.opendaylight.controller.pr" +
+      "otobuff.messages.transactionB\035ShardTrans" +
+      "actionChainMessages"
     };
     com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
       new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionMessages.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/java/org/opendaylight/controller/protobuff/messages/transaction/ShardTransactionMessages.java
new file mode 100644 (file)
index 0000000..cabcf85
--- /dev/null
@@ -0,0 +1,5207 @@
+// Generated by the protocol buffer compiler.  DO NOT EDIT!
+// source: ShardTransaction.proto
+
+package org.opendaylight.controller.protobuff.messages.transaction;
+
+public final class ShardTransactionMessages {
+  private ShardTransactionMessages() {}
+  public static void registerAllExtensions(
+      com.google.protobuf.ExtensionRegistry registry) {
+  }
+  public interface CloseTransactionOrBuilder
+      extends com.google.protobuf.MessageOrBuilder {
+  }
+  /**
+   * Protobuf type {@code org.opendaylight.controller.mdsal.CloseTransaction}
+   */
+  public static final class CloseTransaction extends
+      com.google.protobuf.GeneratedMessage
+      implements CloseTransactionOrBuilder {
+    // Use CloseTransaction.newBuilder() to construct.
+    private CloseTransaction(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
+      super(builder);
+      this.unknownFields = builder.getUnknownFields();
+    }
+    private CloseTransaction(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+    private static final CloseTransaction defaultInstance;
+    public static CloseTransaction getDefaultInstance() {
+      return defaultInstance;
+    }
+
+    public CloseTransaction getDefaultInstanceForType() {
+      return defaultInstance;
+    }
+
+    private final com.google.protobuf.UnknownFieldSet unknownFields;
+    @java.lang.Override
+    public final com.google.protobuf.UnknownFieldSet
+        getUnknownFields() {
+      return this.unknownFields;
+    }
+    private CloseTransaction(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      initFields();
+      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+          com.google.protobuf.UnknownFieldSet.newBuilder();
+      try {
+        boolean done = false;
+        while (!done) {
+          int tag = input.readTag();
+          switch (tag) {
+            case 0:
+              done = true;
+              break;
+            default: {
+              if (!parseUnknownField(input, unknownFields,
+                                     extensionRegistry, tag)) {
+                done = true;
+              }
+              break;
+            }
+          }
+        }
+      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+        throw e.setUnfinishedMessage(this);
+      } catch (java.io.IOException e) {
+        throw new com.google.protobuf.InvalidProtocolBufferException(
+            e.getMessage()).setUnfinishedMessage(this);
+      } finally {
+        this.unknownFields = unknownFields.build();
+        makeExtensionsImmutable();
+      }
+    }
+    public static final com.google.protobuf.Descriptors.Descriptor
+        getDescriptor() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransaction_descriptor;
+    }
+
+    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+        internalGetFieldAccessorTable() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransaction_fieldAccessorTable
+          .ensureFieldAccessorsInitialized(
+              org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction.Builder.class);
+    }
+
+    public static com.google.protobuf.Parser<CloseTransaction> PARSER =
+        new com.google.protobuf.AbstractParser<CloseTransaction>() {
+      public CloseTransaction parsePartialFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws com.google.protobuf.InvalidProtocolBufferException {
+        return new CloseTransaction(input, extensionRegistry);
+      }
+    };
+
+    @java.lang.Override
+    public com.google.protobuf.Parser<CloseTransaction> getParserForType() {
+      return PARSER;
+    }
+
+    private void initFields() {
+    }
+    private byte memoizedIsInitialized = -1;
+    public final boolean isInitialized() {
+      byte isInitialized = memoizedIsInitialized;
+      if (isInitialized != -1) return isInitialized == 1;
+
+      memoizedIsInitialized = 1;
+      return true;
+    }
+
+    public void writeTo(com.google.protobuf.CodedOutputStream output)
+                        throws java.io.IOException {
+      getSerializedSize();
+      getUnknownFields().writeTo(output);
+    }
+
+    private int memoizedSerializedSize = -1;
+    public int getSerializedSize() {
+      int size = memoizedSerializedSize;
+      if (size != -1) return size;
+
+      size = 0;
+      size += getUnknownFields().getSerializedSize();
+      memoizedSerializedSize = size;
+      return size;
+    }
+
+    private static final long serialVersionUID = 0L;
+    @java.lang.Override
+    protected java.lang.Object writeReplace()
+        throws java.io.ObjectStreamException {
+      return super.writeReplace();
+    }
+
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction parseFrom(
+        com.google.protobuf.ByteString data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction parseFrom(
+        com.google.protobuf.ByteString data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction parseFrom(byte[] data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction parseFrom(
+        byte[] data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction parseFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction parseFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction parseDelimitedFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction parseDelimitedFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction parseFrom(
+        com.google.protobuf.CodedInputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction parseFrom(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+
+    public static Builder newBuilder() { return Builder.create(); }
+    public Builder newBuilderForType() { return newBuilder(); }
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction prototype) {
+      return newBuilder().mergeFrom(prototype);
+    }
+    public Builder toBuilder() { return newBuilder(this); }
+
+    @java.lang.Override
+    protected Builder newBuilderForType(
+        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+      Builder builder = new Builder(parent);
+      return builder;
+    }
+    /**
+     * Protobuf type {@code org.opendaylight.controller.mdsal.CloseTransaction}
+     */
+    public static final class Builder extends
+        com.google.protobuf.GeneratedMessage.Builder<Builder>
+       implements org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionOrBuilder {
+      public static final com.google.protobuf.Descriptors.Descriptor
+          getDescriptor() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransaction_descriptor;
+      }
+
+      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+          internalGetFieldAccessorTable() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransaction_fieldAccessorTable
+            .ensureFieldAccessorsInitialized(
+                org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction.Builder.class);
+      }
+
+      // Construct using org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction.newBuilder()
+      private Builder() {
+        maybeForceBuilderInitialization();
+      }
+
+      private Builder(
+          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+        super(parent);
+        maybeForceBuilderInitialization();
+      }
+      private void maybeForceBuilderInitialization() {
+        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+        }
+      }
+      private static Builder create() {
+        return new Builder();
+      }
+
+      public Builder clear() {
+        super.clear();
+        return this;
+      }
+
+      public Builder clone() {
+        return create().mergeFrom(buildPartial());
+      }
+
+      public com.google.protobuf.Descriptors.Descriptor
+          getDescriptorForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransaction_descriptor;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction.getDefaultInstance();
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction build() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction result = buildPartial();
+        if (!result.isInitialized()) {
+          throw newUninitializedMessageException(result);
+        }
+        return result;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction buildPartial() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction result = new org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction(this);
+        onBuilt();
+        return result;
+      }
+
+      public Builder mergeFrom(com.google.protobuf.Message other) {
+        if (other instanceof org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction)other);
+        } else {
+          super.mergeFrom(other);
+          return this;
+        }
+      }
+
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction other) {
+        if (other == org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction.getDefaultInstance()) return this;
+        this.mergeUnknownFields(other.getUnknownFields());
+        return this;
+      }
+
+      public final boolean isInitialized() {
+        return true;
+      }
+
+      public Builder mergeFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws java.io.IOException {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction parsedMessage = null;
+        try {
+          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransaction) e.getUnfinishedMessage();
+          throw e;
+        } finally {
+          if (parsedMessage != null) {
+            mergeFrom(parsedMessage);
+          }
+        }
+        return this;
+      }
+
+      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.CloseTransaction)
+    }
+
+    static {
+      defaultInstance = new CloseTransaction(true);
+      defaultInstance.initFields();
+    }
+
+    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.CloseTransaction)
+  }
+
+  public interface CloseTransactionReplyOrBuilder
+      extends com.google.protobuf.MessageOrBuilder {
+  }
+  /**
+   * Protobuf type {@code org.opendaylight.controller.mdsal.CloseTransactionReply}
+   */
+  public static final class CloseTransactionReply extends
+      com.google.protobuf.GeneratedMessage
+      implements CloseTransactionReplyOrBuilder {
+    // Use CloseTransactionReply.newBuilder() to construct.
+    private CloseTransactionReply(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
+      super(builder);
+      this.unknownFields = builder.getUnknownFields();
+    }
+    private CloseTransactionReply(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+    private static final CloseTransactionReply defaultInstance;
+    public static CloseTransactionReply getDefaultInstance() {
+      return defaultInstance;
+    }
+
+    public CloseTransactionReply getDefaultInstanceForType() {
+      return defaultInstance;
+    }
+
+    private final com.google.protobuf.UnknownFieldSet unknownFields;
+    @java.lang.Override
+    public final com.google.protobuf.UnknownFieldSet
+        getUnknownFields() {
+      return this.unknownFields;
+    }
+    private CloseTransactionReply(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      initFields();
+      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+          com.google.protobuf.UnknownFieldSet.newBuilder();
+      try {
+        boolean done = false;
+        while (!done) {
+          int tag = input.readTag();
+          switch (tag) {
+            case 0:
+              done = true;
+              break;
+            default: {
+              if (!parseUnknownField(input, unknownFields,
+                                     extensionRegistry, tag)) {
+                done = true;
+              }
+              break;
+            }
+          }
+        }
+      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+        throw e.setUnfinishedMessage(this);
+      } catch (java.io.IOException e) {
+        throw new com.google.protobuf.InvalidProtocolBufferException(
+            e.getMessage()).setUnfinishedMessage(this);
+      } finally {
+        this.unknownFields = unknownFields.build();
+        makeExtensionsImmutable();
+      }
+    }
+    public static final com.google.protobuf.Descriptors.Descriptor
+        getDescriptor() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionReply_descriptor;
+    }
+
+    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+        internalGetFieldAccessorTable() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionReply_fieldAccessorTable
+          .ensureFieldAccessorsInitialized(
+              org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply.Builder.class);
+    }
+
+    public static com.google.protobuf.Parser<CloseTransactionReply> PARSER =
+        new com.google.protobuf.AbstractParser<CloseTransactionReply>() {
+      public CloseTransactionReply parsePartialFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws com.google.protobuf.InvalidProtocolBufferException {
+        return new CloseTransactionReply(input, extensionRegistry);
+      }
+    };
+
+    @java.lang.Override
+    public com.google.protobuf.Parser<CloseTransactionReply> getParserForType() {
+      return PARSER;
+    }
+
+    private void initFields() {
+    }
+    private byte memoizedIsInitialized = -1;
+    public final boolean isInitialized() {
+      byte isInitialized = memoizedIsInitialized;
+      if (isInitialized != -1) return isInitialized == 1;
+
+      memoizedIsInitialized = 1;
+      return true;
+    }
+
+    public void writeTo(com.google.protobuf.CodedOutputStream output)
+                        throws java.io.IOException {
+      getSerializedSize();
+      getUnknownFields().writeTo(output);
+    }
+
+    private int memoizedSerializedSize = -1;
+    public int getSerializedSize() {
+      int size = memoizedSerializedSize;
+      if (size != -1) return size;
+
+      size = 0;
+      size += getUnknownFields().getSerializedSize();
+      memoizedSerializedSize = size;
+      return size;
+    }
+
+    private static final long serialVersionUID = 0L;
+    @java.lang.Override
+    protected java.lang.Object writeReplace()
+        throws java.io.ObjectStreamException {
+      return super.writeReplace();
+    }
+
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply parseFrom(
+        com.google.protobuf.ByteString data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply parseFrom(
+        com.google.protobuf.ByteString data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply parseFrom(byte[] data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply parseFrom(
+        byte[] data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply parseFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply parseFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply parseDelimitedFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply parseDelimitedFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply parseFrom(
+        com.google.protobuf.CodedInputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply parseFrom(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+
+    public static Builder newBuilder() { return Builder.create(); }
+    public Builder newBuilderForType() { return newBuilder(); }
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply prototype) {
+      return newBuilder().mergeFrom(prototype);
+    }
+    public Builder toBuilder() { return newBuilder(this); }
+
+    @java.lang.Override
+    protected Builder newBuilderForType(
+        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+      Builder builder = new Builder(parent);
+      return builder;
+    }
+    /**
+     * Protobuf type {@code org.opendaylight.controller.mdsal.CloseTransactionReply}
+     */
+    public static final class Builder extends
+        com.google.protobuf.GeneratedMessage.Builder<Builder>
+       implements org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReplyOrBuilder {
+      public static final com.google.protobuf.Descriptors.Descriptor
+          getDescriptor() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionReply_descriptor;
+      }
+
+      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+          internalGetFieldAccessorTable() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionReply_fieldAccessorTable
+            .ensureFieldAccessorsInitialized(
+                org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply.Builder.class);
+      }
+
+      // Construct using org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply.newBuilder()
+      private Builder() {
+        maybeForceBuilderInitialization();
+      }
+
+      private Builder(
+          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+        super(parent);
+        maybeForceBuilderInitialization();
+      }
+      private void maybeForceBuilderInitialization() {
+        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+        }
+      }
+      private static Builder create() {
+        return new Builder();
+      }
+
+      public Builder clear() {
+        super.clear();
+        return this;
+      }
+
+      public Builder clone() {
+        return create().mergeFrom(buildPartial());
+      }
+
+      public com.google.protobuf.Descriptors.Descriptor
+          getDescriptorForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CloseTransactionReply_descriptor;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply.getDefaultInstance();
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply build() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply result = buildPartial();
+        if (!result.isInitialized()) {
+          throw newUninitializedMessageException(result);
+        }
+        return result;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply buildPartial() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply result = new org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply(this);
+        onBuilt();
+        return result;
+      }
+
+      public Builder mergeFrom(com.google.protobuf.Message other) {
+        if (other instanceof org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply)other);
+        } else {
+          super.mergeFrom(other);
+          return this;
+        }
+      }
+
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply other) {
+        if (other == org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply.getDefaultInstance()) return this;
+        this.mergeUnknownFields(other.getUnknownFields());
+        return this;
+      }
+
+      public final boolean isInitialized() {
+        return true;
+      }
+
+      public Builder mergeFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws java.io.IOException {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply parsedMessage = null;
+        try {
+          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CloseTransactionReply) e.getUnfinishedMessage();
+          throw e;
+        } finally {
+          if (parsedMessage != null) {
+            mergeFrom(parsedMessage);
+          }
+        }
+        return this;
+      }
+
+      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.CloseTransactionReply)
+    }
+
+    static {
+      defaultInstance = new CloseTransactionReply(true);
+      defaultInstance.initFields();
+    }
+
+    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.CloseTransactionReply)
+  }
+
+  public interface CreateTransactionOrBuilder
+      extends com.google.protobuf.MessageOrBuilder {
+  }
+  /**
+   * Protobuf type {@code org.opendaylight.controller.mdsal.CreateTransaction}
+   */
+  public static final class CreateTransaction extends
+      com.google.protobuf.GeneratedMessage
+      implements CreateTransactionOrBuilder {
+    // Use CreateTransaction.newBuilder() to construct.
+    private CreateTransaction(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
+      super(builder);
+      this.unknownFields = builder.getUnknownFields();
+    }
+    private CreateTransaction(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+    private static final CreateTransaction defaultInstance;
+    public static CreateTransaction getDefaultInstance() {
+      return defaultInstance;
+    }
+
+    public CreateTransaction getDefaultInstanceForType() {
+      return defaultInstance;
+    }
+
+    private final com.google.protobuf.UnknownFieldSet unknownFields;
+    @java.lang.Override
+    public final com.google.protobuf.UnknownFieldSet
+        getUnknownFields() {
+      return this.unknownFields;
+    }
+    private CreateTransaction(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      initFields();
+      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+          com.google.protobuf.UnknownFieldSet.newBuilder();
+      try {
+        boolean done = false;
+        while (!done) {
+          int tag = input.readTag();
+          switch (tag) {
+            case 0:
+              done = true;
+              break;
+            default: {
+              if (!parseUnknownField(input, unknownFields,
+                                     extensionRegistry, tag)) {
+                done = true;
+              }
+              break;
+            }
+          }
+        }
+      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+        throw e.setUnfinishedMessage(this);
+      } catch (java.io.IOException e) {
+        throw new com.google.protobuf.InvalidProtocolBufferException(
+            e.getMessage()).setUnfinishedMessage(this);
+      } finally {
+        this.unknownFields = unknownFields.build();
+        makeExtensionsImmutable();
+      }
+    }
+    public static final com.google.protobuf.Descriptors.Descriptor
+        getDescriptor() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransaction_descriptor;
+    }
+
+    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+        internalGetFieldAccessorTable() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransaction_fieldAccessorTable
+          .ensureFieldAccessorsInitialized(
+              org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction.Builder.class);
+    }
+
+    public static com.google.protobuf.Parser<CreateTransaction> PARSER =
+        new com.google.protobuf.AbstractParser<CreateTransaction>() {
+      public CreateTransaction parsePartialFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws com.google.protobuf.InvalidProtocolBufferException {
+        return new CreateTransaction(input, extensionRegistry);
+      }
+    };
+
+    @java.lang.Override
+    public com.google.protobuf.Parser<CreateTransaction> getParserForType() {
+      return PARSER;
+    }
+
+    private void initFields() {
+    }
+    private byte memoizedIsInitialized = -1;
+    public final boolean isInitialized() {
+      byte isInitialized = memoizedIsInitialized;
+      if (isInitialized != -1) return isInitialized == 1;
+
+      memoizedIsInitialized = 1;
+      return true;
+    }
+
+    public void writeTo(com.google.protobuf.CodedOutputStream output)
+                        throws java.io.IOException {
+      getSerializedSize();
+      getUnknownFields().writeTo(output);
+    }
+
+    private int memoizedSerializedSize = -1;
+    public int getSerializedSize() {
+      int size = memoizedSerializedSize;
+      if (size != -1) return size;
+
+      size = 0;
+      size += getUnknownFields().getSerializedSize();
+      memoizedSerializedSize = size;
+      return size;
+    }
+
+    private static final long serialVersionUID = 0L;
+    @java.lang.Override
+    protected java.lang.Object writeReplace()
+        throws java.io.ObjectStreamException {
+      return super.writeReplace();
+    }
+
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction parseFrom(
+        com.google.protobuf.ByteString data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction parseFrom(
+        com.google.protobuf.ByteString data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction parseFrom(byte[] data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction parseFrom(
+        byte[] data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction parseFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction parseFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction parseDelimitedFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction parseDelimitedFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction parseFrom(
+        com.google.protobuf.CodedInputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction parseFrom(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+
+    public static Builder newBuilder() { return Builder.create(); }
+    public Builder newBuilderForType() { return newBuilder(); }
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction prototype) {
+      return newBuilder().mergeFrom(prototype);
+    }
+    public Builder toBuilder() { return newBuilder(this); }
+
+    @java.lang.Override
+    protected Builder newBuilderForType(
+        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+      Builder builder = new Builder(parent);
+      return builder;
+    }
+    /**
+     * Protobuf type {@code org.opendaylight.controller.mdsal.CreateTransaction}
+     */
+    public static final class Builder extends
+        com.google.protobuf.GeneratedMessage.Builder<Builder>
+       implements org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionOrBuilder {
+      public static final com.google.protobuf.Descriptors.Descriptor
+          getDescriptor() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransaction_descriptor;
+      }
+
+      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+          internalGetFieldAccessorTable() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransaction_fieldAccessorTable
+            .ensureFieldAccessorsInitialized(
+                org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction.Builder.class);
+      }
+
+      // Construct using org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction.newBuilder()
+      private Builder() {
+        maybeForceBuilderInitialization();
+      }
+
+      private Builder(
+          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+        super(parent);
+        maybeForceBuilderInitialization();
+      }
+      private void maybeForceBuilderInitialization() {
+        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+        }
+      }
+      private static Builder create() {
+        return new Builder();
+      }
+
+      public Builder clear() {
+        super.clear();
+        return this;
+      }
+
+      public Builder clone() {
+        return create().mergeFrom(buildPartial());
+      }
+
+      public com.google.protobuf.Descriptors.Descriptor
+          getDescriptorForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransaction_descriptor;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction.getDefaultInstance();
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction build() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction result = buildPartial();
+        if (!result.isInitialized()) {
+          throw newUninitializedMessageException(result);
+        }
+        return result;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction buildPartial() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction result = new org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction(this);
+        onBuilt();
+        return result;
+      }
+
+      public Builder mergeFrom(com.google.protobuf.Message other) {
+        if (other instanceof org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction)other);
+        } else {
+          super.mergeFrom(other);
+          return this;
+        }
+      }
+
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction other) {
+        if (other == org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction.getDefaultInstance()) return this;
+        this.mergeUnknownFields(other.getUnknownFields());
+        return this;
+      }
+
+      public final boolean isInitialized() {
+        return true;
+      }
+
+      public Builder mergeFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws java.io.IOException {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction parsedMessage = null;
+        try {
+          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransaction) e.getUnfinishedMessage();
+          throw e;
+        } finally {
+          if (parsedMessage != null) {
+            mergeFrom(parsedMessage);
+          }
+        }
+        return this;
+      }
+
+      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.CreateTransaction)
+    }
+
+    static {
+      defaultInstance = new CreateTransaction(true);
+      defaultInstance.initFields();
+    }
+
+    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.CreateTransaction)
+  }
+
+  public interface CreateTransactionReplyOrBuilder
+      extends com.google.protobuf.MessageOrBuilder {
+
+    // required string transactionPath = 1;
+    /**
+     * <code>required string transactionPath = 1;</code>
+     */
+    boolean hasTransactionPath();
+    /**
+     * <code>required string transactionPath = 1;</code>
+     */
+    java.lang.String getTransactionPath();
+    /**
+     * <code>required string transactionPath = 1;</code>
+     */
+    com.google.protobuf.ByteString
+        getTransactionPathBytes();
+  }
+  /**
+   * Protobuf type {@code org.opendaylight.controller.mdsal.CreateTransactionReply}
+   */
+  public static final class CreateTransactionReply extends
+      com.google.protobuf.GeneratedMessage
+      implements CreateTransactionReplyOrBuilder {
+    // Use CreateTransactionReply.newBuilder() to construct.
+    private CreateTransactionReply(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
+      super(builder);
+      this.unknownFields = builder.getUnknownFields();
+    }
+    private CreateTransactionReply(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+    private static final CreateTransactionReply defaultInstance;
+    public static CreateTransactionReply getDefaultInstance() {
+      return defaultInstance;
+    }
+
+    public CreateTransactionReply getDefaultInstanceForType() {
+      return defaultInstance;
+    }
+
+    private final com.google.protobuf.UnknownFieldSet unknownFields;
+    @java.lang.Override
+    public final com.google.protobuf.UnknownFieldSet
+        getUnknownFields() {
+      return this.unknownFields;
+    }
+    private CreateTransactionReply(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      initFields();
+      int mutable_bitField0_ = 0;
+      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+          com.google.protobuf.UnknownFieldSet.newBuilder();
+      try {
+        boolean done = false;
+        while (!done) {
+          int tag = input.readTag();
+          switch (tag) {
+            case 0:
+              done = true;
+              break;
+            default: {
+              if (!parseUnknownField(input, unknownFields,
+                                     extensionRegistry, tag)) {
+                done = true;
+              }
+              break;
+            }
+            case 10: {
+              bitField0_ |= 0x00000001;
+              transactionPath_ = input.readBytes();
+              break;
+            }
+          }
+        }
+      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+        throw e.setUnfinishedMessage(this);
+      } catch (java.io.IOException e) {
+        throw new com.google.protobuf.InvalidProtocolBufferException(
+            e.getMessage()).setUnfinishedMessage(this);
+      } finally {
+        this.unknownFields = unknownFields.build();
+        makeExtensionsImmutable();
+      }
+    }
+    public static final com.google.protobuf.Descriptors.Descriptor
+        getDescriptor() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_descriptor;
+    }
+
+    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+        internalGetFieldAccessorTable() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_fieldAccessorTable
+          .ensureFieldAccessorsInitialized(
+              org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply.Builder.class);
+    }
+
+    public static com.google.protobuf.Parser<CreateTransactionReply> PARSER =
+        new com.google.protobuf.AbstractParser<CreateTransactionReply>() {
+      public CreateTransactionReply parsePartialFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws com.google.protobuf.InvalidProtocolBufferException {
+        return new CreateTransactionReply(input, extensionRegistry);
+      }
+    };
+
+    @java.lang.Override
+    public com.google.protobuf.Parser<CreateTransactionReply> getParserForType() {
+      return PARSER;
+    }
+
+    private int bitField0_;
+    // required string transactionPath = 1;
+    public static final int TRANSACTIONPATH_FIELD_NUMBER = 1;
+    private java.lang.Object transactionPath_;
+    /**
+     * <code>required string transactionPath = 1;</code>
+     */
+    public boolean hasTransactionPath() {
+      return ((bitField0_ & 0x00000001) == 0x00000001);
+    }
+    /**
+     * <code>required string transactionPath = 1;</code>
+     */
+    public java.lang.String getTransactionPath() {
+      java.lang.Object ref = transactionPath_;
+      if (ref instanceof java.lang.String) {
+        return (java.lang.String) ref;
+      } else {
+        com.google.protobuf.ByteString bs =
+            (com.google.protobuf.ByteString) ref;
+        java.lang.String s = bs.toStringUtf8();
+        if (bs.isValidUtf8()) {
+          transactionPath_ = s;
+        }
+        return s;
+      }
+    }
+    /**
+     * <code>required string transactionPath = 1;</code>
+     */
+    public com.google.protobuf.ByteString
+        getTransactionPathBytes() {
+      java.lang.Object ref = transactionPath_;
+      if (ref instanceof java.lang.String) {
+        com.google.protobuf.ByteString b =
+            com.google.protobuf.ByteString.copyFromUtf8(
+                (java.lang.String) ref);
+        transactionPath_ = b;
+        return b;
+      } else {
+        return (com.google.protobuf.ByteString) ref;
+      }
+    }
+
+    private void initFields() {
+      transactionPath_ = "";
+    }
+    private byte memoizedIsInitialized = -1;
+    public final boolean isInitialized() {
+      byte isInitialized = memoizedIsInitialized;
+      if (isInitialized != -1) return isInitialized == 1;
+
+      if (!hasTransactionPath()) {
+        memoizedIsInitialized = 0;
+        return false;
+      }
+      memoizedIsInitialized = 1;
+      return true;
+    }
+
+    public void writeTo(com.google.protobuf.CodedOutputStream output)
+                        throws java.io.IOException {
+      getSerializedSize();
+      if (((bitField0_ & 0x00000001) == 0x00000001)) {
+        output.writeBytes(1, getTransactionPathBytes());
+      }
+      getUnknownFields().writeTo(output);
+    }
+
+    private int memoizedSerializedSize = -1;
+    public int getSerializedSize() {
+      int size = memoizedSerializedSize;
+      if (size != -1) return size;
+
+      size = 0;
+      if (((bitField0_ & 0x00000001) == 0x00000001)) {
+        size += com.google.protobuf.CodedOutputStream
+          .computeBytesSize(1, getTransactionPathBytes());
+      }
+      size += getUnknownFields().getSerializedSize();
+      memoizedSerializedSize = size;
+      return size;
+    }
+
+    private static final long serialVersionUID = 0L;
+    @java.lang.Override
+    protected java.lang.Object writeReplace()
+        throws java.io.ObjectStreamException {
+      return super.writeReplace();
+    }
+
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply parseFrom(
+        com.google.protobuf.ByteString data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply parseFrom(
+        com.google.protobuf.ByteString data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply parseFrom(byte[] data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply parseFrom(
+        byte[] data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply parseFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply parseFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply parseDelimitedFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply parseDelimitedFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply parseFrom(
+        com.google.protobuf.CodedInputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply parseFrom(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+
+    public static Builder newBuilder() { return Builder.create(); }
+    public Builder newBuilderForType() { return newBuilder(); }
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply prototype) {
+      return newBuilder().mergeFrom(prototype);
+    }
+    public Builder toBuilder() { return newBuilder(this); }
+
+    @java.lang.Override
+    protected Builder newBuilderForType(
+        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+      Builder builder = new Builder(parent);
+      return builder;
+    }
+    /**
+     * Protobuf type {@code org.opendaylight.controller.mdsal.CreateTransactionReply}
+     */
+    public static final class Builder extends
+        com.google.protobuf.GeneratedMessage.Builder<Builder>
+       implements org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReplyOrBuilder {
+      public static final com.google.protobuf.Descriptors.Descriptor
+          getDescriptor() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_descriptor;
+      }
+
+      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+          internalGetFieldAccessorTable() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_fieldAccessorTable
+            .ensureFieldAccessorsInitialized(
+                org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply.Builder.class);
+      }
+
+      // Construct using org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply.newBuilder()
+      private Builder() {
+        maybeForceBuilderInitialization();
+      }
+
+      private Builder(
+          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+        super(parent);
+        maybeForceBuilderInitialization();
+      }
+      private void maybeForceBuilderInitialization() {
+        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+        }
+      }
+      private static Builder create() {
+        return new Builder();
+      }
+
+      public Builder clear() {
+        super.clear();
+        transactionPath_ = "";
+        bitField0_ = (bitField0_ & ~0x00000001);
+        return this;
+      }
+
+      public Builder clone() {
+        return create().mergeFrom(buildPartial());
+      }
+
+      public com.google.protobuf.Descriptors.Descriptor
+          getDescriptorForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_descriptor;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply.getDefaultInstance();
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply build() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply result = buildPartial();
+        if (!result.isInitialized()) {
+          throw newUninitializedMessageException(result);
+        }
+        return result;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply buildPartial() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply result = new org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply(this);
+        int from_bitField0_ = bitField0_;
+        int to_bitField0_ = 0;
+        if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
+          to_bitField0_ |= 0x00000001;
+        }
+        result.transactionPath_ = transactionPath_;
+        result.bitField0_ = to_bitField0_;
+        onBuilt();
+        return result;
+      }
+
+      public Builder mergeFrom(com.google.protobuf.Message other) {
+        if (other instanceof org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply)other);
+        } else {
+          super.mergeFrom(other);
+          return this;
+        }
+      }
+
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply other) {
+        if (other == org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply.getDefaultInstance()) return this;
+        if (other.hasTransactionPath()) {
+          bitField0_ |= 0x00000001;
+          transactionPath_ = other.transactionPath_;
+          onChanged();
+        }
+        this.mergeUnknownFields(other.getUnknownFields());
+        return this;
+      }
+
+      public final boolean isInitialized() {
+        if (!hasTransactionPath()) {
+
+          return false;
+        }
+        return true;
+      }
+
+      public Builder mergeFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws java.io.IOException {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply parsedMessage = null;
+        try {
+          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.CreateTransactionReply) e.getUnfinishedMessage();
+          throw e;
+        } finally {
+          if (parsedMessage != null) {
+            mergeFrom(parsedMessage);
+          }
+        }
+        return this;
+      }
+      private int bitField0_;
+
+      // required string transactionPath = 1;
+      private java.lang.Object transactionPath_ = "";
+      /**
+       * <code>required string transactionPath = 1;</code>
+       */
+      public boolean hasTransactionPath() {
+        return ((bitField0_ & 0x00000001) == 0x00000001);
+      }
+      /**
+       * <code>required string transactionPath = 1;</code>
+       */
+      public java.lang.String getTransactionPath() {
+        java.lang.Object ref = transactionPath_;
+        if (!(ref instanceof java.lang.String)) {
+          java.lang.String s = ((com.google.protobuf.ByteString) ref)
+              .toStringUtf8();
+          transactionPath_ = s;
+          return s;
+        } else {
+          return (java.lang.String) ref;
+        }
+      }
+      /**
+       * <code>required string transactionPath = 1;</code>
+       */
+      public com.google.protobuf.ByteString
+          getTransactionPathBytes() {
+        java.lang.Object ref = transactionPath_;
+        if (ref instanceof String) {
+          com.google.protobuf.ByteString b =
+              com.google.protobuf.ByteString.copyFromUtf8(
+                  (java.lang.String) ref);
+          transactionPath_ = b;
+          return b;
+        } else {
+          return (com.google.protobuf.ByteString) ref;
+        }
+      }
+      /**
+       * <code>required string transactionPath = 1;</code>
+       */
+      public Builder setTransactionPath(
+          java.lang.String value) {
+        if (value == null) {
+    throw new NullPointerException();
+  }
+  bitField0_ |= 0x00000001;
+        transactionPath_ = value;
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>required string transactionPath = 1;</code>
+       */
+      public Builder clearTransactionPath() {
+        bitField0_ = (bitField0_ & ~0x00000001);
+        transactionPath_ = getDefaultInstance().getTransactionPath();
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>required string transactionPath = 1;</code>
+       */
+      public Builder setTransactionPathBytes(
+          com.google.protobuf.ByteString value) {
+        if (value == null) {
+    throw new NullPointerException();
+  }
+  bitField0_ |= 0x00000001;
+        transactionPath_ = value;
+        onChanged();
+        return this;
+      }
+
+      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.CreateTransactionReply)
+    }
+
+    static {
+      defaultInstance = new CreateTransactionReply(true);
+      defaultInstance.initFields();
+    }
+
+    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.CreateTransactionReply)
+  }
+
+  public interface ReadyTransactionOrBuilder
+      extends com.google.protobuf.MessageOrBuilder {
+  }
+  /**
+   * Protobuf type {@code org.opendaylight.controller.mdsal.ReadyTransaction}
+   */
+  public static final class ReadyTransaction extends
+      com.google.protobuf.GeneratedMessage
+      implements ReadyTransactionOrBuilder {
+    // Use ReadyTransaction.newBuilder() to construct.
+    private ReadyTransaction(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
+      super(builder);
+      this.unknownFields = builder.getUnknownFields();
+    }
+    private ReadyTransaction(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+    private static final ReadyTransaction defaultInstance;
+    public static ReadyTransaction getDefaultInstance() {
+      return defaultInstance;
+    }
+
+    public ReadyTransaction getDefaultInstanceForType() {
+      return defaultInstance;
+    }
+
+    private final com.google.protobuf.UnknownFieldSet unknownFields;
+    @java.lang.Override
+    public final com.google.protobuf.UnknownFieldSet
+        getUnknownFields() {
+      return this.unknownFields;
+    }
+    private ReadyTransaction(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      initFields();
+      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+          com.google.protobuf.UnknownFieldSet.newBuilder();
+      try {
+        boolean done = false;
+        while (!done) {
+          int tag = input.readTag();
+          switch (tag) {
+            case 0:
+              done = true;
+              break;
+            default: {
+              if (!parseUnknownField(input, unknownFields,
+                                     extensionRegistry, tag)) {
+                done = true;
+              }
+              break;
+            }
+          }
+        }
+      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+        throw e.setUnfinishedMessage(this);
+      } catch (java.io.IOException e) {
+        throw new com.google.protobuf.InvalidProtocolBufferException(
+            e.getMessage()).setUnfinishedMessage(this);
+      } finally {
+        this.unknownFields = unknownFields.build();
+        makeExtensionsImmutable();
+      }
+    }
+    public static final com.google.protobuf.Descriptors.Descriptor
+        getDescriptor() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_descriptor;
+    }
+
+    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+        internalGetFieldAccessorTable() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_fieldAccessorTable
+          .ensureFieldAccessorsInitialized(
+              org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction.Builder.class);
+    }
+
+    public static com.google.protobuf.Parser<ReadyTransaction> PARSER =
+        new com.google.protobuf.AbstractParser<ReadyTransaction>() {
+      public ReadyTransaction parsePartialFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws com.google.protobuf.InvalidProtocolBufferException {
+        return new ReadyTransaction(input, extensionRegistry);
+      }
+    };
+
+    @java.lang.Override
+    public com.google.protobuf.Parser<ReadyTransaction> getParserForType() {
+      return PARSER;
+    }
+
+    private void initFields() {
+    }
+    private byte memoizedIsInitialized = -1;
+    public final boolean isInitialized() {
+      byte isInitialized = memoizedIsInitialized;
+      if (isInitialized != -1) return isInitialized == 1;
+
+      memoizedIsInitialized = 1;
+      return true;
+    }
+
+    public void writeTo(com.google.protobuf.CodedOutputStream output)
+                        throws java.io.IOException {
+      getSerializedSize();
+      getUnknownFields().writeTo(output);
+    }
+
+    private int memoizedSerializedSize = -1;
+    public int getSerializedSize() {
+      int size = memoizedSerializedSize;
+      if (size != -1) return size;
+
+      size = 0;
+      size += getUnknownFields().getSerializedSize();
+      memoizedSerializedSize = size;
+      return size;
+    }
+
+    private static final long serialVersionUID = 0L;
+    @java.lang.Override
+    protected java.lang.Object writeReplace()
+        throws java.io.ObjectStreamException {
+      return super.writeReplace();
+    }
+
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction parseFrom(
+        com.google.protobuf.ByteString data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction parseFrom(
+        com.google.protobuf.ByteString data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction parseFrom(byte[] data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction parseFrom(
+        byte[] data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction parseFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction parseFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction parseDelimitedFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction parseDelimitedFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction parseFrom(
+        com.google.protobuf.CodedInputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction parseFrom(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+
+    public static Builder newBuilder() { return Builder.create(); }
+    public Builder newBuilderForType() { return newBuilder(); }
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction prototype) {
+      return newBuilder().mergeFrom(prototype);
+    }
+    public Builder toBuilder() { return newBuilder(this); }
+
+    @java.lang.Override
+    protected Builder newBuilderForType(
+        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+      Builder builder = new Builder(parent);
+      return builder;
+    }
+    /**
+     * Protobuf type {@code org.opendaylight.controller.mdsal.ReadyTransaction}
+     */
+    public static final class Builder extends
+        com.google.protobuf.GeneratedMessage.Builder<Builder>
+       implements org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionOrBuilder {
+      public static final com.google.protobuf.Descriptors.Descriptor
+          getDescriptor() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_descriptor;
+      }
+
+      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+          internalGetFieldAccessorTable() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_fieldAccessorTable
+            .ensureFieldAccessorsInitialized(
+                org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction.Builder.class);
+      }
+
+      // Construct using org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction.newBuilder()
+      private Builder() {
+        maybeForceBuilderInitialization();
+      }
+
+      private Builder(
+          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+        super(parent);
+        maybeForceBuilderInitialization();
+      }
+      private void maybeForceBuilderInitialization() {
+        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+        }
+      }
+      private static Builder create() {
+        return new Builder();
+      }
+
+      public Builder clear() {
+        super.clear();
+        return this;
+      }
+
+      public Builder clone() {
+        return create().mergeFrom(buildPartial());
+      }
+
+      public com.google.protobuf.Descriptors.Descriptor
+          getDescriptorForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_descriptor;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction.getDefaultInstance();
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction build() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction result = buildPartial();
+        if (!result.isInitialized()) {
+          throw newUninitializedMessageException(result);
+        }
+        return result;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction buildPartial() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction result = new org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction(this);
+        onBuilt();
+        return result;
+      }
+
+      public Builder mergeFrom(com.google.protobuf.Message other) {
+        if (other instanceof org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction)other);
+        } else {
+          super.mergeFrom(other);
+          return this;
+        }
+      }
+
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction other) {
+        if (other == org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction.getDefaultInstance()) return this;
+        this.mergeUnknownFields(other.getUnknownFields());
+        return this;
+      }
+
+      public final boolean isInitialized() {
+        return true;
+      }
+
+      public Builder mergeFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws java.io.IOException {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction parsedMessage = null;
+        try {
+          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransaction) e.getUnfinishedMessage();
+          throw e;
+        } finally {
+          if (parsedMessage != null) {
+            mergeFrom(parsedMessage);
+          }
+        }
+        return this;
+      }
+
+      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.ReadyTransaction)
+    }
+
+    static {
+      defaultInstance = new ReadyTransaction(true);
+      defaultInstance.initFields();
+    }
+
+    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.ReadyTransaction)
+  }
+
+  public interface ReadyTransactionReplyOrBuilder
+      extends com.google.protobuf.MessageOrBuilder {
+
+    // required string actorPath = 1;
+    /**
+     * <code>required string actorPath = 1;</code>
+     */
+    boolean hasActorPath();
+    /**
+     * <code>required string actorPath = 1;</code>
+     */
+    java.lang.String getActorPath();
+    /**
+     * <code>required string actorPath = 1;</code>
+     */
+    com.google.protobuf.ByteString
+        getActorPathBytes();
+  }
+  /**
+   * Protobuf type {@code org.opendaylight.controller.mdsal.ReadyTransactionReply}
+   */
+  public static final class ReadyTransactionReply extends
+      com.google.protobuf.GeneratedMessage
+      implements ReadyTransactionReplyOrBuilder {
+    // Use ReadyTransactionReply.newBuilder() to construct.
+    private ReadyTransactionReply(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
+      super(builder);
+      this.unknownFields = builder.getUnknownFields();
+    }
+    private ReadyTransactionReply(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+    private static final ReadyTransactionReply defaultInstance;
+    public static ReadyTransactionReply getDefaultInstance() {
+      return defaultInstance;
+    }
+
+    public ReadyTransactionReply getDefaultInstanceForType() {
+      return defaultInstance;
+    }
+
+    private final com.google.protobuf.UnknownFieldSet unknownFields;
+    @java.lang.Override
+    public final com.google.protobuf.UnknownFieldSet
+        getUnknownFields() {
+      return this.unknownFields;
+    }
+    private ReadyTransactionReply(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      initFields();
+      int mutable_bitField0_ = 0;
+      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+          com.google.protobuf.UnknownFieldSet.newBuilder();
+      try {
+        boolean done = false;
+        while (!done) {
+          int tag = input.readTag();
+          switch (tag) {
+            case 0:
+              done = true;
+              break;
+            default: {
+              if (!parseUnknownField(input, unknownFields,
+                                     extensionRegistry, tag)) {
+                done = true;
+              }
+              break;
+            }
+            case 10: {
+              bitField0_ |= 0x00000001;
+              actorPath_ = input.readBytes();
+              break;
+            }
+          }
+        }
+      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+        throw e.setUnfinishedMessage(this);
+      } catch (java.io.IOException e) {
+        throw new com.google.protobuf.InvalidProtocolBufferException(
+            e.getMessage()).setUnfinishedMessage(this);
+      } finally {
+        this.unknownFields = unknownFields.build();
+        makeExtensionsImmutable();
+      }
+    }
+    public static final com.google.protobuf.Descriptors.Descriptor
+        getDescriptor() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadyTransactionReply_descriptor;
+    }
+
+    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+        internalGetFieldAccessorTable() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadyTransactionReply_fieldAccessorTable
+          .ensureFieldAccessorsInitialized(
+              org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply.Builder.class);
+    }
+
+    public static com.google.protobuf.Parser<ReadyTransactionReply> PARSER =
+        new com.google.protobuf.AbstractParser<ReadyTransactionReply>() {
+      public ReadyTransactionReply parsePartialFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws com.google.protobuf.InvalidProtocolBufferException {
+        return new ReadyTransactionReply(input, extensionRegistry);
+      }
+    };
+
+    @java.lang.Override
+    public com.google.protobuf.Parser<ReadyTransactionReply> getParserForType() {
+      return PARSER;
+    }
+
+    private int bitField0_;
+    // required string actorPath = 1;
+    public static final int ACTORPATH_FIELD_NUMBER = 1;
+    private java.lang.Object actorPath_;
+    /**
+     * <code>required string actorPath = 1;</code>
+     */
+    public boolean hasActorPath() {
+      return ((bitField0_ & 0x00000001) == 0x00000001);
+    }
+    /**
+     * <code>required string actorPath = 1;</code>
+     */
+    public java.lang.String getActorPath() {
+      java.lang.Object ref = actorPath_;
+      if (ref instanceof java.lang.String) {
+        return (java.lang.String) ref;
+      } else {
+        com.google.protobuf.ByteString bs =
+            (com.google.protobuf.ByteString) ref;
+        java.lang.String s = bs.toStringUtf8();
+        if (bs.isValidUtf8()) {
+          actorPath_ = s;
+        }
+        return s;
+      }
+    }
+    /**
+     * <code>required string actorPath = 1;</code>
+     */
+    public com.google.protobuf.ByteString
+        getActorPathBytes() {
+      java.lang.Object ref = actorPath_;
+      if (ref instanceof java.lang.String) {
+        com.google.protobuf.ByteString b =
+            com.google.protobuf.ByteString.copyFromUtf8(
+                (java.lang.String) ref);
+        actorPath_ = b;
+        return b;
+      } else {
+        return (com.google.protobuf.ByteString) ref;
+      }
+    }
+
+    private void initFields() {
+      actorPath_ = "";
+    }
+    private byte memoizedIsInitialized = -1;
+    public final boolean isInitialized() {
+      byte isInitialized = memoizedIsInitialized;
+      if (isInitialized != -1) return isInitialized == 1;
+
+      if (!hasActorPath()) {
+        memoizedIsInitialized = 0;
+        return false;
+      }
+      memoizedIsInitialized = 1;
+      return true;
+    }
+
+    public void writeTo(com.google.protobuf.CodedOutputStream output)
+                        throws java.io.IOException {
+      getSerializedSize();
+      if (((bitField0_ & 0x00000001) == 0x00000001)) {
+        output.writeBytes(1, getActorPathBytes());
+      }
+      getUnknownFields().writeTo(output);
+    }
+
+    private int memoizedSerializedSize = -1;
+    public int getSerializedSize() {
+      int size = memoizedSerializedSize;
+      if (size != -1) return size;
+
+      size = 0;
+      if (((bitField0_ & 0x00000001) == 0x00000001)) {
+        size += com.google.protobuf.CodedOutputStream
+          .computeBytesSize(1, getActorPathBytes());
+      }
+      size += getUnknownFields().getSerializedSize();
+      memoizedSerializedSize = size;
+      return size;
+    }
+
+    private static final long serialVersionUID = 0L;
+    @java.lang.Override
+    protected java.lang.Object writeReplace()
+        throws java.io.ObjectStreamException {
+      return super.writeReplace();
+    }
+
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply parseFrom(
+        com.google.protobuf.ByteString data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply parseFrom(
+        com.google.protobuf.ByteString data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply parseFrom(byte[] data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply parseFrom(
+        byte[] data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply parseFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply parseFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply parseDelimitedFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply parseDelimitedFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply parseFrom(
+        com.google.protobuf.CodedInputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply parseFrom(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+
+    public static Builder newBuilder() { return Builder.create(); }
+    public Builder newBuilderForType() { return newBuilder(); }
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply prototype) {
+      return newBuilder().mergeFrom(prototype);
+    }
+    public Builder toBuilder() { return newBuilder(this); }
+
+    @java.lang.Override
+    protected Builder newBuilderForType(
+        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+      Builder builder = new Builder(parent);
+      return builder;
+    }
+    /**
+     * Protobuf type {@code org.opendaylight.controller.mdsal.ReadyTransactionReply}
+     */
+    public static final class Builder extends
+        com.google.protobuf.GeneratedMessage.Builder<Builder>
+       implements org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReplyOrBuilder {
+      public static final com.google.protobuf.Descriptors.Descriptor
+          getDescriptor() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadyTransactionReply_descriptor;
+      }
+
+      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+          internalGetFieldAccessorTable() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadyTransactionReply_fieldAccessorTable
+            .ensureFieldAccessorsInitialized(
+                org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply.Builder.class);
+      }
+
+      // Construct using org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply.newBuilder()
+      private Builder() {
+        maybeForceBuilderInitialization();
+      }
+
+      private Builder(
+          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+        super(parent);
+        maybeForceBuilderInitialization();
+      }
+      private void maybeForceBuilderInitialization() {
+        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+        }
+      }
+      private static Builder create() {
+        return new Builder();
+      }
+
+      public Builder clear() {
+        super.clear();
+        actorPath_ = "";
+        bitField0_ = (bitField0_ & ~0x00000001);
+        return this;
+      }
+
+      public Builder clone() {
+        return create().mergeFrom(buildPartial());
+      }
+
+      public com.google.protobuf.Descriptors.Descriptor
+          getDescriptorForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadyTransactionReply_descriptor;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply.getDefaultInstance();
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply build() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply result = buildPartial();
+        if (!result.isInitialized()) {
+          throw newUninitializedMessageException(result);
+        }
+        return result;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply buildPartial() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply result = new org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply(this);
+        int from_bitField0_ = bitField0_;
+        int to_bitField0_ = 0;
+        if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
+          to_bitField0_ |= 0x00000001;
+        }
+        result.actorPath_ = actorPath_;
+        result.bitField0_ = to_bitField0_;
+        onBuilt();
+        return result;
+      }
+
+      public Builder mergeFrom(com.google.protobuf.Message other) {
+        if (other instanceof org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply)other);
+        } else {
+          super.mergeFrom(other);
+          return this;
+        }
+      }
+
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply other) {
+        if (other == org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply.getDefaultInstance()) return this;
+        if (other.hasActorPath()) {
+          bitField0_ |= 0x00000001;
+          actorPath_ = other.actorPath_;
+          onChanged();
+        }
+        this.mergeUnknownFields(other.getUnknownFields());
+        return this;
+      }
+
+      public final boolean isInitialized() {
+        if (!hasActorPath()) {
+
+          return false;
+        }
+        return true;
+      }
+
+      public Builder mergeFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws java.io.IOException {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply parsedMessage = null;
+        try {
+          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadyTransactionReply) e.getUnfinishedMessage();
+          throw e;
+        } finally {
+          if (parsedMessage != null) {
+            mergeFrom(parsedMessage);
+          }
+        }
+        return this;
+      }
+      private int bitField0_;
+
+      // required string actorPath = 1;
+      private java.lang.Object actorPath_ = "";
+      /**
+       * <code>required string actorPath = 1;</code>
+       */
+      public boolean hasActorPath() {
+        return ((bitField0_ & 0x00000001) == 0x00000001);
+      }
+      /**
+       * <code>required string actorPath = 1;</code>
+       */
+      public java.lang.String getActorPath() {
+        java.lang.Object ref = actorPath_;
+        if (!(ref instanceof java.lang.String)) {
+          java.lang.String s = ((com.google.protobuf.ByteString) ref)
+              .toStringUtf8();
+          actorPath_ = s;
+          return s;
+        } else {
+          return (java.lang.String) ref;
+        }
+      }
+      /**
+       * <code>required string actorPath = 1;</code>
+       */
+      public com.google.protobuf.ByteString
+          getActorPathBytes() {
+        java.lang.Object ref = actorPath_;
+        if (ref instanceof String) {
+          com.google.protobuf.ByteString b =
+              com.google.protobuf.ByteString.copyFromUtf8(
+                  (java.lang.String) ref);
+          actorPath_ = b;
+          return b;
+        } else {
+          return (com.google.protobuf.ByteString) ref;
+        }
+      }
+      /**
+       * <code>required string actorPath = 1;</code>
+       */
+      public Builder setActorPath(
+          java.lang.String value) {
+        if (value == null) {
+    throw new NullPointerException();
+  }
+  bitField0_ |= 0x00000001;
+        actorPath_ = value;
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>required string actorPath = 1;</code>
+       */
+      public Builder clearActorPath() {
+        bitField0_ = (bitField0_ & ~0x00000001);
+        actorPath_ = getDefaultInstance().getActorPath();
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>required string actorPath = 1;</code>
+       */
+      public Builder setActorPathBytes(
+          com.google.protobuf.ByteString value) {
+        if (value == null) {
+    throw new NullPointerException();
+  }
+  bitField0_ |= 0x00000001;
+        actorPath_ = value;
+        onChanged();
+        return this;
+      }
+
+      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.ReadyTransactionReply)
+    }
+
+    static {
+      defaultInstance = new ReadyTransactionReply(true);
+      defaultInstance.initFields();
+    }
+
+    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.ReadyTransactionReply)
+  }
+
+  public interface DeleteDataOrBuilder
+      extends com.google.protobuf.MessageOrBuilder {
+
+    // repeated string instanceIdentifierPathArguments = 1;
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    java.util.List<java.lang.String>
+    getInstanceIdentifierPathArgumentsList();
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    int getInstanceIdentifierPathArgumentsCount();
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    java.lang.String getInstanceIdentifierPathArguments(int index);
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    com.google.protobuf.ByteString
+        getInstanceIdentifierPathArgumentsBytes(int index);
+  }
+  /**
+   * Protobuf type {@code org.opendaylight.controller.mdsal.DeleteData}
+   */
+  public static final class DeleteData extends
+      com.google.protobuf.GeneratedMessage
+      implements DeleteDataOrBuilder {
+    // Use DeleteData.newBuilder() to construct.
+    private DeleteData(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
+      super(builder);
+      this.unknownFields = builder.getUnknownFields();
+    }
+    private DeleteData(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+    private static final DeleteData defaultInstance;
+    public static DeleteData getDefaultInstance() {
+      return defaultInstance;
+    }
+
+    public DeleteData getDefaultInstanceForType() {
+      return defaultInstance;
+    }
+
+    private final com.google.protobuf.UnknownFieldSet unknownFields;
+    @java.lang.Override
+    public final com.google.protobuf.UnknownFieldSet
+        getUnknownFields() {
+      return this.unknownFields;
+    }
+    private DeleteData(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      initFields();
+      int mutable_bitField0_ = 0;
+      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+          com.google.protobuf.UnknownFieldSet.newBuilder();
+      try {
+        boolean done = false;
+        while (!done) {
+          int tag = input.readTag();
+          switch (tag) {
+            case 0:
+              done = true;
+              break;
+            default: {
+              if (!parseUnknownField(input, unknownFields,
+                                     extensionRegistry, tag)) {
+                done = true;
+              }
+              break;
+            }
+            case 10: {
+              if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
+                instanceIdentifierPathArguments_ = new com.google.protobuf.LazyStringArrayList();
+                mutable_bitField0_ |= 0x00000001;
+              }
+              instanceIdentifierPathArguments_.add(input.readBytes());
+              break;
+            }
+          }
+        }
+      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+        throw e.setUnfinishedMessage(this);
+      } catch (java.io.IOException e) {
+        throw new com.google.protobuf.InvalidProtocolBufferException(
+            e.getMessage()).setUnfinishedMessage(this);
+      } finally {
+        if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
+          instanceIdentifierPathArguments_ = new com.google.protobuf.UnmodifiableLazyStringList(instanceIdentifierPathArguments_);
+        }
+        this.unknownFields = unknownFields.build();
+        makeExtensionsImmutable();
+      }
+    }
+    public static final com.google.protobuf.Descriptors.Descriptor
+        getDescriptor() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_DeleteData_descriptor;
+    }
+
+    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+        internalGetFieldAccessorTable() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_DeleteData_fieldAccessorTable
+          .ensureFieldAccessorsInitialized(
+              org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData.Builder.class);
+    }
+
+    public static com.google.protobuf.Parser<DeleteData> PARSER =
+        new com.google.protobuf.AbstractParser<DeleteData>() {
+      public DeleteData parsePartialFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws com.google.protobuf.InvalidProtocolBufferException {
+        return new DeleteData(input, extensionRegistry);
+      }
+    };
+
+    @java.lang.Override
+    public com.google.protobuf.Parser<DeleteData> getParserForType() {
+      return PARSER;
+    }
+
+    // repeated string instanceIdentifierPathArguments = 1;
+    public static final int INSTANCEIDENTIFIERPATHARGUMENTS_FIELD_NUMBER = 1;
+    private com.google.protobuf.LazyStringList instanceIdentifierPathArguments_;
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    public java.util.List<java.lang.String>
+        getInstanceIdentifierPathArgumentsList() {
+      return instanceIdentifierPathArguments_;
+    }
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    public int getInstanceIdentifierPathArgumentsCount() {
+      return instanceIdentifierPathArguments_.size();
+    }
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    public java.lang.String getInstanceIdentifierPathArguments(int index) {
+      return instanceIdentifierPathArguments_.get(index);
+    }
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    public com.google.protobuf.ByteString
+        getInstanceIdentifierPathArgumentsBytes(int index) {
+      return instanceIdentifierPathArguments_.getByteString(index);
+    }
+
+    private void initFields() {
+      instanceIdentifierPathArguments_ = com.google.protobuf.LazyStringArrayList.EMPTY;
+    }
+    private byte memoizedIsInitialized = -1;
+    public final boolean isInitialized() {
+      byte isInitialized = memoizedIsInitialized;
+      if (isInitialized != -1) return isInitialized == 1;
+
+      memoizedIsInitialized = 1;
+      return true;
+    }
+
+    public void writeTo(com.google.protobuf.CodedOutputStream output)
+                        throws java.io.IOException {
+      getSerializedSize();
+      for (int i = 0; i < instanceIdentifierPathArguments_.size(); i++) {
+        output.writeBytes(1, instanceIdentifierPathArguments_.getByteString(i));
+      }
+      getUnknownFields().writeTo(output);
+    }
+
+    private int memoizedSerializedSize = -1;
+    public int getSerializedSize() {
+      int size = memoizedSerializedSize;
+      if (size != -1) return size;
+
+      size = 0;
+      {
+        int dataSize = 0;
+        for (int i = 0; i < instanceIdentifierPathArguments_.size(); i++) {
+          dataSize += com.google.protobuf.CodedOutputStream
+            .computeBytesSizeNoTag(instanceIdentifierPathArguments_.getByteString(i));
+        }
+        size += dataSize;
+        size += 1 * getInstanceIdentifierPathArgumentsList().size();
+      }
+      size += getUnknownFields().getSerializedSize();
+      memoizedSerializedSize = size;
+      return size;
+    }
+
+    private static final long serialVersionUID = 0L;
+    @java.lang.Override
+    protected java.lang.Object writeReplace()
+        throws java.io.ObjectStreamException {
+      return super.writeReplace();
+    }
+
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData parseFrom(
+        com.google.protobuf.ByteString data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData parseFrom(
+        com.google.protobuf.ByteString data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData parseFrom(byte[] data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData parseFrom(
+        byte[] data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData parseFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData parseFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData parseDelimitedFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData parseDelimitedFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData parseFrom(
+        com.google.protobuf.CodedInputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData parseFrom(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+
+    public static Builder newBuilder() { return Builder.create(); }
+    public Builder newBuilderForType() { return newBuilder(); }
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData prototype) {
+      return newBuilder().mergeFrom(prototype);
+    }
+    public Builder toBuilder() { return newBuilder(this); }
+
+    @java.lang.Override
+    protected Builder newBuilderForType(
+        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+      Builder builder = new Builder(parent);
+      return builder;
+    }
+    /**
+     * Protobuf type {@code org.opendaylight.controller.mdsal.DeleteData}
+     */
+    public static final class Builder extends
+        com.google.protobuf.GeneratedMessage.Builder<Builder>
+       implements org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataOrBuilder {
+      public static final com.google.protobuf.Descriptors.Descriptor
+          getDescriptor() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_DeleteData_descriptor;
+      }
+
+      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+          internalGetFieldAccessorTable() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_DeleteData_fieldAccessorTable
+            .ensureFieldAccessorsInitialized(
+                org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData.Builder.class);
+      }
+
+      // Construct using org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData.newBuilder()
+      private Builder() {
+        maybeForceBuilderInitialization();
+      }
+
+      private Builder(
+          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+        super(parent);
+        maybeForceBuilderInitialization();
+      }
+      private void maybeForceBuilderInitialization() {
+        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+        }
+      }
+      private static Builder create() {
+        return new Builder();
+      }
+
+      public Builder clear() {
+        super.clear();
+        instanceIdentifierPathArguments_ = com.google.protobuf.LazyStringArrayList.EMPTY;
+        bitField0_ = (bitField0_ & ~0x00000001);
+        return this;
+      }
+
+      public Builder clone() {
+        return create().mergeFrom(buildPartial());
+      }
+
+      public com.google.protobuf.Descriptors.Descriptor
+          getDescriptorForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_DeleteData_descriptor;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData.getDefaultInstance();
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData build() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData result = buildPartial();
+        if (!result.isInitialized()) {
+          throw newUninitializedMessageException(result);
+        }
+        return result;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData buildPartial() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData result = new org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData(this);
+        int from_bitField0_ = bitField0_;
+        if (((bitField0_ & 0x00000001) == 0x00000001)) {
+          instanceIdentifierPathArguments_ = new com.google.protobuf.UnmodifiableLazyStringList(
+              instanceIdentifierPathArguments_);
+          bitField0_ = (bitField0_ & ~0x00000001);
+        }
+        result.instanceIdentifierPathArguments_ = instanceIdentifierPathArguments_;
+        onBuilt();
+        return result;
+      }
+
+      public Builder mergeFrom(com.google.protobuf.Message other) {
+        if (other instanceof org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData)other);
+        } else {
+          super.mergeFrom(other);
+          return this;
+        }
+      }
+
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData other) {
+        if (other == org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData.getDefaultInstance()) return this;
+        if (!other.instanceIdentifierPathArguments_.isEmpty()) {
+          if (instanceIdentifierPathArguments_.isEmpty()) {
+            instanceIdentifierPathArguments_ = other.instanceIdentifierPathArguments_;
+            bitField0_ = (bitField0_ & ~0x00000001);
+          } else {
+            ensureInstanceIdentifierPathArgumentsIsMutable();
+            instanceIdentifierPathArguments_.addAll(other.instanceIdentifierPathArguments_);
+          }
+          onChanged();
+        }
+        this.mergeUnknownFields(other.getUnknownFields());
+        return this;
+      }
+
+      public final boolean isInitialized() {
+        return true;
+      }
+
+      public Builder mergeFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws java.io.IOException {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData parsedMessage = null;
+        try {
+          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteData) e.getUnfinishedMessage();
+          throw e;
+        } finally {
+          if (parsedMessage != null) {
+            mergeFrom(parsedMessage);
+          }
+        }
+        return this;
+      }
+      private int bitField0_;
+
+      // repeated string instanceIdentifierPathArguments = 1;
+      private com.google.protobuf.LazyStringList instanceIdentifierPathArguments_ = com.google.protobuf.LazyStringArrayList.EMPTY;
+      private void ensureInstanceIdentifierPathArgumentsIsMutable() {
+        if (!((bitField0_ & 0x00000001) == 0x00000001)) {
+          instanceIdentifierPathArguments_ = new com.google.protobuf.LazyStringArrayList(instanceIdentifierPathArguments_);
+          bitField0_ |= 0x00000001;
+         }
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public java.util.List<java.lang.String>
+          getInstanceIdentifierPathArgumentsList() {
+        return java.util.Collections.unmodifiableList(instanceIdentifierPathArguments_);
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public int getInstanceIdentifierPathArgumentsCount() {
+        return instanceIdentifierPathArguments_.size();
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public java.lang.String getInstanceIdentifierPathArguments(int index) {
+        return instanceIdentifierPathArguments_.get(index);
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public com.google.protobuf.ByteString
+          getInstanceIdentifierPathArgumentsBytes(int index) {
+        return instanceIdentifierPathArguments_.getByteString(index);
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public Builder setInstanceIdentifierPathArguments(
+          int index, java.lang.String value) {
+        if (value == null) {
+    throw new NullPointerException();
+  }
+  ensureInstanceIdentifierPathArgumentsIsMutable();
+        instanceIdentifierPathArguments_.set(index, value);
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public Builder addInstanceIdentifierPathArguments(
+          java.lang.String value) {
+        if (value == null) {
+    throw new NullPointerException();
+  }
+  ensureInstanceIdentifierPathArgumentsIsMutable();
+        instanceIdentifierPathArguments_.add(value);
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public Builder addAllInstanceIdentifierPathArguments(
+          java.lang.Iterable<java.lang.String> values) {
+        ensureInstanceIdentifierPathArgumentsIsMutable();
+        super.addAll(values, instanceIdentifierPathArguments_);
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public Builder clearInstanceIdentifierPathArguments() {
+        instanceIdentifierPathArguments_ = com.google.protobuf.LazyStringArrayList.EMPTY;
+        bitField0_ = (bitField0_ & ~0x00000001);
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public Builder addInstanceIdentifierPathArgumentsBytes(
+          com.google.protobuf.ByteString value) {
+        if (value == null) {
+    throw new NullPointerException();
+  }
+  ensureInstanceIdentifierPathArgumentsIsMutable();
+        instanceIdentifierPathArguments_.add(value);
+        onChanged();
+        return this;
+      }
+
+      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.DeleteData)
+    }
+
+    static {
+      defaultInstance = new DeleteData(true);
+      defaultInstance.initFields();
+    }
+
+    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.DeleteData)
+  }
+
+  public interface DeleteDataReplyOrBuilder
+      extends com.google.protobuf.MessageOrBuilder {
+  }
+  /**
+   * Protobuf type {@code org.opendaylight.controller.mdsal.DeleteDataReply}
+   */
+  public static final class DeleteDataReply extends
+      com.google.protobuf.GeneratedMessage
+      implements DeleteDataReplyOrBuilder {
+    // Use DeleteDataReply.newBuilder() to construct.
+    private DeleteDataReply(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
+      super(builder);
+      this.unknownFields = builder.getUnknownFields();
+    }
+    private DeleteDataReply(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+    private static final DeleteDataReply defaultInstance;
+    public static DeleteDataReply getDefaultInstance() {
+      return defaultInstance;
+    }
+
+    public DeleteDataReply getDefaultInstanceForType() {
+      return defaultInstance;
+    }
+
+    private final com.google.protobuf.UnknownFieldSet unknownFields;
+    @java.lang.Override
+    public final com.google.protobuf.UnknownFieldSet
+        getUnknownFields() {
+      return this.unknownFields;
+    }
+    private DeleteDataReply(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      initFields();
+      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+          com.google.protobuf.UnknownFieldSet.newBuilder();
+      try {
+        boolean done = false;
+        while (!done) {
+          int tag = input.readTag();
+          switch (tag) {
+            case 0:
+              done = true;
+              break;
+            default: {
+              if (!parseUnknownField(input, unknownFields,
+                                     extensionRegistry, tag)) {
+                done = true;
+              }
+              break;
+            }
+          }
+        }
+      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+        throw e.setUnfinishedMessage(this);
+      } catch (java.io.IOException e) {
+        throw new com.google.protobuf.InvalidProtocolBufferException(
+            e.getMessage()).setUnfinishedMessage(this);
+      } finally {
+        this.unknownFields = unknownFields.build();
+        makeExtensionsImmutable();
+      }
+    }
+    public static final com.google.protobuf.Descriptors.Descriptor
+        getDescriptor() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_DeleteDataReply_descriptor;
+    }
+
+    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+        internalGetFieldAccessorTable() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_DeleteDataReply_fieldAccessorTable
+          .ensureFieldAccessorsInitialized(
+              org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply.Builder.class);
+    }
+
+    public static com.google.protobuf.Parser<DeleteDataReply> PARSER =
+        new com.google.protobuf.AbstractParser<DeleteDataReply>() {
+      public DeleteDataReply parsePartialFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws com.google.protobuf.InvalidProtocolBufferException {
+        return new DeleteDataReply(input, extensionRegistry);
+      }
+    };
+
+    @java.lang.Override
+    public com.google.protobuf.Parser<DeleteDataReply> getParserForType() {
+      return PARSER;
+    }
+
+    private void initFields() {
+    }
+    private byte memoizedIsInitialized = -1;
+    public final boolean isInitialized() {
+      byte isInitialized = memoizedIsInitialized;
+      if (isInitialized != -1) return isInitialized == 1;
+
+      memoizedIsInitialized = 1;
+      return true;
+    }
+
+    public void writeTo(com.google.protobuf.CodedOutputStream output)
+                        throws java.io.IOException {
+      getSerializedSize();
+      getUnknownFields().writeTo(output);
+    }
+
+    private int memoizedSerializedSize = -1;
+    public int getSerializedSize() {
+      int size = memoizedSerializedSize;
+      if (size != -1) return size;
+
+      size = 0;
+      size += getUnknownFields().getSerializedSize();
+      memoizedSerializedSize = size;
+      return size;
+    }
+
+    private static final long serialVersionUID = 0L;
+    @java.lang.Override
+    protected java.lang.Object writeReplace()
+        throws java.io.ObjectStreamException {
+      return super.writeReplace();
+    }
+
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply parseFrom(
+        com.google.protobuf.ByteString data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply parseFrom(
+        com.google.protobuf.ByteString data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply parseFrom(byte[] data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply parseFrom(
+        byte[] data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply parseFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply parseFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply parseDelimitedFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply parseDelimitedFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply parseFrom(
+        com.google.protobuf.CodedInputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply parseFrom(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+
+    public static Builder newBuilder() { return Builder.create(); }
+    public Builder newBuilderForType() { return newBuilder(); }
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply prototype) {
+      return newBuilder().mergeFrom(prototype);
+    }
+    public Builder toBuilder() { return newBuilder(this); }
+
+    @java.lang.Override
+    protected Builder newBuilderForType(
+        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+      Builder builder = new Builder(parent);
+      return builder;
+    }
+    /**
+     * Protobuf type {@code org.opendaylight.controller.mdsal.DeleteDataReply}
+     */
+    public static final class Builder extends
+        com.google.protobuf.GeneratedMessage.Builder<Builder>
+       implements org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReplyOrBuilder {
+      public static final com.google.protobuf.Descriptors.Descriptor
+          getDescriptor() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_DeleteDataReply_descriptor;
+      }
+
+      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+          internalGetFieldAccessorTable() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_DeleteDataReply_fieldAccessorTable
+            .ensureFieldAccessorsInitialized(
+                org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply.Builder.class);
+      }
+
+      // Construct using org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply.newBuilder()
+      private Builder() {
+        maybeForceBuilderInitialization();
+      }
+
+      private Builder(
+          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+        super(parent);
+        maybeForceBuilderInitialization();
+      }
+      private void maybeForceBuilderInitialization() {
+        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+        }
+      }
+      private static Builder create() {
+        return new Builder();
+      }
+
+      public Builder clear() {
+        super.clear();
+        return this;
+      }
+
+      public Builder clone() {
+        return create().mergeFrom(buildPartial());
+      }
+
+      public com.google.protobuf.Descriptors.Descriptor
+          getDescriptorForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_DeleteDataReply_descriptor;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply.getDefaultInstance();
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply build() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply result = buildPartial();
+        if (!result.isInitialized()) {
+          throw newUninitializedMessageException(result);
+        }
+        return result;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply buildPartial() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply result = new org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply(this);
+        onBuilt();
+        return result;
+      }
+
+      public Builder mergeFrom(com.google.protobuf.Message other) {
+        if (other instanceof org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply)other);
+        } else {
+          super.mergeFrom(other);
+          return this;
+        }
+      }
+
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply other) {
+        if (other == org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply.getDefaultInstance()) return this;
+        this.mergeUnknownFields(other.getUnknownFields());
+        return this;
+      }
+
+      public final boolean isInitialized() {
+        return true;
+      }
+
+      public Builder mergeFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws java.io.IOException {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply parsedMessage = null;
+        try {
+          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.DeleteDataReply) e.getUnfinishedMessage();
+          throw e;
+        } finally {
+          if (parsedMessage != null) {
+            mergeFrom(parsedMessage);
+          }
+        }
+        return this;
+      }
+
+      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.DeleteDataReply)
+    }
+
+    static {
+      defaultInstance = new DeleteDataReply(true);
+      defaultInstance.initFields();
+    }
+
+    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.DeleteDataReply)
+  }
+
+  public interface ReadDataOrBuilder
+      extends com.google.protobuf.MessageOrBuilder {
+
+    // required string instanceIdentifierPathArguments = 1;
+    /**
+     * <code>required string instanceIdentifierPathArguments = 1;</code>
+     */
+    boolean hasInstanceIdentifierPathArguments();
+    /**
+     * <code>required string instanceIdentifierPathArguments = 1;</code>
+     */
+    java.lang.String getInstanceIdentifierPathArguments();
+    /**
+     * <code>required string instanceIdentifierPathArguments = 1;</code>
+     */
+    com.google.protobuf.ByteString
+        getInstanceIdentifierPathArgumentsBytes();
+  }
+  /**
+   * Protobuf type {@code org.opendaylight.controller.mdsal.ReadData}
+   */
+  public static final class ReadData extends
+      com.google.protobuf.GeneratedMessage
+      implements ReadDataOrBuilder {
+    // Use ReadData.newBuilder() to construct.
+    private ReadData(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
+      super(builder);
+      this.unknownFields = builder.getUnknownFields();
+    }
+    private ReadData(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+    private static final ReadData defaultInstance;
+    public static ReadData getDefaultInstance() {
+      return defaultInstance;
+    }
+
+    public ReadData getDefaultInstanceForType() {
+      return defaultInstance;
+    }
+
+    private final com.google.protobuf.UnknownFieldSet unknownFields;
+    @java.lang.Override
+    public final com.google.protobuf.UnknownFieldSet
+        getUnknownFields() {
+      return this.unknownFields;
+    }
+    private ReadData(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      initFields();
+      int mutable_bitField0_ = 0;
+      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+          com.google.protobuf.UnknownFieldSet.newBuilder();
+      try {
+        boolean done = false;
+        while (!done) {
+          int tag = input.readTag();
+          switch (tag) {
+            case 0:
+              done = true;
+              break;
+            default: {
+              if (!parseUnknownField(input, unknownFields,
+                                     extensionRegistry, tag)) {
+                done = true;
+              }
+              break;
+            }
+            case 10: {
+              bitField0_ |= 0x00000001;
+              instanceIdentifierPathArguments_ = input.readBytes();
+              break;
+            }
+          }
+        }
+      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+        throw e.setUnfinishedMessage(this);
+      } catch (java.io.IOException e) {
+        throw new com.google.protobuf.InvalidProtocolBufferException(
+            e.getMessage()).setUnfinishedMessage(this);
+      } finally {
+        this.unknownFields = unknownFields.build();
+        makeExtensionsImmutable();
+      }
+    }
+    public static final com.google.protobuf.Descriptors.Descriptor
+        getDescriptor() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadData_descriptor;
+    }
+
+    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+        internalGetFieldAccessorTable() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadData_fieldAccessorTable
+          .ensureFieldAccessorsInitialized(
+              org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData.Builder.class);
+    }
+
+    public static com.google.protobuf.Parser<ReadData> PARSER =
+        new com.google.protobuf.AbstractParser<ReadData>() {
+      public ReadData parsePartialFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws com.google.protobuf.InvalidProtocolBufferException {
+        return new ReadData(input, extensionRegistry);
+      }
+    };
+
+    @java.lang.Override
+    public com.google.protobuf.Parser<ReadData> getParserForType() {
+      return PARSER;
+    }
+
+    private int bitField0_;
+    // required string instanceIdentifierPathArguments = 1;
+    public static final int INSTANCEIDENTIFIERPATHARGUMENTS_FIELD_NUMBER = 1;
+    private java.lang.Object instanceIdentifierPathArguments_;
+    /**
+     * <code>required string instanceIdentifierPathArguments = 1;</code>
+     */
+    public boolean hasInstanceIdentifierPathArguments() {
+      return ((bitField0_ & 0x00000001) == 0x00000001);
+    }
+    /**
+     * <code>required string instanceIdentifierPathArguments = 1;</code>
+     */
+    public java.lang.String getInstanceIdentifierPathArguments() {
+      java.lang.Object ref = instanceIdentifierPathArguments_;
+      if (ref instanceof java.lang.String) {
+        return (java.lang.String) ref;
+      } else {
+        com.google.protobuf.ByteString bs =
+            (com.google.protobuf.ByteString) ref;
+        java.lang.String s = bs.toStringUtf8();
+        if (bs.isValidUtf8()) {
+          instanceIdentifierPathArguments_ = s;
+        }
+        return s;
+      }
+    }
+    /**
+     * <code>required string instanceIdentifierPathArguments = 1;</code>
+     */
+    public com.google.protobuf.ByteString
+        getInstanceIdentifierPathArgumentsBytes() {
+      java.lang.Object ref = instanceIdentifierPathArguments_;
+      if (ref instanceof java.lang.String) {
+        com.google.protobuf.ByteString b =
+            com.google.protobuf.ByteString.copyFromUtf8(
+                (java.lang.String) ref);
+        instanceIdentifierPathArguments_ = b;
+        return b;
+      } else {
+        return (com.google.protobuf.ByteString) ref;
+      }
+    }
+
+    private void initFields() {
+      instanceIdentifierPathArguments_ = "";
+    }
+    private byte memoizedIsInitialized = -1;
+    public final boolean isInitialized() {
+      byte isInitialized = memoizedIsInitialized;
+      if (isInitialized != -1) return isInitialized == 1;
+
+      if (!hasInstanceIdentifierPathArguments()) {
+        memoizedIsInitialized = 0;
+        return false;
+      }
+      memoizedIsInitialized = 1;
+      return true;
+    }
+
+    public void writeTo(com.google.protobuf.CodedOutputStream output)
+                        throws java.io.IOException {
+      getSerializedSize();
+      if (((bitField0_ & 0x00000001) == 0x00000001)) {
+        output.writeBytes(1, getInstanceIdentifierPathArgumentsBytes());
+      }
+      getUnknownFields().writeTo(output);
+    }
+
+    private int memoizedSerializedSize = -1;
+    public int getSerializedSize() {
+      int size = memoizedSerializedSize;
+      if (size != -1) return size;
+
+      size = 0;
+      if (((bitField0_ & 0x00000001) == 0x00000001)) {
+        size += com.google.protobuf.CodedOutputStream
+          .computeBytesSize(1, getInstanceIdentifierPathArgumentsBytes());
+      }
+      size += getUnknownFields().getSerializedSize();
+      memoizedSerializedSize = size;
+      return size;
+    }
+
+    private static final long serialVersionUID = 0L;
+    @java.lang.Override
+    protected java.lang.Object writeReplace()
+        throws java.io.ObjectStreamException {
+      return super.writeReplace();
+    }
+
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData parseFrom(
+        com.google.protobuf.ByteString data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData parseFrom(
+        com.google.protobuf.ByteString data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData parseFrom(byte[] data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData parseFrom(
+        byte[] data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData parseFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData parseFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData parseDelimitedFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData parseDelimitedFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData parseFrom(
+        com.google.protobuf.CodedInputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData parseFrom(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+
+    public static Builder newBuilder() { return Builder.create(); }
+    public Builder newBuilderForType() { return newBuilder(); }
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData prototype) {
+      return newBuilder().mergeFrom(prototype);
+    }
+    public Builder toBuilder() { return newBuilder(this); }
+
+    @java.lang.Override
+    protected Builder newBuilderForType(
+        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+      Builder builder = new Builder(parent);
+      return builder;
+    }
+    /**
+     * Protobuf type {@code org.opendaylight.controller.mdsal.ReadData}
+     */
+    public static final class Builder extends
+        com.google.protobuf.GeneratedMessage.Builder<Builder>
+       implements org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataOrBuilder {
+      public static final com.google.protobuf.Descriptors.Descriptor
+          getDescriptor() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadData_descriptor;
+      }
+
+      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+          internalGetFieldAccessorTable() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadData_fieldAccessorTable
+            .ensureFieldAccessorsInitialized(
+                org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData.Builder.class);
+      }
+
+      // Construct using org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData.newBuilder()
+      private Builder() {
+        maybeForceBuilderInitialization();
+      }
+
+      private Builder(
+          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+        super(parent);
+        maybeForceBuilderInitialization();
+      }
+      private void maybeForceBuilderInitialization() {
+        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+        }
+      }
+      private static Builder create() {
+        return new Builder();
+      }
+
+      public Builder clear() {
+        super.clear();
+        instanceIdentifierPathArguments_ = "";
+        bitField0_ = (bitField0_ & ~0x00000001);
+        return this;
+      }
+
+      public Builder clone() {
+        return create().mergeFrom(buildPartial());
+      }
+
+      public com.google.protobuf.Descriptors.Descriptor
+          getDescriptorForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadData_descriptor;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData.getDefaultInstance();
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData build() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData result = buildPartial();
+        if (!result.isInitialized()) {
+          throw newUninitializedMessageException(result);
+        }
+        return result;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData buildPartial() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData result = new org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData(this);
+        int from_bitField0_ = bitField0_;
+        int to_bitField0_ = 0;
+        if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
+          to_bitField0_ |= 0x00000001;
+        }
+        result.instanceIdentifierPathArguments_ = instanceIdentifierPathArguments_;
+        result.bitField0_ = to_bitField0_;
+        onBuilt();
+        return result;
+      }
+
+      public Builder mergeFrom(com.google.protobuf.Message other) {
+        if (other instanceof org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData)other);
+        } else {
+          super.mergeFrom(other);
+          return this;
+        }
+      }
+
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData other) {
+        if (other == org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData.getDefaultInstance()) return this;
+        if (other.hasInstanceIdentifierPathArguments()) {
+          bitField0_ |= 0x00000001;
+          instanceIdentifierPathArguments_ = other.instanceIdentifierPathArguments_;
+          onChanged();
+        }
+        this.mergeUnknownFields(other.getUnknownFields());
+        return this;
+      }
+
+      public final boolean isInitialized() {
+        if (!hasInstanceIdentifierPathArguments()) {
+
+          return false;
+        }
+        return true;
+      }
+
+      public Builder mergeFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws java.io.IOException {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData parsedMessage = null;
+        try {
+          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadData) e.getUnfinishedMessage();
+          throw e;
+        } finally {
+          if (parsedMessage != null) {
+            mergeFrom(parsedMessage);
+          }
+        }
+        return this;
+      }
+      private int bitField0_;
+
+      // required string instanceIdentifierPathArguments = 1;
+      private java.lang.Object instanceIdentifierPathArguments_ = "";
+      /**
+       * <code>required string instanceIdentifierPathArguments = 1;</code>
+       */
+      public boolean hasInstanceIdentifierPathArguments() {
+        return ((bitField0_ & 0x00000001) == 0x00000001);
+      }
+      /**
+       * <code>required string instanceIdentifierPathArguments = 1;</code>
+       */
+      public java.lang.String getInstanceIdentifierPathArguments() {
+        java.lang.Object ref = instanceIdentifierPathArguments_;
+        if (!(ref instanceof java.lang.String)) {
+          java.lang.String s = ((com.google.protobuf.ByteString) ref)
+              .toStringUtf8();
+          instanceIdentifierPathArguments_ = s;
+          return s;
+        } else {
+          return (java.lang.String) ref;
+        }
+      }
+      /**
+       * <code>required string instanceIdentifierPathArguments = 1;</code>
+       */
+      public com.google.protobuf.ByteString
+          getInstanceIdentifierPathArgumentsBytes() {
+        java.lang.Object ref = instanceIdentifierPathArguments_;
+        if (ref instanceof String) {
+          com.google.protobuf.ByteString b =
+              com.google.protobuf.ByteString.copyFromUtf8(
+                  (java.lang.String) ref);
+          instanceIdentifierPathArguments_ = b;
+          return b;
+        } else {
+          return (com.google.protobuf.ByteString) ref;
+        }
+      }
+      /**
+       * <code>required string instanceIdentifierPathArguments = 1;</code>
+       */
+      public Builder setInstanceIdentifierPathArguments(
+          java.lang.String value) {
+        if (value == null) {
+    throw new NullPointerException();
+  }
+  bitField0_ |= 0x00000001;
+        instanceIdentifierPathArguments_ = value;
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>required string instanceIdentifierPathArguments = 1;</code>
+       */
+      public Builder clearInstanceIdentifierPathArguments() {
+        bitField0_ = (bitField0_ & ~0x00000001);
+        instanceIdentifierPathArguments_ = getDefaultInstance().getInstanceIdentifierPathArguments();
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>required string instanceIdentifierPathArguments = 1;</code>
+       */
+      public Builder setInstanceIdentifierPathArgumentsBytes(
+          com.google.protobuf.ByteString value) {
+        if (value == null) {
+    throw new NullPointerException();
+  }
+  bitField0_ |= 0x00000001;
+        instanceIdentifierPathArguments_ = value;
+        onChanged();
+        return this;
+      }
+
+      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.ReadData)
+    }
+
+    static {
+      defaultInstance = new ReadData(true);
+      defaultInstance.initFields();
+    }
+
+    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.ReadData)
+  }
+
+  public interface ReadDataReplyOrBuilder
+      extends com.google.protobuf.MessageOrBuilder {
+
+    // required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 1;
+    /**
+     * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 1;</code>
+     */
+    boolean hasNormalizedNode();
+    /**
+     * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 1;</code>
+     */
+    org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml getNormalizedNode();
+    /**
+     * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 1;</code>
+     */
+    org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXmlOrBuilder getNormalizedNodeOrBuilder();
+  }
+  /**
+   * Protobuf type {@code org.opendaylight.controller.mdsal.ReadDataReply}
+   */
+  public static final class ReadDataReply extends
+      com.google.protobuf.GeneratedMessage
+      implements ReadDataReplyOrBuilder {
+    // Use ReadDataReply.newBuilder() to construct.
+    private ReadDataReply(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
+      super(builder);
+      this.unknownFields = builder.getUnknownFields();
+    }
+    private ReadDataReply(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+    private static final ReadDataReply defaultInstance;
+    public static ReadDataReply getDefaultInstance() {
+      return defaultInstance;
+    }
+
+    public ReadDataReply getDefaultInstanceForType() {
+      return defaultInstance;
+    }
+
+    private final com.google.protobuf.UnknownFieldSet unknownFields;
+    @java.lang.Override
+    public final com.google.protobuf.UnknownFieldSet
+        getUnknownFields() {
+      return this.unknownFields;
+    }
+    private ReadDataReply(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      initFields();
+      int mutable_bitField0_ = 0;
+      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+          com.google.protobuf.UnknownFieldSet.newBuilder();
+      try {
+        boolean done = false;
+        while (!done) {
+          int tag = input.readTag();
+          switch (tag) {
+            case 0:
+              done = true;
+              break;
+            default: {
+              if (!parseUnknownField(input, unknownFields,
+                                     extensionRegistry, tag)) {
+                done = true;
+              }
+              break;
+            }
+            case 10: {
+              org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder subBuilder = null;
+              if (((bitField0_ & 0x00000001) == 0x00000001)) {
+                subBuilder = normalizedNode_.toBuilder();
+              }
+              normalizedNode_ = input.readMessage(org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.PARSER, extensionRegistry);
+              if (subBuilder != null) {
+                subBuilder.mergeFrom(normalizedNode_);
+                normalizedNode_ = subBuilder.buildPartial();
+              }
+              bitField0_ |= 0x00000001;
+              break;
+            }
+          }
+        }
+      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+        throw e.setUnfinishedMessage(this);
+      } catch (java.io.IOException e) {
+        throw new com.google.protobuf.InvalidProtocolBufferException(
+            e.getMessage()).setUnfinishedMessage(this);
+      } finally {
+        this.unknownFields = unknownFields.build();
+        makeExtensionsImmutable();
+      }
+    }
+    public static final com.google.protobuf.Descriptors.Descriptor
+        getDescriptor() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadDataReply_descriptor;
+    }
+
+    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+        internalGetFieldAccessorTable() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadDataReply_fieldAccessorTable
+          .ensureFieldAccessorsInitialized(
+              org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply.Builder.class);
+    }
+
+    public static com.google.protobuf.Parser<ReadDataReply> PARSER =
+        new com.google.protobuf.AbstractParser<ReadDataReply>() {
+      public ReadDataReply parsePartialFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws com.google.protobuf.InvalidProtocolBufferException {
+        return new ReadDataReply(input, extensionRegistry);
+      }
+    };
+
+    @java.lang.Override
+    public com.google.protobuf.Parser<ReadDataReply> getParserForType() {
+      return PARSER;
+    }
+
+    private int bitField0_;
+    // required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 1;
+    public static final int NORMALIZEDNODE_FIELD_NUMBER = 1;
+    private org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml normalizedNode_;
+    /**
+     * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 1;</code>
+     */
+    public boolean hasNormalizedNode() {
+      return ((bitField0_ & 0x00000001) == 0x00000001);
+    }
+    /**
+     * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 1;</code>
+     */
+    public org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml getNormalizedNode() {
+      return normalizedNode_;
+    }
+    /**
+     * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 1;</code>
+     */
+    public org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXmlOrBuilder getNormalizedNodeOrBuilder() {
+      return normalizedNode_;
+    }
+
+    private void initFields() {
+      normalizedNode_ = org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.getDefaultInstance();
+    }
+    private byte memoizedIsInitialized = -1;
+    public final boolean isInitialized() {
+      byte isInitialized = memoizedIsInitialized;
+      if (isInitialized != -1) return isInitialized == 1;
+
+      if (!hasNormalizedNode()) {
+        memoizedIsInitialized = 0;
+        return false;
+      }
+      if (!getNormalizedNode().isInitialized()) {
+        memoizedIsInitialized = 0;
+        return false;
+      }
+      memoizedIsInitialized = 1;
+      return true;
+    }
+
+    public void writeTo(com.google.protobuf.CodedOutputStream output)
+                        throws java.io.IOException {
+      getSerializedSize();
+      if (((bitField0_ & 0x00000001) == 0x00000001)) {
+        output.writeMessage(1, normalizedNode_);
+      }
+      getUnknownFields().writeTo(output);
+    }
+
+    private int memoizedSerializedSize = -1;
+    public int getSerializedSize() {
+      int size = memoizedSerializedSize;
+      if (size != -1) return size;
+
+      size = 0;
+      if (((bitField0_ & 0x00000001) == 0x00000001)) {
+        size += com.google.protobuf.CodedOutputStream
+          .computeMessageSize(1, normalizedNode_);
+      }
+      size += getUnknownFields().getSerializedSize();
+      memoizedSerializedSize = size;
+      return size;
+    }
+
+    private static final long serialVersionUID = 0L;
+    @java.lang.Override
+    protected java.lang.Object writeReplace()
+        throws java.io.ObjectStreamException {
+      return super.writeReplace();
+    }
+
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply parseFrom(
+        com.google.protobuf.ByteString data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply parseFrom(
+        com.google.protobuf.ByteString data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply parseFrom(byte[] data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply parseFrom(
+        byte[] data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply parseFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply parseFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply parseDelimitedFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply parseDelimitedFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply parseFrom(
+        com.google.protobuf.CodedInputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply parseFrom(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+
+    public static Builder newBuilder() { return Builder.create(); }
+    public Builder newBuilderForType() { return newBuilder(); }
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply prototype) {
+      return newBuilder().mergeFrom(prototype);
+    }
+    public Builder toBuilder() { return newBuilder(this); }
+
+    @java.lang.Override
+    protected Builder newBuilderForType(
+        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+      Builder builder = new Builder(parent);
+      return builder;
+    }
+    /**
+     * Protobuf type {@code org.opendaylight.controller.mdsal.ReadDataReply}
+     */
+    public static final class Builder extends
+        com.google.protobuf.GeneratedMessage.Builder<Builder>
+       implements org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReplyOrBuilder {
+      public static final com.google.protobuf.Descriptors.Descriptor
+          getDescriptor() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadDataReply_descriptor;
+      }
+
+      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+          internalGetFieldAccessorTable() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadDataReply_fieldAccessorTable
+            .ensureFieldAccessorsInitialized(
+                org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply.Builder.class);
+      }
+
+      // Construct using org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply.newBuilder()
+      private Builder() {
+        maybeForceBuilderInitialization();
+      }
+
+      private Builder(
+          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+        super(parent);
+        maybeForceBuilderInitialization();
+      }
+      private void maybeForceBuilderInitialization() {
+        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+          getNormalizedNodeFieldBuilder();
+        }
+      }
+      private static Builder create() {
+        return new Builder();
+      }
+
+      public Builder clear() {
+        super.clear();
+        if (normalizedNodeBuilder_ == null) {
+          normalizedNode_ = org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.getDefaultInstance();
+        } else {
+          normalizedNodeBuilder_.clear();
+        }
+        bitField0_ = (bitField0_ & ~0x00000001);
+        return this;
+      }
+
+      public Builder clone() {
+        return create().mergeFrom(buildPartial());
+      }
+
+      public com.google.protobuf.Descriptors.Descriptor
+          getDescriptorForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_ReadDataReply_descriptor;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply.getDefaultInstance();
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply build() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply result = buildPartial();
+        if (!result.isInitialized()) {
+          throw newUninitializedMessageException(result);
+        }
+        return result;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply buildPartial() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply result = new org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply(this);
+        int from_bitField0_ = bitField0_;
+        int to_bitField0_ = 0;
+        if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
+          to_bitField0_ |= 0x00000001;
+        }
+        if (normalizedNodeBuilder_ == null) {
+          result.normalizedNode_ = normalizedNode_;
+        } else {
+          result.normalizedNode_ = normalizedNodeBuilder_.build();
+        }
+        result.bitField0_ = to_bitField0_;
+        onBuilt();
+        return result;
+      }
+
+      public Builder mergeFrom(com.google.protobuf.Message other) {
+        if (other instanceof org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply)other);
+        } else {
+          super.mergeFrom(other);
+          return this;
+        }
+      }
+
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply other) {
+        if (other == org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply.getDefaultInstance()) return this;
+        if (other.hasNormalizedNode()) {
+          mergeNormalizedNode(other.getNormalizedNode());
+        }
+        this.mergeUnknownFields(other.getUnknownFields());
+        return this;
+      }
+
+      public final boolean isInitialized() {
+        if (!hasNormalizedNode()) {
+
+          return false;
+        }
+        if (!getNormalizedNode().isInitialized()) {
+
+          return false;
+        }
+        return true;
+      }
+
+      public Builder mergeFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws java.io.IOException {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply parsedMessage = null;
+        try {
+          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.ReadDataReply) e.getUnfinishedMessage();
+          throw e;
+        } finally {
+          if (parsedMessage != null) {
+            mergeFrom(parsedMessage);
+          }
+        }
+        return this;
+      }
+      private int bitField0_;
+
+      // required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 1;
+      private org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml normalizedNode_ = org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.getDefaultInstance();
+      private com.google.protobuf.SingleFieldBuilder<
+          org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml, org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder, org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXmlOrBuilder> normalizedNodeBuilder_;
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 1;</code>
+       */
+      public boolean hasNormalizedNode() {
+        return ((bitField0_ & 0x00000001) == 0x00000001);
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 1;</code>
+       */
+      public org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml getNormalizedNode() {
+        if (normalizedNodeBuilder_ == null) {
+          return normalizedNode_;
+        } else {
+          return normalizedNodeBuilder_.getMessage();
+        }
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 1;</code>
+       */
+      public Builder setNormalizedNode(org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml value) {
+        if (normalizedNodeBuilder_ == null) {
+          if (value == null) {
+            throw new NullPointerException();
+          }
+          normalizedNode_ = value;
+          onChanged();
+        } else {
+          normalizedNodeBuilder_.setMessage(value);
+        }
+        bitField0_ |= 0x00000001;
+        return this;
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 1;</code>
+       */
+      public Builder setNormalizedNode(
+          org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder builderForValue) {
+        if (normalizedNodeBuilder_ == null) {
+          normalizedNode_ = builderForValue.build();
+          onChanged();
+        } else {
+          normalizedNodeBuilder_.setMessage(builderForValue.build());
+        }
+        bitField0_ |= 0x00000001;
+        return this;
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 1;</code>
+       */
+      public Builder mergeNormalizedNode(org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml value) {
+        if (normalizedNodeBuilder_ == null) {
+          if (((bitField0_ & 0x00000001) == 0x00000001) &&
+              normalizedNode_ != org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.getDefaultInstance()) {
+            normalizedNode_ =
+              org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.newBuilder(normalizedNode_).mergeFrom(value).buildPartial();
+          } else {
+            normalizedNode_ = value;
+          }
+          onChanged();
+        } else {
+          normalizedNodeBuilder_.mergeFrom(value);
+        }
+        bitField0_ |= 0x00000001;
+        return this;
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 1;</code>
+       */
+      public Builder clearNormalizedNode() {
+        if (normalizedNodeBuilder_ == null) {
+          normalizedNode_ = org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.getDefaultInstance();
+          onChanged();
+        } else {
+          normalizedNodeBuilder_.clear();
+        }
+        bitField0_ = (bitField0_ & ~0x00000001);
+        return this;
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 1;</code>
+       */
+      public org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder getNormalizedNodeBuilder() {
+        bitField0_ |= 0x00000001;
+        onChanged();
+        return getNormalizedNodeFieldBuilder().getBuilder();
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 1;</code>
+       */
+      public org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXmlOrBuilder getNormalizedNodeOrBuilder() {
+        if (normalizedNodeBuilder_ != null) {
+          return normalizedNodeBuilder_.getMessageOrBuilder();
+        } else {
+          return normalizedNode_;
+        }
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 1;</code>
+       */
+      private com.google.protobuf.SingleFieldBuilder<
+          org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml, org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder, org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXmlOrBuilder>
+          getNormalizedNodeFieldBuilder() {
+        if (normalizedNodeBuilder_ == null) {
+          normalizedNodeBuilder_ = new com.google.protobuf.SingleFieldBuilder<
+              org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml, org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder, org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXmlOrBuilder>(
+                  normalizedNode_,
+                  getParentForChildren(),
+                  isClean());
+          normalizedNode_ = null;
+        }
+        return normalizedNodeBuilder_;
+      }
+
+      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.ReadDataReply)
+    }
+
+    static {
+      defaultInstance = new ReadDataReply(true);
+      defaultInstance.initFields();
+    }
+
+    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.ReadDataReply)
+  }
+
+  public interface WriteDataOrBuilder
+      extends com.google.protobuf.MessageOrBuilder {
+
+    // repeated string instanceIdentifierPathArguments = 1;
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    java.util.List<java.lang.String>
+    getInstanceIdentifierPathArgumentsList();
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    int getInstanceIdentifierPathArgumentsCount();
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    java.lang.String getInstanceIdentifierPathArguments(int index);
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    com.google.protobuf.ByteString
+        getInstanceIdentifierPathArgumentsBytes(int index);
+
+    // required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 2;
+    /**
+     * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 2;</code>
+     */
+    boolean hasNormalizedNode();
+    /**
+     * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 2;</code>
+     */
+    org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml getNormalizedNode();
+    /**
+     * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 2;</code>
+     */
+    org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXmlOrBuilder getNormalizedNodeOrBuilder();
+  }
+  /**
+   * Protobuf type {@code org.opendaylight.controller.mdsal.WriteData}
+   */
+  public static final class WriteData extends
+      com.google.protobuf.GeneratedMessage
+      implements WriteDataOrBuilder {
+    // Use WriteData.newBuilder() to construct.
+    private WriteData(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
+      super(builder);
+      this.unknownFields = builder.getUnknownFields();
+    }
+    private WriteData(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+    private static final WriteData defaultInstance;
+    public static WriteData getDefaultInstance() {
+      return defaultInstance;
+    }
+
+    public WriteData getDefaultInstanceForType() {
+      return defaultInstance;
+    }
+
+    private final com.google.protobuf.UnknownFieldSet unknownFields;
+    @java.lang.Override
+    public final com.google.protobuf.UnknownFieldSet
+        getUnknownFields() {
+      return this.unknownFields;
+    }
+    private WriteData(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      initFields();
+      int mutable_bitField0_ = 0;
+      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+          com.google.protobuf.UnknownFieldSet.newBuilder();
+      try {
+        boolean done = false;
+        while (!done) {
+          int tag = input.readTag();
+          switch (tag) {
+            case 0:
+              done = true;
+              break;
+            default: {
+              if (!parseUnknownField(input, unknownFields,
+                                     extensionRegistry, tag)) {
+                done = true;
+              }
+              break;
+            }
+            case 10: {
+              if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
+                instanceIdentifierPathArguments_ = new com.google.protobuf.LazyStringArrayList();
+                mutable_bitField0_ |= 0x00000001;
+              }
+              instanceIdentifierPathArguments_.add(input.readBytes());
+              break;
+            }
+            case 18: {
+              org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder subBuilder = null;
+              if (((bitField0_ & 0x00000001) == 0x00000001)) {
+                subBuilder = normalizedNode_.toBuilder();
+              }
+              normalizedNode_ = input.readMessage(org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.PARSER, extensionRegistry);
+              if (subBuilder != null) {
+                subBuilder.mergeFrom(normalizedNode_);
+                normalizedNode_ = subBuilder.buildPartial();
+              }
+              bitField0_ |= 0x00000001;
+              break;
+            }
+          }
+        }
+      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+        throw e.setUnfinishedMessage(this);
+      } catch (java.io.IOException e) {
+        throw new com.google.protobuf.InvalidProtocolBufferException(
+            e.getMessage()).setUnfinishedMessage(this);
+      } finally {
+        if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
+          instanceIdentifierPathArguments_ = new com.google.protobuf.UnmodifiableLazyStringList(instanceIdentifierPathArguments_);
+        }
+        this.unknownFields = unknownFields.build();
+        makeExtensionsImmutable();
+      }
+    }
+    public static final com.google.protobuf.Descriptors.Descriptor
+        getDescriptor() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_WriteData_descriptor;
+    }
+
+    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+        internalGetFieldAccessorTable() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_WriteData_fieldAccessorTable
+          .ensureFieldAccessorsInitialized(
+              org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData.Builder.class);
+    }
+
+    public static com.google.protobuf.Parser<WriteData> PARSER =
+        new com.google.protobuf.AbstractParser<WriteData>() {
+      public WriteData parsePartialFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws com.google.protobuf.InvalidProtocolBufferException {
+        return new WriteData(input, extensionRegistry);
+      }
+    };
+
+    @java.lang.Override
+    public com.google.protobuf.Parser<WriteData> getParserForType() {
+      return PARSER;
+    }
+
+    private int bitField0_;
+    // repeated string instanceIdentifierPathArguments = 1;
+    public static final int INSTANCEIDENTIFIERPATHARGUMENTS_FIELD_NUMBER = 1;
+    private com.google.protobuf.LazyStringList instanceIdentifierPathArguments_;
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    public java.util.List<java.lang.String>
+        getInstanceIdentifierPathArgumentsList() {
+      return instanceIdentifierPathArguments_;
+    }
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    public int getInstanceIdentifierPathArgumentsCount() {
+      return instanceIdentifierPathArguments_.size();
+    }
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    public java.lang.String getInstanceIdentifierPathArguments(int index) {
+      return instanceIdentifierPathArguments_.get(index);
+    }
+    /**
+     * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+     */
+    public com.google.protobuf.ByteString
+        getInstanceIdentifierPathArgumentsBytes(int index) {
+      return instanceIdentifierPathArguments_.getByteString(index);
+    }
+
+    // required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 2;
+    public static final int NORMALIZEDNODE_FIELD_NUMBER = 2;
+    private org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml normalizedNode_;
+    /**
+     * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 2;</code>
+     */
+    public boolean hasNormalizedNode() {
+      return ((bitField0_ & 0x00000001) == 0x00000001);
+    }
+    /**
+     * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 2;</code>
+     */
+    public org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml getNormalizedNode() {
+      return normalizedNode_;
+    }
+    /**
+     * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 2;</code>
+     */
+    public org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXmlOrBuilder getNormalizedNodeOrBuilder() {
+      return normalizedNode_;
+    }
+
+    private void initFields() {
+      instanceIdentifierPathArguments_ = com.google.protobuf.LazyStringArrayList.EMPTY;
+      normalizedNode_ = org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.getDefaultInstance();
+    }
+    private byte memoizedIsInitialized = -1;
+    public final boolean isInitialized() {
+      byte isInitialized = memoizedIsInitialized;
+      if (isInitialized != -1) return isInitialized == 1;
+
+      if (!hasNormalizedNode()) {
+        memoizedIsInitialized = 0;
+        return false;
+      }
+      if (!getNormalizedNode().isInitialized()) {
+        memoizedIsInitialized = 0;
+        return false;
+      }
+      memoizedIsInitialized = 1;
+      return true;
+    }
+
+    public void writeTo(com.google.protobuf.CodedOutputStream output)
+                        throws java.io.IOException {
+      getSerializedSize();
+      for (int i = 0; i < instanceIdentifierPathArguments_.size(); i++) {
+        output.writeBytes(1, instanceIdentifierPathArguments_.getByteString(i));
+      }
+      if (((bitField0_ & 0x00000001) == 0x00000001)) {
+        output.writeMessage(2, normalizedNode_);
+      }
+      getUnknownFields().writeTo(output);
+    }
+
+    private int memoizedSerializedSize = -1;
+    public int getSerializedSize() {
+      int size = memoizedSerializedSize;
+      if (size != -1) return size;
+
+      size = 0;
+      {
+        int dataSize = 0;
+        for (int i = 0; i < instanceIdentifierPathArguments_.size(); i++) {
+          dataSize += com.google.protobuf.CodedOutputStream
+            .computeBytesSizeNoTag(instanceIdentifierPathArguments_.getByteString(i));
+        }
+        size += dataSize;
+        size += 1 * getInstanceIdentifierPathArgumentsList().size();
+      }
+      if (((bitField0_ & 0x00000001) == 0x00000001)) {
+        size += com.google.protobuf.CodedOutputStream
+          .computeMessageSize(2, normalizedNode_);
+      }
+      size += getUnknownFields().getSerializedSize();
+      memoizedSerializedSize = size;
+      return size;
+    }
+
+    private static final long serialVersionUID = 0L;
+    @java.lang.Override
+    protected java.lang.Object writeReplace()
+        throws java.io.ObjectStreamException {
+      return super.writeReplace();
+    }
+
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData parseFrom(
+        com.google.protobuf.ByteString data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData parseFrom(
+        com.google.protobuf.ByteString data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData parseFrom(byte[] data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData parseFrom(
+        byte[] data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData parseFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData parseFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData parseDelimitedFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData parseDelimitedFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData parseFrom(
+        com.google.protobuf.CodedInputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData parseFrom(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+
+    public static Builder newBuilder() { return Builder.create(); }
+    public Builder newBuilderForType() { return newBuilder(); }
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData prototype) {
+      return newBuilder().mergeFrom(prototype);
+    }
+    public Builder toBuilder() { return newBuilder(this); }
+
+    @java.lang.Override
+    protected Builder newBuilderForType(
+        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+      Builder builder = new Builder(parent);
+      return builder;
+    }
+    /**
+     * Protobuf type {@code org.opendaylight.controller.mdsal.WriteData}
+     */
+    public static final class Builder extends
+        com.google.protobuf.GeneratedMessage.Builder<Builder>
+       implements org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataOrBuilder {
+      public static final com.google.protobuf.Descriptors.Descriptor
+          getDescriptor() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_WriteData_descriptor;
+      }
+
+      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+          internalGetFieldAccessorTable() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_WriteData_fieldAccessorTable
+            .ensureFieldAccessorsInitialized(
+                org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData.Builder.class);
+      }
+
+      // Construct using org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData.newBuilder()
+      private Builder() {
+        maybeForceBuilderInitialization();
+      }
+
+      private Builder(
+          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+        super(parent);
+        maybeForceBuilderInitialization();
+      }
+      private void maybeForceBuilderInitialization() {
+        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+          getNormalizedNodeFieldBuilder();
+        }
+      }
+      private static Builder create() {
+        return new Builder();
+      }
+
+      public Builder clear() {
+        super.clear();
+        instanceIdentifierPathArguments_ = com.google.protobuf.LazyStringArrayList.EMPTY;
+        bitField0_ = (bitField0_ & ~0x00000001);
+        if (normalizedNodeBuilder_ == null) {
+          normalizedNode_ = org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.getDefaultInstance();
+        } else {
+          normalizedNodeBuilder_.clear();
+        }
+        bitField0_ = (bitField0_ & ~0x00000002);
+        return this;
+      }
+
+      public Builder clone() {
+        return create().mergeFrom(buildPartial());
+      }
+
+      public com.google.protobuf.Descriptors.Descriptor
+          getDescriptorForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_WriteData_descriptor;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData.getDefaultInstance();
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData build() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData result = buildPartial();
+        if (!result.isInitialized()) {
+          throw newUninitializedMessageException(result);
+        }
+        return result;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData buildPartial() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData result = new org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData(this);
+        int from_bitField0_ = bitField0_;
+        int to_bitField0_ = 0;
+        if (((bitField0_ & 0x00000001) == 0x00000001)) {
+          instanceIdentifierPathArguments_ = new com.google.protobuf.UnmodifiableLazyStringList(
+              instanceIdentifierPathArguments_);
+          bitField0_ = (bitField0_ & ~0x00000001);
+        }
+        result.instanceIdentifierPathArguments_ = instanceIdentifierPathArguments_;
+        if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
+          to_bitField0_ |= 0x00000001;
+        }
+        if (normalizedNodeBuilder_ == null) {
+          result.normalizedNode_ = normalizedNode_;
+        } else {
+          result.normalizedNode_ = normalizedNodeBuilder_.build();
+        }
+        result.bitField0_ = to_bitField0_;
+        onBuilt();
+        return result;
+      }
+
+      public Builder mergeFrom(com.google.protobuf.Message other) {
+        if (other instanceof org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData)other);
+        } else {
+          super.mergeFrom(other);
+          return this;
+        }
+      }
+
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData other) {
+        if (other == org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData.getDefaultInstance()) return this;
+        if (!other.instanceIdentifierPathArguments_.isEmpty()) {
+          if (instanceIdentifierPathArguments_.isEmpty()) {
+            instanceIdentifierPathArguments_ = other.instanceIdentifierPathArguments_;
+            bitField0_ = (bitField0_ & ~0x00000001);
+          } else {
+            ensureInstanceIdentifierPathArgumentsIsMutable();
+            instanceIdentifierPathArguments_.addAll(other.instanceIdentifierPathArguments_);
+          }
+          onChanged();
+        }
+        if (other.hasNormalizedNode()) {
+          mergeNormalizedNode(other.getNormalizedNode());
+        }
+        this.mergeUnknownFields(other.getUnknownFields());
+        return this;
+      }
+
+      public final boolean isInitialized() {
+        if (!hasNormalizedNode()) {
+
+          return false;
+        }
+        if (!getNormalizedNode().isInitialized()) {
+
+          return false;
+        }
+        return true;
+      }
+
+      public Builder mergeFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws java.io.IOException {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData parsedMessage = null;
+        try {
+          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteData) e.getUnfinishedMessage();
+          throw e;
+        } finally {
+          if (parsedMessage != null) {
+            mergeFrom(parsedMessage);
+          }
+        }
+        return this;
+      }
+      private int bitField0_;
+
+      // repeated string instanceIdentifierPathArguments = 1;
+      private com.google.protobuf.LazyStringList instanceIdentifierPathArguments_ = com.google.protobuf.LazyStringArrayList.EMPTY;
+      private void ensureInstanceIdentifierPathArgumentsIsMutable() {
+        if (!((bitField0_ & 0x00000001) == 0x00000001)) {
+          instanceIdentifierPathArguments_ = new com.google.protobuf.LazyStringArrayList(instanceIdentifierPathArguments_);
+          bitField0_ |= 0x00000001;
+         }
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public java.util.List<java.lang.String>
+          getInstanceIdentifierPathArgumentsList() {
+        return java.util.Collections.unmodifiableList(instanceIdentifierPathArguments_);
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public int getInstanceIdentifierPathArgumentsCount() {
+        return instanceIdentifierPathArguments_.size();
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public java.lang.String getInstanceIdentifierPathArguments(int index) {
+        return instanceIdentifierPathArguments_.get(index);
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public com.google.protobuf.ByteString
+          getInstanceIdentifierPathArgumentsBytes(int index) {
+        return instanceIdentifierPathArguments_.getByteString(index);
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public Builder setInstanceIdentifierPathArguments(
+          int index, java.lang.String value) {
+        if (value == null) {
+    throw new NullPointerException();
+  }
+  ensureInstanceIdentifierPathArgumentsIsMutable();
+        instanceIdentifierPathArguments_.set(index, value);
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public Builder addInstanceIdentifierPathArguments(
+          java.lang.String value) {
+        if (value == null) {
+    throw new NullPointerException();
+  }
+  ensureInstanceIdentifierPathArgumentsIsMutable();
+        instanceIdentifierPathArguments_.add(value);
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public Builder addAllInstanceIdentifierPathArguments(
+          java.lang.Iterable<java.lang.String> values) {
+        ensureInstanceIdentifierPathArgumentsIsMutable();
+        super.addAll(values, instanceIdentifierPathArguments_);
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public Builder clearInstanceIdentifierPathArguments() {
+        instanceIdentifierPathArguments_ = com.google.protobuf.LazyStringArrayList.EMPTY;
+        bitField0_ = (bitField0_ & ~0x00000001);
+        onChanged();
+        return this;
+      }
+      /**
+       * <code>repeated string instanceIdentifierPathArguments = 1;</code>
+       */
+      public Builder addInstanceIdentifierPathArgumentsBytes(
+          com.google.protobuf.ByteString value) {
+        if (value == null) {
+    throw new NullPointerException();
+  }
+  ensureInstanceIdentifierPathArgumentsIsMutable();
+        instanceIdentifierPathArguments_.add(value);
+        onChanged();
+        return this;
+      }
+
+      // required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 2;
+      private org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml normalizedNode_ = org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.getDefaultInstance();
+      private com.google.protobuf.SingleFieldBuilder<
+          org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml, org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder, org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXmlOrBuilder> normalizedNodeBuilder_;
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 2;</code>
+       */
+      public boolean hasNormalizedNode() {
+        return ((bitField0_ & 0x00000002) == 0x00000002);
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 2;</code>
+       */
+      public org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml getNormalizedNode() {
+        if (normalizedNodeBuilder_ == null) {
+          return normalizedNode_;
+        } else {
+          return normalizedNodeBuilder_.getMessage();
+        }
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 2;</code>
+       */
+      public Builder setNormalizedNode(org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml value) {
+        if (normalizedNodeBuilder_ == null) {
+          if (value == null) {
+            throw new NullPointerException();
+          }
+          normalizedNode_ = value;
+          onChanged();
+        } else {
+          normalizedNodeBuilder_.setMessage(value);
+        }
+        bitField0_ |= 0x00000002;
+        return this;
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 2;</code>
+       */
+      public Builder setNormalizedNode(
+          org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder builderForValue) {
+        if (normalizedNodeBuilder_ == null) {
+          normalizedNode_ = builderForValue.build();
+          onChanged();
+        } else {
+          normalizedNodeBuilder_.setMessage(builderForValue.build());
+        }
+        bitField0_ |= 0x00000002;
+        return this;
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 2;</code>
+       */
+      public Builder mergeNormalizedNode(org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml value) {
+        if (normalizedNodeBuilder_ == null) {
+          if (((bitField0_ & 0x00000002) == 0x00000002) &&
+              normalizedNode_ != org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.getDefaultInstance()) {
+            normalizedNode_ =
+              org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.newBuilder(normalizedNode_).mergeFrom(value).buildPartial();
+          } else {
+            normalizedNode_ = value;
+          }
+          onChanged();
+        } else {
+          normalizedNodeBuilder_.mergeFrom(value);
+        }
+        bitField0_ |= 0x00000002;
+        return this;
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 2;</code>
+       */
+      public Builder clearNormalizedNode() {
+        if (normalizedNodeBuilder_ == null) {
+          normalizedNode_ = org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.getDefaultInstance();
+          onChanged();
+        } else {
+          normalizedNodeBuilder_.clear();
+        }
+        bitField0_ = (bitField0_ & ~0x00000002);
+        return this;
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 2;</code>
+       */
+      public org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder getNormalizedNodeBuilder() {
+        bitField0_ |= 0x00000002;
+        onChanged();
+        return getNormalizedNodeFieldBuilder().getBuilder();
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 2;</code>
+       */
+      public org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXmlOrBuilder getNormalizedNodeOrBuilder() {
+        if (normalizedNodeBuilder_ != null) {
+          return normalizedNodeBuilder_.getMessageOrBuilder();
+        } else {
+          return normalizedNode_;
+        }
+      }
+      /**
+       * <code>required .org.opendaylight.controller.mdsal.NormalizedNodeXml normalizedNode = 2;</code>
+       */
+      private com.google.protobuf.SingleFieldBuilder<
+          org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml, org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder, org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXmlOrBuilder>
+          getNormalizedNodeFieldBuilder() {
+        if (normalizedNodeBuilder_ == null) {
+          normalizedNodeBuilder_ = new com.google.protobuf.SingleFieldBuilder<
+              org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml, org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXml.Builder, org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.NormalizedNodeXmlOrBuilder>(
+                  normalizedNode_,
+                  getParentForChildren(),
+                  isClean());
+          normalizedNode_ = null;
+        }
+        return normalizedNodeBuilder_;
+      }
+
+      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.WriteData)
+    }
+
+    static {
+      defaultInstance = new WriteData(true);
+      defaultInstance.initFields();
+    }
+
+    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.WriteData)
+  }
+
+  public interface WriteDataReplyOrBuilder
+      extends com.google.protobuf.MessageOrBuilder {
+  }
+  /**
+   * Protobuf type {@code org.opendaylight.controller.mdsal.WriteDataReply}
+   */
+  public static final class WriteDataReply extends
+      com.google.protobuf.GeneratedMessage
+      implements WriteDataReplyOrBuilder {
+    // Use WriteDataReply.newBuilder() to construct.
+    private WriteDataReply(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
+      super(builder);
+      this.unknownFields = builder.getUnknownFields();
+    }
+    private WriteDataReply(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
+
+    private static final WriteDataReply defaultInstance;
+    public static WriteDataReply getDefaultInstance() {
+      return defaultInstance;
+    }
+
+    public WriteDataReply getDefaultInstanceForType() {
+      return defaultInstance;
+    }
+
+    private final com.google.protobuf.UnknownFieldSet unknownFields;
+    @java.lang.Override
+    public final com.google.protobuf.UnknownFieldSet
+        getUnknownFields() {
+      return this.unknownFields;
+    }
+    private WriteDataReply(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      initFields();
+      com.google.protobuf.UnknownFieldSet.Builder unknownFields =
+          com.google.protobuf.UnknownFieldSet.newBuilder();
+      try {
+        boolean done = false;
+        while (!done) {
+          int tag = input.readTag();
+          switch (tag) {
+            case 0:
+              done = true;
+              break;
+            default: {
+              if (!parseUnknownField(input, unknownFields,
+                                     extensionRegistry, tag)) {
+                done = true;
+              }
+              break;
+            }
+          }
+        }
+      } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+        throw e.setUnfinishedMessage(this);
+      } catch (java.io.IOException e) {
+        throw new com.google.protobuf.InvalidProtocolBufferException(
+            e.getMessage()).setUnfinishedMessage(this);
+      } finally {
+        this.unknownFields = unknownFields.build();
+        makeExtensionsImmutable();
+      }
+    }
+    public static final com.google.protobuf.Descriptors.Descriptor
+        getDescriptor() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_WriteDataReply_descriptor;
+    }
+
+    protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+        internalGetFieldAccessorTable() {
+      return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_WriteDataReply_fieldAccessorTable
+          .ensureFieldAccessorsInitialized(
+              org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply.Builder.class);
+    }
+
+    public static com.google.protobuf.Parser<WriteDataReply> PARSER =
+        new com.google.protobuf.AbstractParser<WriteDataReply>() {
+      public WriteDataReply parsePartialFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws com.google.protobuf.InvalidProtocolBufferException {
+        return new WriteDataReply(input, extensionRegistry);
+      }
+    };
+
+    @java.lang.Override
+    public com.google.protobuf.Parser<WriteDataReply> getParserForType() {
+      return PARSER;
+    }
+
+    private void initFields() {
+    }
+    private byte memoizedIsInitialized = -1;
+    public final boolean isInitialized() {
+      byte isInitialized = memoizedIsInitialized;
+      if (isInitialized != -1) return isInitialized == 1;
+
+      memoizedIsInitialized = 1;
+      return true;
+    }
+
+    public void writeTo(com.google.protobuf.CodedOutputStream output)
+                        throws java.io.IOException {
+      getSerializedSize();
+      getUnknownFields().writeTo(output);
+    }
+
+    private int memoizedSerializedSize = -1;
+    public int getSerializedSize() {
+      int size = memoizedSerializedSize;
+      if (size != -1) return size;
+
+      size = 0;
+      size += getUnknownFields().getSerializedSize();
+      memoizedSerializedSize = size;
+      return size;
+    }
+
+    private static final long serialVersionUID = 0L;
+    @java.lang.Override
+    protected java.lang.Object writeReplace()
+        throws java.io.ObjectStreamException {
+      return super.writeReplace();
+    }
+
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply parseFrom(
+        com.google.protobuf.ByteString data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply parseFrom(
+        com.google.protobuf.ByteString data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply parseFrom(byte[] data)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply parseFrom(
+        byte[] data,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws com.google.protobuf.InvalidProtocolBufferException {
+      return PARSER.parseFrom(data, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply parseFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply parseFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply parseDelimitedFrom(java.io.InputStream input)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply parseDelimitedFrom(
+        java.io.InputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseDelimitedFrom(input, extensionRegistry);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply parseFrom(
+        com.google.protobuf.CodedInputStream input)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input);
+    }
+    public static org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply parseFrom(
+        com.google.protobuf.CodedInputStream input,
+        com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+        throws java.io.IOException {
+      return PARSER.parseFrom(input, extensionRegistry);
+    }
+
+    public static Builder newBuilder() { return Builder.create(); }
+    public Builder newBuilderForType() { return newBuilder(); }
+    public static Builder newBuilder(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply prototype) {
+      return newBuilder().mergeFrom(prototype);
+    }
+    public Builder toBuilder() { return newBuilder(this); }
+
+    @java.lang.Override
+    protected Builder newBuilderForType(
+        com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+      Builder builder = new Builder(parent);
+      return builder;
+    }
+    /**
+     * Protobuf type {@code org.opendaylight.controller.mdsal.WriteDataReply}
+     */
+    public static final class Builder extends
+        com.google.protobuf.GeneratedMessage.Builder<Builder>
+       implements org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReplyOrBuilder {
+      public static final com.google.protobuf.Descriptors.Descriptor
+          getDescriptor() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_WriteDataReply_descriptor;
+      }
+
+      protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
+          internalGetFieldAccessorTable() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_WriteDataReply_fieldAccessorTable
+            .ensureFieldAccessorsInitialized(
+                org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply.class, org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply.Builder.class);
+      }
+
+      // Construct using org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply.newBuilder()
+      private Builder() {
+        maybeForceBuilderInitialization();
+      }
+
+      private Builder(
+          com.google.protobuf.GeneratedMessage.BuilderParent parent) {
+        super(parent);
+        maybeForceBuilderInitialization();
+      }
+      private void maybeForceBuilderInitialization() {
+        if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
+        }
+      }
+      private static Builder create() {
+        return new Builder();
+      }
+
+      public Builder clear() {
+        super.clear();
+        return this;
+      }
+
+      public Builder clone() {
+        return create().mergeFrom(buildPartial());
+      }
+
+      public com.google.protobuf.Descriptors.Descriptor
+          getDescriptorForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.internal_static_org_opendaylight_controller_mdsal_WriteDataReply_descriptor;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply getDefaultInstanceForType() {
+        return org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply.getDefaultInstance();
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply build() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply result = buildPartial();
+        if (!result.isInitialized()) {
+          throw newUninitializedMessageException(result);
+        }
+        return result;
+      }
+
+      public org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply buildPartial() {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply result = new org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply(this);
+        onBuilt();
+        return result;
+      }
+
+      public Builder mergeFrom(com.google.protobuf.Message other) {
+        if (other instanceof org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply) {
+          return mergeFrom((org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply)other);
+        } else {
+          super.mergeFrom(other);
+          return this;
+        }
+      }
+
+      public Builder mergeFrom(org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply other) {
+        if (other == org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply.getDefaultInstance()) return this;
+        this.mergeUnknownFields(other.getUnknownFields());
+        return this;
+      }
+
+      public final boolean isInitialized() {
+        return true;
+      }
+
+      public Builder mergeFrom(
+          com.google.protobuf.CodedInputStream input,
+          com.google.protobuf.ExtensionRegistryLite extensionRegistry)
+          throws java.io.IOException {
+        org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply parsedMessage = null;
+        try {
+          parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
+        } catch (com.google.protobuf.InvalidProtocolBufferException e) {
+          parsedMessage = (org.opendaylight.controller.protobuff.messages.transaction.ShardTransactionMessages.WriteDataReply) e.getUnfinishedMessage();
+          throw e;
+        } finally {
+          if (parsedMessage != null) {
+            mergeFrom(parsedMessage);
+          }
+        }
+        return this;
+      }
+
+      // @@protoc_insertion_point(builder_scope:org.opendaylight.controller.mdsal.WriteDataReply)
+    }
+
+    static {
+      defaultInstance = new WriteDataReply(true);
+      defaultInstance.initFields();
+    }
+
+    // @@protoc_insertion_point(class_scope:org.opendaylight.controller.mdsal.WriteDataReply)
+  }
+
+  private static com.google.protobuf.Descriptors.Descriptor
+    internal_static_org_opendaylight_controller_mdsal_CloseTransaction_descriptor;
+  private static
+    com.google.protobuf.GeneratedMessage.FieldAccessorTable
+      internal_static_org_opendaylight_controller_mdsal_CloseTransaction_fieldAccessorTable;
+  private static com.google.protobuf.Descriptors.Descriptor
+    internal_static_org_opendaylight_controller_mdsal_CloseTransactionReply_descriptor;
+  private static
+    com.google.protobuf.GeneratedMessage.FieldAccessorTable
+      internal_static_org_opendaylight_controller_mdsal_CloseTransactionReply_fieldAccessorTable;
+  private static com.google.protobuf.Descriptors.Descriptor
+    internal_static_org_opendaylight_controller_mdsal_CreateTransaction_descriptor;
+  private static
+    com.google.protobuf.GeneratedMessage.FieldAccessorTable
+      internal_static_org_opendaylight_controller_mdsal_CreateTransaction_fieldAccessorTable;
+  private static com.google.protobuf.Descriptors.Descriptor
+    internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_descriptor;
+  private static
+    com.google.protobuf.GeneratedMessage.FieldAccessorTable
+      internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_fieldAccessorTable;
+  private static com.google.protobuf.Descriptors.Descriptor
+    internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_descriptor;
+  private static
+    com.google.protobuf.GeneratedMessage.FieldAccessorTable
+      internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_fieldAccessorTable;
+  private static com.google.protobuf.Descriptors.Descriptor
+    internal_static_org_opendaylight_controller_mdsal_ReadyTransactionReply_descriptor;
+  private static
+    com.google.protobuf.GeneratedMessage.FieldAccessorTable
+      internal_static_org_opendaylight_controller_mdsal_ReadyTransactionReply_fieldAccessorTable;
+  private static com.google.protobuf.Descriptors.Descriptor
+    internal_static_org_opendaylight_controller_mdsal_DeleteData_descriptor;
+  private static
+    com.google.protobuf.GeneratedMessage.FieldAccessorTable
+      internal_static_org_opendaylight_controller_mdsal_DeleteData_fieldAccessorTable;
+  private static com.google.protobuf.Descriptors.Descriptor
+    internal_static_org_opendaylight_controller_mdsal_DeleteDataReply_descriptor;
+  private static
+    com.google.protobuf.GeneratedMessage.FieldAccessorTable
+      internal_static_org_opendaylight_controller_mdsal_DeleteDataReply_fieldAccessorTable;
+  private static com.google.protobuf.Descriptors.Descriptor
+    internal_static_org_opendaylight_controller_mdsal_ReadData_descriptor;
+  private static
+    com.google.protobuf.GeneratedMessage.FieldAccessorTable
+      internal_static_org_opendaylight_controller_mdsal_ReadData_fieldAccessorTable;
+  private static com.google.protobuf.Descriptors.Descriptor
+    internal_static_org_opendaylight_controller_mdsal_ReadDataReply_descriptor;
+  private static
+    com.google.protobuf.GeneratedMessage.FieldAccessorTable
+      internal_static_org_opendaylight_controller_mdsal_ReadDataReply_fieldAccessorTable;
+  private static com.google.protobuf.Descriptors.Descriptor
+    internal_static_org_opendaylight_controller_mdsal_WriteData_descriptor;
+  private static
+    com.google.protobuf.GeneratedMessage.FieldAccessorTable
+      internal_static_org_opendaylight_controller_mdsal_WriteData_fieldAccessorTable;
+  private static com.google.protobuf.Descriptors.Descriptor
+    internal_static_org_opendaylight_controller_mdsal_WriteDataReply_descriptor;
+  private static
+    com.google.protobuf.GeneratedMessage.FieldAccessorTable
+      internal_static_org_opendaylight_controller_mdsal_WriteDataReply_fieldAccessorTable;
+
+  public static com.google.protobuf.Descriptors.FileDescriptor
+      getDescriptor() {
+    return descriptor;
+  }
+  private static com.google.protobuf.Descriptors.FileDescriptor
+      descriptor;
+  static {
+    java.lang.String[] descriptorData = {
+      "\n\026ShardTransaction.proto\022!org.opendaylig" +
+      "ht.controller.mdsal\032\032SimpleNormalizedNod" +
+      "e.proto\"\022\n\020CloseTransaction\"\027\n\025CloseTran" +
+      "sactionReply\"\023\n\021CreateTransaction\"1\n\026Cre" +
+      "ateTransactionReply\022\027\n\017transactionPath\030\001" +
+      " \002(\t\"\022\n\020ReadyTransaction\"*\n\025ReadyTransac" +
+      "tionReply\022\021\n\tactorPath\030\001 \002(\t\"5\n\nDeleteDa" +
+      "ta\022\'\n\037instanceIdentifierPathArguments\030\001 " +
+      "\003(\t\"\021\n\017DeleteDataReply\"3\n\010ReadData\022\'\n\037in" +
+      "stanceIdentifierPathArguments\030\001 \002(\t\"]\n\rR",
+      "eadDataReply\022L\n\016normalizedNode\030\001 \002(\01324.o" +
+      "rg.opendaylight.controller.mdsal.Normali" +
+      "zedNodeXml\"\202\001\n\tWriteData\022\'\n\037instanceIden" +
+      "tifierPathArguments\030\001 \003(\t\022L\n\016normalizedN" +
+      "ode\030\002 \002(\01324.org.opendaylight.controller." +
+      "mdsal.NormalizedNodeXml\"\020\n\016WriteDataRepl" +
+      "yBV\n:org.opendaylight.controller.protobu" +
+      "ff.messages.transactionB\030ShardTransactio" +
+      "nMessages"
+    };
+    com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
+      new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
+        public com.google.protobuf.ExtensionRegistry assignDescriptors(
+            com.google.protobuf.Descriptors.FileDescriptor root) {
+          descriptor = root;
+          internal_static_org_opendaylight_controller_mdsal_CloseTransaction_descriptor =
+            getDescriptor().getMessageTypes().get(0);
+          internal_static_org_opendaylight_controller_mdsal_CloseTransaction_fieldAccessorTable = new
+            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+              internal_static_org_opendaylight_controller_mdsal_CloseTransaction_descriptor,
+              new java.lang.String[] { });
+          internal_static_org_opendaylight_controller_mdsal_CloseTransactionReply_descriptor =
+            getDescriptor().getMessageTypes().get(1);
+          internal_static_org_opendaylight_controller_mdsal_CloseTransactionReply_fieldAccessorTable = new
+            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+              internal_static_org_opendaylight_controller_mdsal_CloseTransactionReply_descriptor,
+              new java.lang.String[] { });
+          internal_static_org_opendaylight_controller_mdsal_CreateTransaction_descriptor =
+            getDescriptor().getMessageTypes().get(2);
+          internal_static_org_opendaylight_controller_mdsal_CreateTransaction_fieldAccessorTable = new
+            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+              internal_static_org_opendaylight_controller_mdsal_CreateTransaction_descriptor,
+              new java.lang.String[] { });
+          internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_descriptor =
+            getDescriptor().getMessageTypes().get(3);
+          internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_fieldAccessorTable = new
+            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+              internal_static_org_opendaylight_controller_mdsal_CreateTransactionReply_descriptor,
+              new java.lang.String[] { "TransactionPath", });
+          internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_descriptor =
+            getDescriptor().getMessageTypes().get(4);
+          internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_fieldAccessorTable = new
+            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+              internal_static_org_opendaylight_controller_mdsal_ReadyTransaction_descriptor,
+              new java.lang.String[] { });
+          internal_static_org_opendaylight_controller_mdsal_ReadyTransactionReply_descriptor =
+            getDescriptor().getMessageTypes().get(5);
+          internal_static_org_opendaylight_controller_mdsal_ReadyTransactionReply_fieldAccessorTable = new
+            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+              internal_static_org_opendaylight_controller_mdsal_ReadyTransactionReply_descriptor,
+              new java.lang.String[] { "ActorPath", });
+          internal_static_org_opendaylight_controller_mdsal_DeleteData_descriptor =
+            getDescriptor().getMessageTypes().get(6);
+          internal_static_org_opendaylight_controller_mdsal_DeleteData_fieldAccessorTable = new
+            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+              internal_static_org_opendaylight_controller_mdsal_DeleteData_descriptor,
+              new java.lang.String[] { "InstanceIdentifierPathArguments", });
+          internal_static_org_opendaylight_controller_mdsal_DeleteDataReply_descriptor =
+            getDescriptor().getMessageTypes().get(7);
+          internal_static_org_opendaylight_controller_mdsal_DeleteDataReply_fieldAccessorTable = new
+            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+              internal_static_org_opendaylight_controller_mdsal_DeleteDataReply_descriptor,
+              new java.lang.String[] { });
+          internal_static_org_opendaylight_controller_mdsal_ReadData_descriptor =
+            getDescriptor().getMessageTypes().get(8);
+          internal_static_org_opendaylight_controller_mdsal_ReadData_fieldAccessorTable = new
+            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+              internal_static_org_opendaylight_controller_mdsal_ReadData_descriptor,
+              new java.lang.String[] { "InstanceIdentifierPathArguments", });
+          internal_static_org_opendaylight_controller_mdsal_ReadDataReply_descriptor =
+            getDescriptor().getMessageTypes().get(9);
+          internal_static_org_opendaylight_controller_mdsal_ReadDataReply_fieldAccessorTable = new
+            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+              internal_static_org_opendaylight_controller_mdsal_ReadDataReply_descriptor,
+              new java.lang.String[] { "NormalizedNode", });
+          internal_static_org_opendaylight_controller_mdsal_WriteData_descriptor =
+            getDescriptor().getMessageTypes().get(10);
+          internal_static_org_opendaylight_controller_mdsal_WriteData_fieldAccessorTable = new
+            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+              internal_static_org_opendaylight_controller_mdsal_WriteData_descriptor,
+              new java.lang.String[] { "InstanceIdentifierPathArguments", "NormalizedNode", });
+          internal_static_org_opendaylight_controller_mdsal_WriteDataReply_descriptor =
+            getDescriptor().getMessageTypes().get(11);
+          internal_static_org_opendaylight_controller_mdsal_WriteDataReply_fieldAccessorTable = new
+            com.google.protobuf.GeneratedMessage.FieldAccessorTable(
+              internal_static_org_opendaylight_controller_mdsal_WriteDataReply_descriptor,
+              new java.lang.String[] { });
+          return null;
+        }
+      };
+    com.google.protobuf.Descriptors.FileDescriptor
+      .internalBuildGeneratedFileFrom(descriptorData,
+        new com.google.protobuf.Descriptors.FileDescriptor[] {
+          org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage.getDescriptor(),
+        }, assigner);
+  }
+
+  // @@protoc_insertion_point(outer_class_scope)
+}
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/resources/DataChangeListener.proto b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/resources/DataChangeListener.proto
new file mode 100644 (file)
index 0000000..f50c36f
--- /dev/null
@@ -0,0 +1,14 @@
+package org.opendaylight.controller.mdsal;
+
+import "SimpleNormalizedNode.proto";
+
+option java_package = "org.opendaylight.controller.protobuff.messages.datachange.notification";
+option java_outer_classname = "DataChangeListenerMessages";
+
+message DataChanged{
+  repeated string instanceIdentifierPathArguments =1 ;
+  required NormalizedNodeXml normalizedNodeXml = 2;
+}
+message DataChangedReply{
+
+}
\ No newline at end of file
index ec8046f5574d84c65b315cd4e9096d4002ce7726..27f3c232e726e2c3ae96d338a727717c4e771e8f 100644 (file)
@@ -1,6 +1,6 @@
 package org.opendaylight.controller.mdsal;
 
-option java_package = "org.opendaylight.controller.cluster.datastore.registration";
+option java_package = "org.opendaylight.controller.protobuff.messages.registration";
 option java_outer_classname = "ListenerRegistrationMessages";
 
 message Close {
index 31e8c58b13fcf95db1e34826be246f2a15d3992a..c86fde0c72dea6cb2f20f652794c19eb44478b80 100644 (file)
@@ -1,6 +1,6 @@
 package org.opendaylight.controller.mdsal;
 
-option java_package = "org.opendaylight.controller.cluster.datastore.shard";
+option java_package = "org.opendaylight.controller.protobuff.messages.shard";
 option java_outer_classname = "ShardManagerMessages";
 
 message FindPrimary {
index 0b260c807175fffed3551983349af063da672bfe..120913eb66f71ea854487c2f06e68b83ae19229e 100644 (file)
@@ -1,6 +1,6 @@
 package org.opendaylight.controller.mdsal;
-
-option java_package = "org.opendaylight.controller.cluster.datastore.transaction";
+import "SimpleNormalizedNode.proto";
+option java_package = "org.opendaylight.controller.protobuff.messages.transaction";
 option java_outer_classname = "ShardTransactionMessages";
 
 message CloseTransaction{
@@ -28,12 +28,26 @@ required string actorPath = 1;
 }
 
 message DeleteData {
-required string instanceIdentifierPath = 1;
+repeated string instanceIdentifierPathArguments = 1;
 }
 
 message DeleteDataReply{
 
 }
 message ReadData {
-required string intanceIdentifier=1;
+required string instanceIdentifierPathArguments=1;
+}
+
+message ReadDataReply{
+  required NormalizedNodeXml normalizedNode=1;
+}
+
+message WriteData {
+ repeated string instanceIdentifierPathArguments = 1;
+required NormalizedNodeXml normalizedNode =2;
+
+}
+
+message WriteDataReply{
+
 }
\ No newline at end of file
index 73a9aa11c800c5383910644b815024321fada379..42f87cbda6dbd661b395efccd5ae9e729420759f 100644 (file)
@@ -1,6 +1,6 @@
 package org.opendaylight.controller.mdsal;
 
-option java_package = "org.opendaylight.controller.cluster.datastore.transaction";
+option java_package = "org.opendaylight.controller.protobuff.messages.transaction";
 option java_outer_classname = "ShardTransactionChainMessages";
 
 message CloseTransactionChain {
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/resources/SimpleNormalizedNode.proto b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/main/resources/SimpleNormalizedNode.proto
new file mode 100644 (file)
index 0000000..e0b21d3
--- /dev/null
@@ -0,0 +1,10 @@
+package org.opendaylight.controller.mdsal;
+
+option java_package = "org.opendaylight.controller.protobuff.messages.common";
+option java_outer_classname = "SimpleNormalizedNodeMessage";
+
+message NormalizedNodeXml {
+  required string nodeIdentifier=1;
+  required string xmlString = 2;
+}
+
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/messages/ShardManagerMessagesTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/messages/ShardManagerMessagesTest.java
deleted file mode 100644 (file)
index f57cfc9..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-package org.opendaylight.controller.cluster.datastore.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.cluster.datastore.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/cluster/datastore/util/NormalizedNodeXmlConverterTest.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/util/NormalizedNodeXmlConverterTest.java
new file mode 100644 (file)
index 0000000..02deb5a
--- /dev/null
@@ -0,0 +1,502 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the terms of the Eclipse
+ * Public License v1.0 which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.cluster.datastore.util;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import org.custommonkey.xmlunit.Diff;
+import org.custommonkey.xmlunit.XMLUnit;
+import org.junit.Test;
+import org.opendaylight.controller.protobuff.messages.common.SimpleNormalizedNodeMessage;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
+import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
+import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.DomToNormalizedNodeParserFactory;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.serializer.DomFromNormalizedNodeSerializerFactory;
+import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.xml.sax.SAXException;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.TransformerFactoryConfigurationError;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.StringWriter;
+import java.net.URI;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+import java.util.Map;
+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
+ *
+ * @syedbahm
+ *
+ */
+
+
+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(SchemaContext context,
+      String moduleName, 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);
+  }
+
+  static DataSchemaNode findChildNode(Set<DataSchemaNode> children, 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;
+  }
+
+  private static InstanceIdentifier.NodeIdentifier getNodeIdentifier(
+      String localName) {
+    return new InstanceIdentifier.NodeIdentifier(new QName(
+        URI.create(NAMESPACE), revision, localName));
+  }
+
+  public static InstanceIdentifier.AugmentationIdentifier getAugmentIdentifier(
+      String... childNames) {
+    Set<QName> qn = Sets.newHashSet();
+
+    for (String childName : childNames) {
+      qn.add(getNodeIdentifier(childName).getNodeType());
+    }
+
+    return new InstanceIdentifier.AugmentationIdentifier(qn);
+  }
+
+
+  private static ContainerNode augmentChoiceExpectedNode() {
+
+    DataContainerNodeBuilder<InstanceIdentifier.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(String yangPath, String xmlPath, ContainerNode expectedNode)
+      throws Exception {
+    SchemaContext schema = parseTestSchema(yangPath);
+    this.xmlPath = xmlPath;
+    this.containerNode =
+        (ContainerSchemaNode) getSchemaNode(schema, "test", "container");
+    this.expectedNode = expectedNode;
+  }
+
+  SchemaContext parseTestSchema(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);
+
+    Iterable<Element> els =
+        DomFromNormalizedNodeSerializerFactory
+            .getInstance(XmlDocumentUtils.getDocument(),
+                DomUtils.defaultValueCodecProvider())
+            .getContainerNodeSerializer().serialize(containerNode, built);
+
+    Element el = els.iterator().next();
+
+    XMLUnit.setIgnoreWhitespace(true);
+    XMLUnit.setIgnoreComments(true);
+
+    System.out.println(toString(doc.getDocumentElement()));
+    System.out.println(toString(el));
+
+    boolean diff =
+        new Diff(
+            XMLUnit.buildControlDocument(toString(doc.getDocumentElement())),
+            XMLUnit.buildTestDocument(toString(el))).similar();
+  }
+
+  private static ContainerNode listLeafListWithAttributes() {
+    DataContainerNodeBuilder<InstanceIdentifier.NodeIdentifier, ContainerNode> b =
+        Builders.containerBuilder();
+    b.withNodeIdentifier(getNodeIdentifier("container"));
+
+    CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder =
+        Builders.mapBuilder().withNodeIdentifier(getNodeIdentifier("list"));
+
+    Map<QName, Object> predicates = Maps.newHashMap();
+    predicates.put(getNodeIdentifier("uint32InList").getNodeType(), 3L);
+
+    DataContainerNodeBuilder<InstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> list1Builder =
+        Builders.mapEntryBuilder().withNodeIdentifier(
+            new InstanceIdentifier.NodeIdentifierWithPredicates(
+                getNodeIdentifier("list").getNodeType(), predicates));
+    NormalizedNodeBuilder<InstanceIdentifier.NodeIdentifier, Object, LeafNode<Object>> uint32InListBuilder =
+        Builders.leafBuilder().withNodeIdentifier(
+            getNodeIdentifier("uint32InList"));
+
+    list1Builder.withChild(uint32InListBuilder.withValue(3L).build());
+
+    listBuilder.withChild(list1Builder.build());
+    b.withChild(listBuilder.build());
+
+    NormalizedNodeBuilder<InstanceIdentifier.NodeIdentifier, Object, LeafNode<Object>> booleanBuilder =
+        Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("boolean"));
+    booleanBuilder.withValue(false);
+    b.withChild(booleanBuilder.build());
+
+    ListNodeBuilder<Object, LeafSetEntryNode<Object>> leafListBuilder =
+        Builders.leafSetBuilder().withNodeIdentifier(
+            getNodeIdentifier("leafList"));
+
+    NormalizedNodeBuilder<InstanceIdentifier.NodeWithValue, Object, LeafSetEntryNode<Object>> leafList1Builder =
+        Builders.leafSetEntryBuilder().withNodeIdentifier(
+            new InstanceIdentifier.NodeWithValue(getNodeIdentifier("leafList")
+                .getNodeType(), "a"));
+
+    leafList1Builder.withValue("a");
+
+    leafListBuilder.withChild(leafList1Builder.build());
+    b.withChild(leafListBuilder.build());
+
+    return b.build();
+  }
+
+
+  @Test
+  public void testConversionWithAttributes() throws Exception {
+    init("/test.yang", "/simple_xml_with_attributes.xml",
+        listLeafListWithAttributes());
+    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);
+
+    Iterable<Element> els =
+        DomFromNormalizedNodeSerializerFactory
+            .getInstance(XmlDocumentUtils.getDocument(),
+                DomUtils.defaultValueCodecProvider())
+            .getContainerNodeSerializer().serialize(containerNode, built);
+
+    Element el = els.iterator().next();
+
+    XMLUnit.setIgnoreWhitespace(true);
+    XMLUnit.setIgnoreComments(true);
+
+    System.out.println(toString(doc.getDocumentElement()));
+    System.out.println(toString(el));
+
+    boolean diff =
+        new Diff(
+            XMLUnit.buildControlDocument(toString(doc.getDocumentElement())),
+            XMLUnit.buildTestDocument(toString(el))).similar();
+  }
+
+
+  private Document loadDocument(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(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(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);
+    boolean diff =
+        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);
+    boolean diff =
+        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 testInMemoryTestModelProtoBuffEncoding() throws Exception {
+
+    SimpleNormalizedNodeMessage.NormalizedNodeXml nnXml =
+        EncoderDecoderUtil.encode(parseTestSchema("/odl-datastore-test.yang"),
+            TestModel.createFamily());
+
+    Document convertedDoc =
+        EncoderDecoderUtil.factory.newDocumentBuilder().parse(
+            new ByteArrayInputStream(nnXml.getXmlString().getBytes("utf-8")));
+    System.out.println(toString(convertedDoc.getDocumentElement()));
+
+    // now we will try to convert xml back to normalize node.
+    ContainerNode cn =
+        (ContainerNode) EncoderDecoderUtil.decode(
+            parseTestSchema("/odl-datastore-test.yang"), nnXml);
+    junit.framework.Assert.assertEquals(TestModel.createFamily(), cn);
+
+
+  }
+}
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/util/TestModel.java b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/java/org/opendaylight/controller/cluster/datastore/util/TestModel.java
new file mode 100644 (file)
index 0000000..81878ba
--- /dev/null
@@ -0,0 +1,372 @@
+package org.opendaylight.controller.cluster.datastore.util;
+
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
+import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetEntryNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafSetNodeBuilder;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
+
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapEntry;
+import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapEntryBuilder;
+import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapNodeBuilder;
+
+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_QNAME = QName.create(
+      "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:aug",
+      "2014-03-13", "name");
+
+  public static final QName DESC_QNAME = QName.create(TEST_QNAME, "desc");
+  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 InstanceIdentifier TEST_PATH = InstanceIdentifier
+      .of(TEST_QNAME);
+  public static final InstanceIdentifier DESC_PATH = InstanceIdentifier
+      .builder(TEST_PATH).node(DESC_QNAME).build();
+  public static final InstanceIdentifier OUTER_LIST_PATH = InstanceIdentifier
+      .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-15", "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 InstanceIdentifier FAMILY_PATH = InstanceIdentifier
+      .of(FAMILY_QNAME);
+  public static final InstanceIdentifier FAMILY_DESC_PATH = InstanceIdentifier
+      .builder(FAMILY_PATH).node(DESC_QNAME).build();
+  public static final InstanceIdentifier CHILDREN_PATH = InstanceIdentifier
+      .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 InstanceIdentifier CHILDREN_1_PATH = InstanceIdentifier
+      .builder(CHILDREN_PATH)
+      .nodeWithKey(CHILDREN_QNAME, CHILD_NUMBER_QNAME, FIRST_CHILD_ID) //
+      .build();
+  private static final InstanceIdentifier CHILDREN_1_NAME_PATH =
+      InstanceIdentifier.builder(CHILDREN_PATH)
+          .nodeWithKey(CHILDREN_QNAME, CHILD_NAME_QNAME, FIRST_CHILD_NAME) //
+          .build();
+
+  private static final InstanceIdentifier CHILDREN_2_PATH = InstanceIdentifier
+      .builder(CHILDREN_PATH)
+      .nodeWithKey(CHILDREN_QNAME, CHILD_NUMBER_QNAME, SECOND_CHILD_ID) //
+      .build();
+  private static final InstanceIdentifier CHILDREN_2_NAME_PATH =
+      InstanceIdentifier.builder(CHILDREN_PATH)
+          .nodeWithKey(CHILDREN_QNAME, CHILD_NAME_QNAME, SECOND_CHILD_NAME) //
+          .build();
+
+
+  private static final InstanceIdentifier GRAND_CHILD_1_PATH =
+      InstanceIdentifier.builder(CHILDREN_1_PATH)
+          .node(GRAND_CHILDREN_QNAME)
+          //
+          .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME,
+              FIRST_GRAND_CHILD_ID) //
+          .build();
+
+  private static final InstanceIdentifier GRAND_CHILD_1_NAME_PATH =
+      InstanceIdentifier.builder(CHILDREN_1_PATH)
+          .node(GRAND_CHILDREN_QNAME)
+          //
+          .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NAME_QNAME,
+              FIRST_GRAND_CHILD_NAME) //
+          .build();
+
+  private static final InstanceIdentifier GRAND_CHILD_2_PATH =
+      InstanceIdentifier.builder(CHILDREN_2_PATH)
+          .node(GRAND_CHILDREN_QNAME)
+          //
+          .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME,
+              SECOND_GRAND_CHILD_ID) //
+          .build();
+
+  private static final InstanceIdentifier GRAND_CHILD_2_NAME_PATH =
+      InstanceIdentifier.builder(CHILDREN_2_PATH)
+          .node(GRAND_CHILDREN_QNAME)
+          //
+          .nodeWithKey(GRAND_CHILDREN_QNAME, GRAND_CHILD_NAME_QNAME,
+              SECOND_GRAND_CHILD_NAME) //
+          .build();
+
+  private static final InstanceIdentifier DESC_PATH_ID = InstanceIdentifier
+      .builder(DESC_PATH).build();
+  private static final InstanceIdentifier OUTER_LIST_1_PATH =
+      InstanceIdentifier.builder(OUTER_LIST_PATH)
+          .nodeWithKey(OUTER_LIST_QNAME, ID_QNAME, ONE_ID) //
+          .build();
+
+  private static final InstanceIdentifier OUTER_LIST_2_PATH =
+      InstanceIdentifier.builder(OUTER_LIST_PATH)
+          .nodeWithKey(OUTER_LIST_QNAME, ID_QNAME, TWO_ID) //
+          .build();
+
+  private static final InstanceIdentifier TWO_TWO_PATH = InstanceIdentifier
+      .builder(OUTER_LIST_2_PATH).node(INNER_LIST_QNAME) //
+      .nodeWithKey(INNER_LIST_QNAME, NAME_QNAME, TWO_TWO_NAME) //
+      .build();
+
+  private static final InstanceIdentifier TWO_TWO_VALUE_PATH =
+      InstanceIdentifier.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
+   *
+   * <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 InstanceIdentifier.NodeIdentifier(schemaContext.getQName()))
+        .withChild(createTestContainer()).build();
+
+  }
+
+  public static ContainerNode createTestContainer() {
+
+
+    final LeafSetEntryNode<Object> nike =
+        ImmutableLeafSetEntryNodeBuilder
+            .create()
+            .withNodeIdentifier(
+                new InstanceIdentifier.NodeWithValue(QName.create(TEST_QNAME,
+                    "shoe"), "nike")).withValue("nike").build();
+    final LeafSetEntryNode<Object> puma =
+        ImmutableLeafSetEntryNodeBuilder
+            .create()
+            .withNodeIdentifier(
+                new InstanceIdentifier.NodeWithValue(QName.create(TEST_QNAME,
+                    "shoe"), "puma")).withValue("puma").build();
+    final LeafSetNode<Object> shoes =
+        ImmutableLeafSetNodeBuilder
+            .create()
+            .withNodeIdentifier(
+                new InstanceIdentifier.NodeIdentifier(QName.create(TEST_QNAME,
+                    "shoe"))).withChild(nike).withChild(puma).build();
+
+
+    final LeafSetEntryNode<Object> five =
+        ImmutableLeafSetEntryNodeBuilder
+            .create()
+            .withNodeIdentifier(
+                (new InstanceIdentifier.NodeWithValue(QName.create(TEST_QNAME,
+                    "number"), 5))).withValue(5).build();
+    final LeafSetEntryNode<Object> fifteen =
+        ImmutableLeafSetEntryNodeBuilder
+            .create()
+            .withNodeIdentifier(
+                (new InstanceIdentifier.NodeWithValue(QName.create(TEST_QNAME,
+                    "number"), 15))).withValue(15).build();
+    final LeafSetNode<Object> numbers =
+        ImmutableLeafSetNodeBuilder
+            .create()
+            .withNodeIdentifier(
+                new InstanceIdentifier.NodeIdentifier(QName.create(TEST_QNAME,
+                    "number"))).withChild(five).withChild(fifteen).build();
+
+
+    Set<QName> childAugmentations = new HashSet<>();
+    childAugmentations.add(AUG_QNAME);
+    final InstanceIdentifier.AugmentationIdentifier augmentationIdentifier =
+        new InstanceIdentifier.AugmentationIdentifier(null, childAugmentations);
+    final AugmentationNode augmentationNode =
+        Builders.augmentationBuilder()
+            .withNodeIdentifier(augmentationIdentifier)
+            .withChild(ImmutableNodes.leafNode(AUG_QNAME, "First Test"))
+            .build();
+    return ImmutableContainerNodeBuilder
+        .create()
+        .withNodeIdentifier(new InstanceIdentifier.NodeIdentifier(TEST_QNAME))
+        .withChild(ImmutableNodes.leafNode(DESC_QNAME, DESC))
+        .withChild(augmentationNode)
+        .withChild(shoes)
+        .withChild(numbers)
+        .withChild(
+            mapNodeBuilder(OUTER_LIST_QNAME)
+                .withChild(mapEntry(OUTER_LIST_QNAME, ID_QNAME, ONE_ID))
+                .withChild(BAR_NODE).build()).build();
+
+  }
+
+
+  public static ContainerNode createFamily() {
+    final DataContainerNodeAttrBuilder<InstanceIdentifier.NodeIdentifier, ContainerNode> familyContainerBuilder =
+        ImmutableContainerNodeBuilder.create().withNodeIdentifier(
+            new InstanceIdentifier.NodeIdentifier(FAMILY_QNAME));
+
+    final CollectionNodeBuilder<MapEntryNode, MapNode> childrenBuilder =
+        mapNodeBuilder(CHILDREN_QNAME);
+
+    final DataContainerNodeBuilder<InstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> firstChildBuilder =
+        mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, FIRST_CHILD_ID);
+    final DataContainerNodeBuilder<InstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> secondChildBuilder =
+        mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, SECOND_CHILD_ID);
+
+    final DataContainerNodeBuilder<InstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> firstGrandChildBuilder =
+        mapEntryBuilder(GRAND_CHILDREN_QNAME, GRAND_CHILD_NUMBER_QNAME,
+            FIRST_GRAND_CHILD_ID);
+    final DataContainerNodeBuilder<InstanceIdentifier.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();
+  }
+
+}
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
new file mode 100644 (file)
index 0000000..b0758da
--- /dev/null
@@ -0,0 +1,42 @@
+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/resources/augment_choice.xml b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/augment_choice.xml
new file mode 100644 (file)
index 0000000..c5a581c
--- /dev/null
@@ -0,0 +1,15 @@
+<container xmlns="urn:opendaylight:params:xml:ns:yang:controller:test">
+
+    <c2Leaf>2</c2Leaf>
+    <c2DeepChoiceCase1Leaf2>2</c2DeepChoiceCase1Leaf2>
+    <!--<c2DeepChoiceCase1Leaf1>2</c2DeepChoiceCase1Leaf1>-->
+
+    <c3Leaf>3</c3Leaf>
+
+    <augLeaf>augment</augLeaf>
+
+    <c1Leaf>1</c1Leaf>
+    <c1Leaf_AnotherAugment>1</c1Leaf_AnotherAugment>
+    <deepLeafc1>1</deepLeafc1>
+    <!--<deepLeafc2>1</deepLeafc2>-->
+</container>
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/augment_choice.yang b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/augment_choice.yang
new file mode 100644 (file)
index 0000000..c2a57f6
--- /dev/null
@@ -0,0 +1,109 @@
+// vi: set smarttab et sw=4 tabstop=4:
+module test {
+    yang-version 1;
+    namespace "urn:opendaylight:params:xml:ns:yang:controller:test";
+    prefix "test";
+
+    organization "Cisco Systems, Inc.";
+
+    revision "2014-3-13" {
+        description
+            "Initial revision";
+    }
+
+
+    container container {
+        choice ch2{}
+        choice ch3{
+            case c3 {
+                leaf c3Leaf {
+                    type string;
+                }
+            }
+        }
+    }
+
+    augment "/container/" {
+        leaf augLeaf {
+            type string;
+        }
+    }
+
+    augment "/container/" {
+        choice ch{}
+    }
+
+    augment "/container/ch/" {
+        case c1 {
+            leaf c1Leaf {
+                type string;
+            }
+        }
+
+        leaf c12 {
+            type string;
+        }
+    }
+    augment "/container/ch/c1/" {
+        leaf c1Leaf_AnotherAugment {
+            type string;
+        }
+
+        choice deepChoice{}
+    }
+
+    augment "/container/ch3/" {
+        case c32 {
+            leaf c32Leaf {
+                type string;
+            }
+        }
+
+        leaf c34LeafS {
+            type string;
+        }
+    }
+
+
+    augment "/container/ch/c1/deepChoice/" {
+        case deepCase1 {
+            leaf deepLeafc1 {
+                type string;
+            }
+        }
+        case deepCase2 {
+            leaf deepLeafc2 {
+                type string;
+            }
+        }
+    }
+
+    augment "/container/ch2/" {
+        case c2 {
+            leaf c2Leaf {
+                type string;
+            }
+
+            choice c2DeepChoice {
+                case c2DeepChoiceCase1 {
+                    leaf c2DeepChoiceCase1Leaf1 {
+                        type string;
+                    }
+                }
+                case c2DeepChoiceCase2 {
+                    leaf c2DeepChoiceCase1Leaf2 {
+                        type string;
+                    }
+                }
+            }
+        }
+    }
+
+    augment "/container/ch2/" {
+        leaf c22Leaf {
+            type string;
+        }
+    }
+
+
+}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/odl-datastore-test.yang b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/odl-datastore-test.yang
new file mode 100644 (file)
index 0000000..32ec277
--- /dev/null
@@ -0,0 +1,33 @@
+module odl-datastore-test {
+    yang-version 1;
+    namespace "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:notification-test";
+    prefix "notification-test-using-family-model";
+
+    revision "2014-04-15" {
+        description "Family structure created on ";
+    }
+
+    container family {
+        leaf desc {
+            type string;
+        }
+        list children {
+            key child-number;
+            leaf child-number {
+                type uint16;
+            }
+            leaf child-name {
+                type string;
+            }
+           list grand-children {
+                key grand-child-number;
+                leaf grand-child-number {
+                    type uint16;
+                }
+                leaf grand-child-name {
+                    type string;
+                }
+            }
+        }
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/simple_xml_with_attributes.xml b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/simple_xml_with_attributes.xml
new file mode 100644 (file)
index 0000000..0316d7a
--- /dev/null
@@ -0,0 +1,12 @@
+<container xmlns="urn:opendaylight:params:xml:ns:yang:controller:test" name="test" xmlns:foo="http://www.foo.com/"
+           foo:baz="baz">
+
+    <list list="on list entry">
+        <uint32InList name="test" foo:baz="baz">3</uint32InList>
+    </list>
+
+    <boolean xmlns:leaf="test:namespace:in:leaf" leaf:a="b">false</boolean>
+
+    <leafList foo:b="b">a</leafList>
+
+</container>
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/test.yang b/opendaylight/md-sal/sal-protocolbuffer-encoding/src/test/resources/test.yang
new file mode 100644 (file)
index 0000000..5f0e500
--- /dev/null
@@ -0,0 +1,225 @@
+// vi: set smarttab et sw=4 tabstop=4:
+module test {
+    yang-version 1;
+    namespace "urn:opendaylight:params:xml:ns:yang:controller:test";
+    prefix "test";
+
+    organization "Cisco Systems, Inc.";
+
+    revision "2014-3-13" {
+        description
+            "Initial revision";
+    }
+
+    grouping listGroup {
+        list list {
+            key "uint32InList";
+
+            leaf uint32InList {
+                type uint32;
+            }
+
+            container containerInList{
+                leaf uint32 {
+                    type uint32;
+                }
+                leaf uint16 {
+                    type uint16;
+                }
+            }
+        }
+     }
+
+     grouping innerContainerGrouping {
+        container innerContainer {
+            leaf uint16 {
+                type uint16;
+            }
+
+            container innerInnerContainer {
+
+                leaf uint16 {
+                    type uint16;
+                }
+
+                leaf uint32 {
+                    type uint32;
+                }
+            }
+        }
+     }
+
+    container container {
+        leaf uint32 {
+            type uint32;
+        }
+
+        leaf decimal64 {
+            type decimal64 {
+                fraction-digits 2;
+            }
+        }
+
+        leaf boolean {
+            type boolean;
+        }
+
+        leaf binary {
+            type binary;
+        }
+
+        leaf string {
+            type string;
+        }
+
+        uses listGroup {
+            augment "list/" {
+                leaf stringAugmentedToList{
+                    type string;
+                }
+
+                choice choiceInList {
+                    case caseInList1 {
+                        leaf stringAugmentedToListInCase1 {
+                            type string;
+                        }
+                    }
+                    case caseInList2 {
+                        leaf stringAugmentedToListInCase2 {
+                            type string;
+                        }
+                    }
+                }
+            }
+        }
+
+        list directList {
+            leaf stringInDirectList {
+                type string;
+            }
+        }
+
+        uses innerContainerGrouping;
+
+        choice choice{}
+        choice choice2{}
+
+        leaf-list leafList {
+            type string;
+        }
+
+        leaf identityRef {
+            type identityref {
+                base test-identity;
+            }
+        }
+
+        /* TODO test modification with empty type
+        leaf empty {
+             type empty;
+         }
+         */
+    }
+
+    augment "/container/" {
+        leaf augmentUint32 {
+            type uint32;
+        }
+    }
+
+    augment "/container/directList/" {
+        leaf augmentedString {
+            type uint32;
+        }
+    }
+
+    augment "/container/choice/" {
+        case test-identity-augment {
+            when "/container/identityRef = 'test-identity'";
+            leaf augmentString1 {
+                type string;
+            }
+
+            leaf augmentInt1 {
+                type uint32;
+            }
+        }
+        case test-identity-augment2 {
+            when "/container/identityRef = 'test-identity2'";
+            leaf augmentString2 {
+                type string;
+            }
+
+            leaf augmentInt2 {
+                type uint32;
+            }
+        }
+    }
+
+    augment "/container/choice/test-identity-augment/" {
+
+        choice augmentedChoiceInCase {
+
+            case augmentedCaseInAugmentedChoice {
+                leaf stringInAugmentedCaseInAugmentedChoice {
+                    type string;
+                }
+            }
+
+            case augmentedCaseInAugmentedChoice2 {
+                leaf stringInAugmentedCaseInAugmentedChoice2 {
+                    type string;
+                }
+            }
+        }
+    }
+
+    augment "/container/choice/test-identity-augment/augmentedChoiceInCase/" {
+        case augmentedCaseInAugmentedChoiceFromAugment {
+            leaf stringInAugmentedCaseInAugmentedChoiceFromAugment {
+                type string;
+            }
+        }
+    }
+
+    augment "/container/choice2/" {
+        case test-identity-augment {
+            when "/container/identityRef = 'test-identity'";
+            container augmentContainer {
+                leaf augmentStringInaugmentContainer {
+                    type string;
+                }
+            }
+        }
+        case test-identity-augment2 {
+            when "/container/identityRef = 'test-identity2'";
+            list augmentedList {
+                leaf augmentStringInaugmentList {
+                    type string;
+                }
+            }
+        }
+    }
+
+
+    augment "/container/choice2/test-identity-augment2/augmentedList/" {
+
+        container augmentedContainerInAugmentedListInAugmentedCase {
+            leaf-list leafInAugmentedContainerInAugmentedListInAugmentedCase {
+                type uint32;
+            }
+        }
+
+        list augmentedListInAugmentedListInAugmentedCase {
+            leaf-list leafInAugmentedListInAugmentedListInAugmentedCase {
+                    type uint32;
+                }
+        }
+    }
+
+    identity test-identity {}
+    identity test-identity2 {
+        base test-identity;
+    }
+
+}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/pom.xml b/opendaylight/md-sal/sal-remoterpc-connector/implementation/pom.xml
deleted file mode 100644 (file)
index 63b80e9..0000000
+++ /dev/null
@@ -1,176 +0,0 @@
-<?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>sal-parent</artifactId>
-    <version>1.1-SNAPSHOT</version>
-    <relativePath>../..</relativePath>
-  </parent>
-
-  <artifactId>sal-remoterpc-connector</artifactId>
-  <packaging>bundle</packaging>
-
-  <properties>
-    <stax.version>1.0.1</stax.version>
-    <zeromq.version>0.3.1</zeromq.version>
-  </properties>
-
-  <dependencies>
-    <dependency>
-      <groupId>${project.groupId}</groupId>
-      <artifactId>sal-common-util</artifactId>
-      <version>${project.version}</version>
-    </dependency>
-    <dependency>
-      <groupId>${project.groupId}</groupId>
-      <artifactId>sal-connector-api</artifactId>
-      <version>${project.version}</version>
-    </dependency>
-    <!-- MD Sal interdependencies -->
-    <dependency>
-      <groupId>${project.groupId}</groupId>
-      <artifactId>sal-core-api</artifactId>
-      <version>${project.version}</version>
-    </dependency>
-    <dependency>
-      <groupId>com.fasterxml.jackson.core</groupId>
-      <artifactId>jackson-annotations</artifactId>
-    </dependency>
-
-    <dependency>
-      <groupId>com.fasterxml.jackson.core</groupId>
-      <artifactId>jackson-core</artifactId>
-    </dependency>
-
-    <dependency>
-      <groupId>com.fasterxml.jackson.core</groupId>
-      <artifactId>jackson-databind</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>com.google.guava</groupId>
-      <artifactId>guava</artifactId>
-    </dependency>
-
-    <!-- Tests -->
-    <dependency>
-      <groupId>junit</groupId>
-      <artifactId>junit</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.mockito</groupId>
-      <artifactId>mockito-all</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>remoterpc-routingtable.implementation</artifactId>
-      <version>${project.version}</version>
-    </dependency>
-
-    <!-- AD Sal -->
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>sal</artifactId>
-    </dependency>
-
-    <!-- Yang tools -->
-    <dependency>
-      <groupId>org.opendaylight.yangtools</groupId>
-      <artifactId>yang-common</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.yangtools</groupId>
-      <artifactId>yang-data-api</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.yangtools</groupId>
-      <artifactId>yang-data-impl</artifactId>
-    </dependency>
-
-    <!-- Third Party -->
-    <dependency>
-      <groupId>org.osgi</groupId>
-      <artifactId>org.osgi.core</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.slf4j</groupId>
-      <artifactId>slf4j-api</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.zeromq</groupId>
-      <artifactId>jeromq</artifactId>
-      <version>${zeromq.version}</version>
-    </dependency>
-
-    <dependency>
-      <groupId>stax</groupId>
-      <artifactId>stax-api</artifactId>
-      <version>${stax.version}</version>
-    </dependency>
-    <dependency>
-      <groupId>ch.qos.logback</groupId>
-      <artifactId>logback-classic</artifactId>
-      <scope>test</scope>
-    </dependency>
-  </dependencies>
-
-  <build>
-    <plugins>
-      <plugin>
-        <groupId>org.apache.felix</groupId>
-        <artifactId>maven-bundle-plugin</artifactId>
-        <extensions>true</extensions>
-        <configuration>
-          <instructions>
-            <Import-Package>*,
-                            !org.codehaus.enunciate.jaxrs</Import-Package>
-            <Export-Package>org.opendaylight.controller.config.yang.md.sal.remote.rpc,
-                            org.opendaylight.controller.sal.connector.remoterpc.util,
-                            org.opendaylight.controller.sal.connector.remoterpc.dto,
-                            org.opendaylight.controller.sal.connector.remoterpc.RemoteRpcClient,
-                            org.opendaylight.controller.sal.connector.remoterpc.RemoteRpcServer,
-                            org.opendaylight.controller.sal.connector.remoterpc.RemoteRpcProvider</Export-Package>
-            <Bundle-Name>${project.groupId}.${project.artifactId}</Bundle-Name>
-          </instructions>
-        </configuration>
-      </plugin>
-
-      <plugin>
-        <groupId>org.opendaylight.yangtools</groupId>
-        <artifactId>yang-maven-plugin</artifactId>
-        <executions>
-          <execution>
-            <goals>
-              <goal>generate-sources</goal>
-            </goals>
-            <configuration>
-              <codeGenerators>
-                <generator>
-                  <codeGeneratorClass>org.opendaylight.controller.config.yangjmxgenerator.plugin.JMXGenerator</codeGeneratorClass>
-                  <outputBaseDir>${jmxGeneratorPath}</outputBaseDir>
-                  <additionalConfiguration>
-                    <namespaceToPackage1>urn:opendaylight:params:xml:ns:yang:controller==org.opendaylight.controller.config.yang</namespaceToPackage1>
-                  </additionalConfiguration>
-                </generator>
-                <generator>
-                  <codeGeneratorClass>org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl</codeGeneratorClass>
-                  <outputBaseDir>${salGeneratorPath}</outputBaseDir>
-                </generator>
-                <generator>
-                  <codeGeneratorClass>org.opendaylight.yangtools.yang.unified.doc.generator.maven.DocumentationGeneratorImpl</codeGeneratorClass>
-                  <outputBaseDir>target/site/models</outputBaseDir>
-                </generator>
-
-                <generator>
-                  <codeGeneratorClass>org.opendaylight.yangtools.yang.unified.doc.generator.maven.DocumentationGeneratorImpl</codeGeneratorClass>
-                  <outputBaseDir>target/site/models</outputBaseDir>
-                </generator>
-              </codeGenerators>
-              <inspectDependencies>true</inspectDependencies>
-            </configuration>
-          </execution>
-        </executions>
-      </plugin>
-    </plugins>
-  </build>
-</project>
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/config/yang/md/sal/remote/rpc/ZeroMQServerModule.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/config/yang/md/sal/remote/rpc/ZeroMQServerModule.java
deleted file mode 100644 (file)
index e3ac9ba..0000000
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yang.md.sal.remote.rpc;
-
-import org.opendaylight.controller.sal.connector.remoterpc.ClientImpl;
-import org.opendaylight.controller.sal.connector.remoterpc.RemoteRpcProvider;
-import org.opendaylight.controller.sal.connector.remoterpc.RoutingTableProvider;
-import org.opendaylight.controller.sal.connector.remoterpc.ServerImpl;
-import org.opendaylight.controller.sal.core.api.Broker;
-import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
-import org.osgi.framework.BundleContext;
-
-/**
- *
- */
-public final class ZeroMQServerModule
-extends org.opendaylight.controller.config.yang.md.sal.remote.rpc.AbstractZeroMQServerModule {
-
-    private static final Integer ZEROMQ_ROUTER_PORT = 5554;
-    private BundleContext bundleContext;
-
-    public ZeroMQServerModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
-            final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
-        super(identifier, dependencyResolver);
-    }
-
-    public ZeroMQServerModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
-            final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,
-            final ZeroMQServerModule oldModule, final java.lang.AutoCloseable oldInstance) {
-
-        super(identifier, dependencyResolver, oldModule, oldInstance);
-    }
-
-    @Override
-    protected void customValidation() {
-        // Add custom validation for module attributes here.
-    }
-
-    @Override
-    public java.lang.AutoCloseable createInstance() {
-
-        Broker broker = getDomBrokerDependency();
-
-        final int port = getPort() != null ? getPort() : ZEROMQ_ROUTER_PORT;
-
-        ServerImpl serverImpl = new ServerImpl(port);
-
-        ClientImpl clientImpl = new ClientImpl();
-
-        RoutingTableProvider provider = new RoutingTableProvider(bundleContext);//,serverImpl);
-
-        RemoteRpcProvider facade = new RemoteRpcProvider(serverImpl, clientImpl);
-        facade.setRoutingTableProvider(provider);
-        facade.setContext(bundleContext);
-        facade.setRpcProvisionRegistry((RpcProvisionRegistry) broker);
-
-        broker.registerProvider(facade, bundleContext);
-        return facade;
-    }
-
-    public void setBundleContext(final BundleContext bundleContext) {
-        this.bundleContext = bundleContext;
-    }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/config/yang/md/sal/remote/rpc/ZeroMQServerModuleFactory.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/config/yang/md/sal/remote/rpc/ZeroMQServerModuleFactory.java
deleted file mode 100644 (file)
index 0c2a370..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yang.md.sal.remote.rpc;
-
-import org.opendaylight.controller.config.api.DependencyResolver;
-import org.opendaylight.controller.config.api.DynamicMBeanWithInstance;
-import org.opendaylight.controller.config.spi.Module;
-import org.osgi.framework.BundleContext;
-
-/**
-*
-*/
-public class ZeroMQServerModuleFactory extends org.opendaylight.controller.config.yang.md.sal.remote.rpc.AbstractZeroMQServerModuleFactory
-{
-
-    @Override
-    public Module createModule(String instanceName, DependencyResolver dependencyResolver, BundleContext bundleContext) {
-        ZeroMQServerModule module = (ZeroMQServerModule) super.createModule(instanceName, dependencyResolver, bundleContext);
-        module.setBundleContext(bundleContext);
-        return module;
-    }
-
-    @Override
-    public Module createModule(String instanceName, DependencyResolver dependencyResolver,
-            DynamicMBeanWithInstance old, BundleContext bundleContext) throws Exception {
-        ZeroMQServerModule module = (ZeroMQServerModule) super.createModule(instanceName, dependencyResolver, old,bundleContext);
-        module.setBundleContext(bundleContext);
-        return module;
-    }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/CapturedMessageHandler.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/CapturedMessageHandler.java
deleted file mode 100644 (file)
index 2dc5eee..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sal.connector.remoterpc;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.zeromq.ZMQ;
-
-public class CapturedMessageHandler implements Runnable {
-
-  private Logger _logger = LoggerFactory.getLogger(CapturedMessageHandler.class);
-
-  private ZMQ.Socket socket;
-
-  public CapturedMessageHandler(ZMQ.Socket socket){
-    this.socket = socket;
-  }
-
-  @Override
-  public void run(){
-
-    try {
-      while (!Thread.currentThread().isInterrupted()){
-        String message = socket.recvStr();
-        _logger.debug("Captured [{}]", message);
-      }
-    } catch (Exception e) {
-      _logger.error("Exception raised [{}]", e.getMessage());
-    }
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ClientImpl.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ClientImpl.java
deleted file mode 100644 (file)
index 200ebae..0000000
+++ /dev/null
@@ -1,254 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sal.connector.remoterpc;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-import static com.google.common.base.Preconditions.checkState;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.FutureTask;
-import java.util.concurrent.TimeUnit;
-
-import org.opendaylight.controller.sal.common.util.RpcErrors;
-import org.opendaylight.controller.sal.common.util.Rpcs;
-import org.opendaylight.controller.sal.connector.api.RpcRouter;
-import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable;
-import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTableException;
-import org.opendaylight.controller.sal.connector.remoterpc.api.SystemException;
-import org.opendaylight.controller.sal.connector.remoterpc.dto.Message;
-import org.opendaylight.controller.sal.connector.remoterpc.dto.RouteIdentifierImpl;
-import org.opendaylight.controller.sal.connector.remoterpc.util.XmlUtils;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.RpcError;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.zeromq.ZMQ;
-
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-
-/**
- * An implementation of {@link org.opendaylight.controller.sal.core.api.RpcImplementation} that makes
- * remote RPC calls
- */
-public class ClientImpl implements RemoteRpcClient {
-
-  private final Logger _logger = LoggerFactory.getLogger(ClientImpl.class);
-
-  private final ZMQ.Context context = ZMQ.context(1);
-  private final ClientRequestHandler handler;
-  private RoutingTableProvider routingTableProvider;
-
-  public ClientImpl(){
-    handler = new ClientRequestHandler(context);
-    start();
-  }
-
-  public ClientImpl(ClientRequestHandler handler){
-    this.handler = handler;
-    start();
-  }
-
-  public RoutingTableProvider getRoutingTableProvider() {
-    return routingTableProvider;
-  }
-
-  @Override
-  public void setRoutingTableProvider(RoutingTableProvider routingTableProvider) {
-    this.routingTableProvider = routingTableProvider;
-  }
-
-  @Override
-  public void start() {/*NOOPS*/}
-
-  @Override
-  public void stop() {
-    closeZmqContext();
-    handler.close();
-    _logger.info("Stopped");
-  }
-
-  @Override
-  public void close(){
-    stop();
-  }
-
-  /**
-   * Finds remote server that can execute this rpc and sends a message to it
-   * requesting execution.
-   * The call blocks until a response from remote server is received. Its upto
-   * the client of this API to implement a timeout functionality.
-   *
-   * @param rpc   remote service to be executed
-   * @param input payload for the remote service
-   * @return
-   */
-  public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(QName rpc, CompositeNode input) {
-    RouteIdentifierImpl routeId = new RouteIdentifierImpl();
-    routeId.setType(rpc);
-
-    String address = lookupRemoteAddressForGlobalRpc(routeId);
-    return sendMessage(input, routeId, address);
-  }
-
-  /**
-   * Finds remote server that can execute this routed rpc and sends a message to it
-   * requesting execution.
-   * The call blocks until a response from remote server is received. Its upto
-   * the client of this API to implement a timeout functionality.
-   *
-   * @param rpc
-   *          rpc to be called
-   * @param identifier
-   *          instance identifier on which rpc is to be executed
-   * @param input
-   *          payload
-   * @return
-   */
-  public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(QName rpc, InstanceIdentifier identifier, CompositeNode input) {
-
-    RouteIdentifierImpl routeId = new RouteIdentifierImpl();
-    routeId.setType(rpc);
-    routeId.setRoute(identifier);
-
-    String address = lookupRemoteAddressForRpc(routeId);
-
-    return sendMessage(input, routeId, address);
-  }
-
-  private ListenableFuture<RpcResult<CompositeNode>> sendMessage(CompositeNode input, RouteIdentifierImpl routeId, String address) {
-    Message request = new Message.MessageBuilder()
-        .type(Message.MessageType.REQUEST)
-        .sender(Context.getInstance().getLocalUri())
-        .recipient(address)
-        .route(routeId)
-        .payload(XmlUtils.compositeNodeToXml(input))
-        .build();
-
-    List<RpcError> errors = new ArrayList<RpcError>();
-
-    try{
-      Message response = handler.handle(request);
-      CompositeNode payload = null;
-
-      if ( response != null ) {
-
-        _logger.info("Received response [{}]", response);
-
-        Object rawPayload = response.getPayload();
-        switch (response.getType()) {
-          case ERROR:
-            if ( rawPayload instanceof List )
-              errors = (List) rawPayload;
-              break;
-
-          case RESPONSE:
-            payload = XmlUtils.xmlToCompositeNode((String) rawPayload);
-            break;
-
-          default:
-            errors.add(
-                RpcErrors.getRpcError(null, null,null,null,"Unable to get response from remote controller", null, null)
-            );
-            break;
-
-        }
-      }
-      return Futures.immediateFuture(Rpcs.getRpcResult(true, payload, errors));
-
-    } catch (Exception e){
-      collectErrors(e, errors);
-      return Futures.immediateFuture(Rpcs.<CompositeNode>getRpcResult(false, null, errors));
-    }
-  }
-
-  /**
-   * Find address for the given route identifier in routing table
-   * @param  routeId route identifier
-   * @return         remote network address
-   */
-  private String lookupRemoteAddressForGlobalRpc(RpcRouter.RouteIdentifier<?, ?, ?> routeId){
-    checkNotNull(routeId, "route must not be null");
-
-    Optional<RoutingTable<RpcRouter.RouteIdentifier<?, ?, ?>, String>> routingTable = routingTableProvider.getRoutingTable();
-    checkNotNull(routingTable.isPresent(), "Routing table is null");
-
-    String address = null;
-    try {
-      address = routingTable.get().getGlobalRoute(routeId);
-    } catch (RoutingTableException|SystemException e) {
-      _logger.error("Exception caught while looking up remote address " + e);
-    }
-    checkState(address != null, "Address not found for route [%s]", routeId);
-
-    return address;
-  }
-
-  /**
-   * Find address for the given route identifier in routing table
-   * @param  routeId route identifier
-   * @return         remote network address
-   */
-  private String lookupRemoteAddressForRpc(RpcRouter.RouteIdentifier<?, ?, ?> routeId){
-    checkNotNull(routeId, "route must not be null");
-
-    Optional<RoutingTable<RpcRouter.RouteIdentifier<?, ?, ?>, String>> routingTable = routingTableProvider.getRoutingTable();
-    checkNotNull(routingTable.isPresent(), "Routing table is null");
-
-    String address = routingTable.get().getLastAddedRoute(routeId);
-    checkState(address != null, "Address not found for route [%s]", routeId);
-
-    return address;
-  }
-
-  private void collectErrors(Exception e, List<RpcError> errors){
-    if (e == null) return;
-    if (errors == null) errors = new ArrayList<RpcError>();
-
-    errors.add(RpcErrors.getRpcError(null, null, null, null, e.getMessage(), null, e.getCause()));
-    for (Throwable t : e.getSuppressed()) {
-      errors.add(RpcErrors.getRpcError(null, null, null, null, t.getMessage(), null, t));
-    }
-  }
-
-  /**
-   * Closes ZMQ Context. It tries to gracefully terminate the context. If
-   * termination takes more than a second, its forcefully shutdown.
-   */
-  private void closeZmqContext() {
-    ExecutorService exec = Executors.newSingleThreadExecutor();
-    FutureTask<?> zmqTermination = new FutureTask<Void>(new Runnable() {
-
-      @Override
-      public void run() {
-        try {
-          if (context != null)
-            context.term();
-          _logger.debug("ZMQ Context terminated");
-        } catch (Exception e) {
-          _logger.debug("ZMQ Context termination threw exception [{}]. Continuing shutdown...", e);
-        }
-      }
-    }, null);
-
-    exec.execute(zmqTermination);
-
-    try {
-      zmqTermination.get(1L, TimeUnit.SECONDS);
-    } catch (Exception e) {/*ignore and continue with shutdown*/}
-
-    exec.shutdownNow();
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ClientRequestHandler.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ClientRequestHandler.java
deleted file mode 100644 (file)
index fe70fb7..0000000
+++ /dev/null
@@ -1,194 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sal.connector.remoterpc;
-
-import com.google.common.base.Preconditions;
-import org.opendaylight.controller.sal.connector.remoterpc.dto.Message;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.zeromq.ZMQ;
-
-import java.io.IOException;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.SynchronousQueue;
-import java.util.concurrent.ThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-
-/**
- *
- */
-class ClientRequestHandler implements AutoCloseable{
-
-  private Logger _logger = LoggerFactory.getLogger(ClientRequestHandler.class);
-  private final String DEFAULT_NAME = "remoterpc-client-worker";
-  private final String INPROC_PROTOCOL_PREFIX = "inproc://";
-  private final String TCP_PROTOCOL_PREFIX = "tcp://";
-
-  private ZMQ.Context context;
-
-  /*
-   * Worker thread pool. Each thread runs a ROUTER-DEALER pair
-   */
-  private ExecutorService workerPool;
-
-  /*
-   * Set of remote servers this client is currently connected to
-   */
-  private Map<String, String> connectedServers;
-
-  protected ClientRequestHandler(ZMQ.Context context) {
-    this.context = context;
-    connectedServers = new ConcurrentHashMap<String, String>();
-    start();
-  }
-
-  /**
-   * Starts a pool of worker as needed. A worker thread that has not been used for 5 min
-   * is terminated and removed from the pool. If thread dies due to an exception, its
-   * restarted.
-   */
-  private void start(){
-
-    workerPool = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
-        5L, TimeUnit.MINUTES,
-        new SynchronousQueue<Runnable>()){
-
-      @Override
-      protected void afterExecute(Runnable r, Throwable t) {
-        if (isTerminating() || isTerminated() || isShutdown())
-          return;
-
-        Worker worker = (Worker) r;
-        Preconditions.checkState( worker != null );
-        String remoteServerAddress = worker.getRemoteServerAddress();
-        connectedServers.remove(remoteServerAddress);
-
-        if ( t != null ){
-          _logger.debug("Exception caught while terminating worker [{},{}]. " +
-              "Restarting worker...", t.getClass(), t.getMessage());
-
-          connectedServers.put(remoteServerAddress, remoteServerAddress);
-          this.execute(r);
-        }
-        super.afterExecute(r, null);
-      }
-    };
-  }
-
-  public Message handle(Message request) throws IOException, ClassNotFoundException, InterruptedException {
-
-    String remoteServerAddress = request.getRecipient();
-    //if we already have router-dealer bridge setup for this address the send request
-    //otherwise first create the bridge and then send request
-    if ( connectedServers.containsKey(remoteServerAddress) )
-      return sendMessage(request, remoteServerAddress);
-
-    else{
-      workerPool.execute(new Worker(remoteServerAddress));
-      connectedServers.put(remoteServerAddress, remoteServerAddress);
-      //give little time for sockets to get initialized
-      //TODO: Add socket ping-pong message to ensure socket init rather than thread.sleep.
-      Thread.sleep(1000);
-      return sendMessage(request, remoteServerAddress);
-    }
-  }
-
-  private Message sendMessage(Message request, String address) throws IOException, ClassNotFoundException {
-    Message response = null;
-    ZMQ.Socket socket = context.socket(ZMQ.REQ);
-
-    try {
-      String inProcessSocketAddress = INPROC_PROTOCOL_PREFIX + address;
-      socket.connect( inProcessSocketAddress );
-      _logger.debug("Sending request [{}]", request);
-      socket.send(Message.serialize(request));
-      _logger.info("Request sent. Waiting for reply...");
-      byte[] reply = socket.recv(0);
-      _logger.info("Response received");
-      response = (Message) Message.deserialize(reply);
-      _logger.debug("Response [{}]", response);
-    } finally {
-      socket.close();
-    }
-    return response;
-  }
-
-  /**
-   * This gets called automatically if used with try-with-resources
-   */
-  @Override
-  public void close(){
-    workerPool.shutdown();
-    _logger.info("Request Handler closed");
-  }
-
-  /**
-   * Total number of workers in the pool. Number of workers represent
-   * number of remote servers {@link org.opendaylight.controller.sal.connector.remoterpc.ClientImpl} is connected to.
-   *
-   * @return worker count
-   */
-  public int getWorkerCount(){
-
-    if (workerPool == null) return 0;
-
-    return ((ThreadPoolExecutor)workerPool).getActiveCount();
-  }
-  /**
-   * Handles RPC request
-   */
-  private class Worker implements Runnable {
-    private String name;
-    private String remoteServer;  //<serverip:rpc-port>
-
-    public Worker(String address){
-      this.name = DEFAULT_NAME + "[" + address + "]";
-      this.remoteServer = address;
-    }
-
-    public String getRemoteServerAddress(){
-      return this.remoteServer;
-    }
-
-    @Override
-    public void run() {
-      Thread.currentThread().setName(name);
-      _logger.debug("Starting ... ");
-
-      ZMQ.Socket router = context.socket(ZMQ.ROUTER);
-      ZMQ.Socket dealer = context.socket(ZMQ.DEALER);
-
-      try {
-        int success = router.bind(INPROC_PROTOCOL_PREFIX + remoteServer);
-        Preconditions.checkState(-1 != success, "Could not bind to " + remoteServer);
-
-        dealer.connect(TCP_PROTOCOL_PREFIX + remoteServer);
-
-        _logger.info("Worker started for [{}]", remoteServer);
-
-        //TODO: Add capture handler
-        //This code will block until the zmq context is terminated.
-        ZMQ.proxy(router, dealer, null);
-
-      } catch (Exception e) {
-        _logger.debug("Ignoring exception [{}, {}]", e.getClass(), e.getMessage());
-      } finally {
-        try {
-          router.close();
-          dealer.close();
-        } catch (Exception x) {
-          _logger.debug("Exception while closing socket [{}]", x);
-        }
-        _logger.debug("Closing...");
-      }
-    }
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/Context.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/Context.java
deleted file mode 100644 (file)
index 37bff7b..0000000
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sal.connector.remoterpc;
-
-import java.net.Inet4Address;
-import java.net.InetAddress;
-import java.net.NetworkInterface;
-import java.net.SocketException;
-import java.util.Enumeration;
-
-import org.zeromq.ZMQ;
-
-/**
- * Provides a ZeroMQ Context object
- */
-public class Context {
-  private final ZMQ.Context zmqContext = ZMQ.context(1);
-  private String uri;
-  private final String DEFAULT_RPC_PORT = "5554";
-
-  private static Context _instance = new Context();
-
-  private Context() {}
-
-  public static Context getInstance(){
-    return _instance;
-  }
-
-  public ZMQ.Context getZmqContext(){
-    return this.zmqContext;
-  }
-
-  public String getLocalUri(){
-    uri = (uri != null) ? uri
-            : new StringBuilder().append(getIpAddress()).append(":")
-              .append(getRpcPort()).toString();
-
-    return uri;
-  }
-
-  public String getRpcPort(){
-    String rpcPort = (System.getProperty("rpc.port") != null)
-        ? System.getProperty("rpc.port")
-        : DEFAULT_RPC_PORT;
-
-    return rpcPort;
-  }
-
-  private String getIpAddress(){
-    String ipAddress = (System.getProperty("local.ip") != null)
-        ? System.getProperty("local.ip")
-        : findIpAddress();
-
-    return ipAddress;
-  }
-
-  /**
-   * Finds IPv4 address of the local VM
-   * TODO: This method is non-deterministic. There may be more than one IPv4 address. Cant say which
-   * address will be returned. Read IP from a property file or enhance the code to make it deterministic.
-   * Should we use IP or hostname?
-   *
-   * @return
-   */
-  private String findIpAddress() {
-    String hostAddress = null;
-    Enumeration<?> e = null;
-    try {
-      e = NetworkInterface.getNetworkInterfaces();
-    } catch (SocketException e1) {
-      e1.printStackTrace();
-    }
-    while (e.hasMoreElements()) {
-
-      NetworkInterface n = (NetworkInterface) e.nextElement();
-
-      Enumeration<?> ee = n.getInetAddresses();
-      while (ee.hasMoreElements()) {
-        InetAddress i = (InetAddress) ee.nextElement();
-        if ((i instanceof Inet4Address) && (i.isSiteLocalAddress()))
-          hostAddress = i.getHostAddress();
-      }
-    }
-    return hostAddress;
-
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcClient.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcClient.java
deleted file mode 100644 (file)
index 94e3232..0000000
+++ /dev/null
@@ -1,18 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sal.connector.remoterpc;
-
-public interface RemoteRpcClient extends AutoCloseable{
-
-    void setRoutingTableProvider(RoutingTableProvider provider);
-
-    void stop();
-
-    void start();
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcProvider.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcProvider.java
deleted file mode 100644 (file)
index 76df256..0000000
+++ /dev/null
@@ -1,295 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sal.connector.remoterpc;
-
-import static com.google.common.base.Preconditions.checkState;
-
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.Map;
-import java.util.Set;
-
-import org.opendaylight.controller.md.sal.common.api.routing.RouteChange;
-import org.opendaylight.controller.md.sal.common.api.routing.RouteChangeListener;
-import org.opendaylight.controller.sal.connector.api.RpcRouter;
-import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable;
-import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTableException;
-import org.opendaylight.controller.sal.connector.remoterpc.api.SystemException;
-import org.opendaylight.controller.sal.connector.remoterpc.dto.RouteIdentifierImpl;
-import org.opendaylight.controller.sal.core.api.Broker.ProviderSession;
-import org.opendaylight.controller.sal.core.api.Provider;
-import org.opendaylight.controller.sal.core.api.RoutedRpcDefaultImplementation;
-import org.opendaylight.controller.sal.core.api.RpcImplementation;
-import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
-import org.opendaylight.controller.sal.core.api.RpcRegistrationListener;
-import org.opendaylight.controller.sal.core.api.RpcRoutingContext;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
-import org.osgi.framework.BundleContext;
-import org.osgi.util.tracker.ServiceTracker;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.ListenableFuture;
-
-public class RemoteRpcProvider implements
-    RpcImplementation,
-    RoutedRpcDefaultImplementation,
-    AutoCloseable,
-    Provider {
-
-  private final Logger _logger = LoggerFactory.getLogger(RemoteRpcProvider.class);
-
-  private final ServerImpl server;
-  private final ClientImpl client;
-  private RoutingTableProvider routingTableProvider;
-  private final RpcListener listener = new RpcListener();
-  private final RoutedRpcListener routeChangeListener = new RoutedRpcListener();
-  private ProviderSession brokerSession;
-  private RpcProvisionRegistry rpcProvisionRegistry;
-  private BundleContext context;
-  private ServiceTracker<?, ?> clusterTracker;
-
-  public RemoteRpcProvider(ServerImpl server, ClientImpl client) {
-    this.server = server;
-    this.client = client;
-  }
-
-  public void setRoutingTableProvider(RoutingTableProvider provider) {
-    this.routingTableProvider = provider;
-    client.setRoutingTableProvider(provider);
-  }
-
-  public void setContext(BundleContext context){
-    this.context = context;
-  }
-
-  public void setRpcProvisionRegistry(RpcProvisionRegistry rpcProvisionRegistry){
-    this.rpcProvisionRegistry = rpcProvisionRegistry;
-  }
-
-  @Override
-  public void onSessionInitiated(ProviderSession session) {
-    brokerSession = session;
-    server.setBrokerSession(session);
-    start();
-  }
-
-  @Override
-  public Set<QName> getSupportedRpcs() {
-    //TODO: Ask Tony if we need to get this from routing table
-    return Collections.emptySet();
-  }
-
-  @Override
-  public Collection<ProviderFunctionality> getProviderFunctionality() {
-    // TODO Auto-generated method stub
-    return null;
-  }
-
-  @Override
-  public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(QName rpc, CompositeNode input) {
-    return client.invokeRpc(rpc, input);
-  }
-
-  @Override
-  public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(QName rpc, InstanceIdentifier identifier, CompositeNode input) {
-    return client.invokeRpc(rpc, identifier, input);
-  }
-
-  public void start() {
-    server.start();
-    client.start();
-    brokerSession.addRpcRegistrationListener(listener);
-    rpcProvisionRegistry.setRoutedRpcDefaultDelegate(this);
-    rpcProvisionRegistry.registerRouteChangeListener(routeChangeListener);
-
-    announceSupportedRpcs();
-    announceSupportedRoutedRpcs();
-  }
-
-  @Override
-  public void close() throws Exception {
-    unregisterSupportedRpcs();
-    unregisterSupportedRoutedRpcs();
-    server.close();
-    client.close();
-  }
-
-  public void stop() {
-    server.stop();
-    client.stop();
-  }
-
-  /**
-   * Add all the locally registered RPCs in the clustered routing table
-   */
-  private void announceSupportedRpcs(){
-    Set<QName> currentlySupported = brokerSession.getSupportedRpcs();
-    for (QName rpc : currentlySupported) {
-      listener.onRpcImplementationAdded(rpc);
-    }
-  }
-
-  /**
-   * Add all the locally registered Routed RPCs in the clustered routing table
-   */
-  private void announceSupportedRoutedRpcs(){
-
-    //TODO: announce all routed RPCs as well
-
-  }
-
-  /**
-   * Un-Register all the supported RPCs from clustered routing table
-   */
-  private void unregisterSupportedRpcs(){
-    Set<QName> currentlySupported = brokerSession.getSupportedRpcs();
-    //TODO: remove all routed RPCs as well
-    for (QName rpc : currentlySupported) {
-      listener.onRpcImplementationRemoved(rpc);
-    }
-  }
-
-  /**
-   * Un-Register all the locally supported Routed RPCs from clustered routing table
-   */
-  private void unregisterSupportedRoutedRpcs(){
-
-    //TODO: remove all routed RPCs as well
-
-  }
-
-  private RoutingTable<RpcRouter.RouteIdentifier<?, ?, ?>, String> getRoutingTable(){
-    Optional<RoutingTable<RpcRouter.RouteIdentifier<?, ?, ?>, String>> routingTable =
-        routingTableProvider.getRoutingTable();
-
-    checkState(routingTable.isPresent(), "Routing table is null");
-
-    return routingTable.get();
-  }
-
-  /**
-   * Listener for rpc registrations in broker
-   */
-  private class RpcListener implements RpcRegistrationListener {
-
-    @Override
-    public void onRpcImplementationAdded(QName rpc) {
-
-      _logger.debug("Adding registration for [{}]", rpc);
-      RouteIdentifierImpl routeId = new RouteIdentifierImpl();
-      routeId.setType(rpc);
-
-      RoutingTable<RpcRouter.RouteIdentifier<?, ?, ?>, String> routingTable = getRoutingTable();
-
-      try {
-        routingTable.addGlobalRoute(routeId, server.getServerAddress());
-        _logger.debug("Route added [{}-{}]", routeId, server.getServerAddress());
-
-      } catch (RoutingTableException | SystemException e) {
-        //TODO: This can be thrown when route already exists in the table. Broker
-        //needs to handle this.
-        _logger.error("Unhandled exception while adding global route to routing table [{}]", e);
-
-      }
-    }
-
-    @Override
-    public void onRpcImplementationRemoved(QName rpc) {
-
-      _logger.debug("Removing registration for [{}]", rpc);
-      RouteIdentifierImpl routeId = new RouteIdentifierImpl();
-      routeId.setType(rpc);
-
-      RoutingTable<RpcRouter.RouteIdentifier<?, ?, ?>, String> routingTable = getRoutingTable();
-
-      try {
-        routingTable.removeGlobalRoute(routeId);
-      } catch (RoutingTableException | SystemException e) {
-        _logger.error("Route delete failed {}", e);
-      }
-    }
-  }
-
-  /**
-   * Listener for Routed Rpc registrations in broker
-   */
-  private class RoutedRpcListener
-      implements RouteChangeListener<RpcRoutingContext, InstanceIdentifier> {
-
-    /**
-     *
-     * @param routeChange
-     */
-    @Override
-    public void onRouteChange(RouteChange<RpcRoutingContext, InstanceIdentifier> routeChange) {
-      Map<RpcRoutingContext, Set<InstanceIdentifier>> announcements = routeChange.getAnnouncements();
-      announce(getRouteIdentifiers(announcements));
-
-      Map<RpcRoutingContext, Set<InstanceIdentifier>> removals = routeChange.getRemovals();
-      remove(getRouteIdentifiers(removals));
-    }
-
-    /**
-     *
-     * @param announcements
-     */
-    private void announce(Set<RpcRouter.RouteIdentifier<?, ?, ?>> announcements) {
-      _logger.debug("Announcing [{}]", announcements);
-      RoutingTable<RpcRouter.RouteIdentifier<?, ?, ?>, String> routingTable = getRoutingTable();
-      try {
-        routingTable.addRoutes(announcements, server.getServerAddress());
-      } catch (RoutingTableException | SystemException e) {
-        _logger.error("Route announcement failed {}", e);
-      }
-    }
-
-    /**
-     *
-     * @param removals
-     */
-    private void remove(Set<RpcRouter.RouteIdentifier<?, ?, ?>> removals){
-      _logger.debug("Removing [{}]", removals);
-      RoutingTable<RpcRouter.RouteIdentifier<?, ?, ?>, String> routingTable = getRoutingTable();
-      try {
-        routingTable.removeRoutes(removals, server.getServerAddress());
-      } catch (RoutingTableException | SystemException e) {
-        _logger.error("Route removal failed {}", e);
-      }
-    }
-
-    /**
-     *
-     * @param changes
-     * @return
-     */
-    private Set<RpcRouter.RouteIdentifier<?, ?, ?>> getRouteIdentifiers(Map<RpcRoutingContext, Set<InstanceIdentifier>> changes) {
-      RouteIdentifierImpl routeId = null;
-      Set<RpcRouter.RouteIdentifier<?, ?, ?>> routeIdSet = new HashSet<>();
-
-      for (RpcRoutingContext context : changes.keySet()){
-        routeId = new RouteIdentifierImpl();
-        routeId.setType(context.getRpc());
-        //routeId.setContext(context.getContext());
-
-        for (InstanceIdentifier instanceId : changes.get(context)){
-          routeId.setRoute(instanceId);
-          routeIdSet.add(routeId);
-        }
-      }
-      return routeIdSet;
-    }
-
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcServer.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcServer.java
deleted file mode 100644 (file)
index e845e43..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sal.connector.remoterpc;
-
-public interface RemoteRpcServer extends AutoCloseable {
-
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RoutingTableProvider.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/RoutingTableProvider.java
deleted file mode 100644 (file)
index d960303..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sal.connector.remoterpc;
-
-import org.opendaylight.controller.sal.connector.api.RpcRouter;
-import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable;
-import org.opendaylight.controller.sal.connector.remoterpc.impl.RoutingTableImpl;
-import org.osgi.framework.BundleContext;
-import org.osgi.util.tracker.ServiceTracker;
-
-import com.google.common.base.Optional;
-
-public class RoutingTableProvider implements AutoCloseable {
-
-    @SuppressWarnings("rawtypes")
-    final ServiceTracker<RoutingTable,RoutingTable> tracker;
-
-    private RoutingTableImpl<?, ?> routingTableImpl = null;
-
-    //final private RouteChangeListener routeChangeListener;
-
-
-    public RoutingTableProvider(BundleContext ctx){//,RouteChangeListener rcl) {
-        @SuppressWarnings("rawtypes")
-        ServiceTracker<RoutingTable, RoutingTable> rawTracker = new ServiceTracker<>(ctx, RoutingTable.class, null);
-        tracker = rawTracker;
-        tracker.open();
-
-        //routeChangeListener = rcl;
-    }
-
-    public Optional<RoutingTable<RpcRouter.RouteIdentifier<?, ?, ?>, String>> getRoutingTable() {
-        @SuppressWarnings("unchecked")
-        RoutingTable<RpcRouter.RouteIdentifier<?, ?, ?>, String> tracked = tracker.getService();
-
-        if(tracked instanceof RoutingTableImpl){
-            if(routingTableImpl != tracked){
-             routingTableImpl= (RoutingTableImpl<?, ?>)tracked;
-             //routingTableImpl.setRouteChangeListener(routeChangeListener);
-            }
-        }
-
-        return Optional.fromNullable(tracked);
-    }
-
-    @Override
-    public void close() throws Exception {
-        tracker.close();
-    }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ServerImpl.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ServerImpl.java
deleted file mode 100644 (file)
index 3acea35..0000000
+++ /dev/null
@@ -1,264 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.connector.remoterpc;
-
-import java.net.Inet4Address;
-import java.net.InetAddress;
-import java.net.NetworkInterface;
-import java.net.SocketException;
-import java.util.Enumeration;
-import java.util.HashSet;
-import java.util.Set;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.FutureTask;
-import java.util.concurrent.TimeUnit;
-
-import org.opendaylight.controller.sal.core.api.Broker.ProviderSession;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.zeromq.ZMQ;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-
-/**
- * ZeroMq based implementation of RpcRouter.
- */
-public class ServerImpl implements RemoteRpcServer {
-
-  private final Logger _logger = LoggerFactory.getLogger(ServerImpl.class);
-
-  private ExecutorService serverPool;
-  protected ServerRequestHandler handler;
-
-  private Set<QName> remoteServices;
-  private ProviderSession brokerSession;
-  private ZMQ.Context context;
-
-  private final String HANDLER_INPROC_ADDRESS = "inproc://rpc-request-handler";
-  private final int HANDLER_WORKER_COUNT = 2;
-  private final int HWM = 200;//high water mark on sockets
-  private volatile State status = State.STOPPED;
-
-  private String serverAddress;
-  private final int port;
-
-  public static enum State {
-    STARTING, STARTED, STOPPED;
-  }
-
-  public ServerImpl(int port) {
-    this.port = port;
-  }
-
-  public State getStatus() {
-    return this.status;
-  }
-
-  public Optional<ServerRequestHandler> getHandler() {
-    return Optional.fromNullable(this.handler);
-  }
-
-  public void setBrokerSession(ProviderSession session) {
-    this.brokerSession = session;
-  }
-
-  public Optional<ProviderSession> getBrokerSession() {
-    return Optional.fromNullable(this.brokerSession);
-  }
-
-  public Optional<ZMQ.Context> getZmqContext() {
-    return Optional.fromNullable(this.context);
-  }
-
-  public String getServerAddress() {
-    return serverAddress;
-  }
-
-  public String getHandlerAddress() {
-    return HANDLER_INPROC_ADDRESS;
-  }
-
-  /**
-   *
-   */
-  public void start() {
-    Preconditions.checkState(State.STOPPED == this.getStatus(),
-        "Remote RPC Server is already running");
-
-    status = State.STARTING;
-    _logger.debug("Remote RPC Server is starting...");
-
-    String hostIpAddress = findIpAddress();
-
-    //Log and silently die as per discussion in the bug (bug-362)
-    //https://bugs.opendaylight.org/show_bug.cgi?id=362
-    //
-    // A tracking enhancement defect (bug-366) is created to properly fix this issue
-    //https://bugs.opendaylight.org/show_bug.cgi?id=366
-    //checkState(hostIpAddress != null, "Remote RPC Server could not acquire host ip address");
-
-    if (hostIpAddress == null) {
-      _logger.error("Remote RPC Server could not acquire host ip address. Stopping...");
-      stop();
-      return;
-    }
-
-    this.serverAddress = new StringBuilder(hostIpAddress).
-        append(":").
-        append(port).
-        toString();
-
-    context = ZMQ.context(1);
-    remoteServices = new HashSet<QName>();//
-    serverPool = Executors.newSingleThreadExecutor();//main server thread
-    serverPool.execute(receive()); // Start listening rpc requests
-
-    status = State.STARTED;
-    _logger.info("Remote RPC Server started [{}]", getServerAddress());
-  }
-
-  public void stop(){
-    close();
-  }
-
-  /**
-   *
-   */
-  @Override
-  public void close() {
-
-    if (State.STOPPED == this.getStatus()) return; //do nothing
-
-    if (serverPool != null)
-      serverPool.shutdown();
-
-    closeZmqContext();
-
-    status = State.STOPPED;
-    _logger.info("Remote RPC Server stopped");
-  }
-
-  /**
-   * Closes ZMQ Context. It tries to gracefully terminate the context. If
-   * termination takes more than 5 seconds, its forcefully shutdown.
-   */
-  private void closeZmqContext() {
-    ExecutorService exec = Executors.newSingleThreadExecutor();
-    FutureTask<?> zmqTermination = new FutureTask<Void>(new Runnable() {
-
-      @Override
-      public void run() {
-        try {
-          if (context != null)
-            context.term();
-          _logger.debug("ZMQ Context terminated gracefully!");
-        } catch (Exception e) {
-          _logger.debug("ZMQ Context termination threw exception [{}]. Continuing shutdown...", e);
-        }
-      }
-    }, null);
-
-    exec.execute(zmqTermination);
-
-    try {
-      zmqTermination.get(5L, TimeUnit.SECONDS);
-    } catch (Exception e) {/*ignore and continue with shutdown*/}
-
-    exec.shutdownNow();
-  }
-
-  /**
-   * Main listener thread that spawns {@link ServerRequestHandler} as workers.
-   *
-   * @return
-   */
-  private Runnable receive() {
-    return new Runnable() {
-
-      @Override
-      public void run() {
-        Thread.currentThread().setName("remote-rpc-server");
-        _logger.debug("Remote RPC Server main thread starting...");
-
-        //socket clients connect to (frontend)
-        ZMQ.Socket clients = context.socket(ZMQ.ROUTER);
-
-        //socket RequestHandlers connect to (backend)
-        ZMQ.Socket workers = context.socket(ZMQ.DEALER);
-
-        try (SocketPair capturePair = new SocketPair();
-             ServerRequestHandler requestHandler = new ServerRequestHandler(context,
-                 brokerSession,
-                 HANDLER_WORKER_COUNT,
-                 HANDLER_INPROC_ADDRESS,
-                 getServerAddress());) {
-
-          handler = requestHandler;
-          clients.setHWM(HWM);
-          clients.bind("tcp://*:" + port);
-          workers.setHWM(HWM);
-          workers.bind(HANDLER_INPROC_ADDRESS);
-          //start worker threads
-          _logger.debug("Remote RPC Server worker threads starting...");
-          requestHandler.start();
-          //start capture thread
-          // handlerPool.execute(new CaptureHandler(capturePair.getReceiver()));
-          //  Connect work threads to client threads via a queue
-          ZMQ.proxy(clients, workers, null);//capturePair.getSender());
-
-        } catch (Exception e) {
-          _logger.debug("Unhandled exception [{}, {}]", e.getClass(), e.getMessage());
-        } finally {
-          if (clients != null) clients.close();
-          if (workers != null) workers.close();
-          _logger.info("Remote RPC Server stopped");
-        }
-      }
-    };
-  }
-
-  /**
-   * Finds IPv4 address of the local VM
-   * TODO: This method is non-deterministic. There may be more than one IPv4 address. Cant say which
-   * address will be returned. Read IP from a property file or enhance the code to make it deterministic.
-   * Should we use IP or hostname?
-   *
-   * @return
-   */
-  private String findIpAddress() {
-    Enumeration<?> e = null;
-    try {
-      e = NetworkInterface.getNetworkInterfaces();
-    } catch (SocketException e1) {
-      _logger.error("Failed to get list of interfaces", e1);
-      return null;
-    }
-    while (e.hasMoreElements()) {
-
-      NetworkInterface n = (NetworkInterface) e.nextElement();
-
-      Enumeration<?> ee = n.getInetAddresses();
-      while (ee.hasMoreElements()) {
-        InetAddress i = (InetAddress) ee.nextElement();
-        _logger.debug("Trying address {}", i);
-        if ((i instanceof Inet4Address) && (!i.isLoopbackAddress())) {
-          String hostAddress = i.getHostAddress();
-          _logger.debug("Settled on host address {}", hostAddress);
-          return hostAddress;
-        }
-      }
-    }
-
-    _logger.error("Failed to find a suitable host address");
-    return null;
-  }
-
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ServerRequestHandler.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/ServerRequestHandler.java
deleted file mode 100644 (file)
index a25387d..0000000
+++ /dev/null
@@ -1,292 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sal.connector.remoterpc;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.Future;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.ThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.opendaylight.controller.sal.connector.api.RpcRouter;
-import org.opendaylight.controller.sal.connector.remoterpc.dto.Message;
-import org.opendaylight.controller.sal.connector.remoterpc.util.XmlUtils;
-import org.opendaylight.controller.sal.core.api.Broker;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.zeromq.ZMQ;
-
-/**
- *
- */
-public class ServerRequestHandler implements AutoCloseable{
-
-  private final Logger _logger = LoggerFactory.getLogger(ServerRequestHandler.class);
-  private final String DEFAULT_NAME = "remote-rpc-worker";
-  private final String dealerAddress;
-  private final String serverAddress;
-  private final int workerCount;
-  private final ZMQ.Context context;
-  private final Broker.ProviderSession broker;
-
-  private RequestHandlerThreadPool workerPool;
-  private final AtomicInteger threadId = new AtomicInteger();
-
-  public ServerRequestHandler(ZMQ.Context context,
-                              Broker.ProviderSession session,
-                              int workerCount,
-                              String dealerAddress,
-                              String serverAddress) {
-    this.context       = context;
-    this.dealerAddress = dealerAddress;
-    this.serverAddress = serverAddress;
-    this.broker        = session;
-    this.workerCount   = workerCount;
-  }
-
-  public ThreadPoolExecutor getWorkerPool(){
-    return workerPool;
-  }
-
-  public void start(){
-    workerPool = new RequestHandlerThreadPool(
-        workerCount, workerCount,
-        0L, TimeUnit.MILLISECONDS,
-        new LinkedBlockingQueue<Runnable>());
-    //unbound is ok. Task will never be submitted
-
-    for (int i=0;i<workerCount;i++){
-      workerPool.execute(new Worker(threadId.incrementAndGet()));
-    }
-  }
-
-  /**
-   * This gets called automatically if used with try-with-resources
-   * @throws Exception
-   */
-  @Override
-  public void close() throws Exception {
-    if (workerPool != null)
-      workerPool.shutdown();
-    _logger.info("Request Handler closed");
-  }
-
-  /**
-   * Worker to handles RPC request
-   */
-  private class Worker implements Runnable {
-    private final String name;
-
-    public Worker(int id){
-      this.name = DEFAULT_NAME + "-" + id;
-    }
-
-    @Override
-    public void run() {
-      Thread.currentThread().setName(name);
-      _logger.debug("Starting... ");
-      ZMQ.Socket socket = null;
-
-      try {
-        socket = context.socket(ZMQ.REP);
-        socket.connect(dealerAddress);
-
-        while (!Thread.currentThread().isInterrupted()) {
-
-          MessageHandler handler = new MessageHandler(socket);
-          handler.receiveMessage();
-
-          if (handler.hasMessageForBroker()) {
-
-            Message request = handler.getMessage();
-            Future<RpcResult<CompositeNode>> rpc = null;
-            RpcResult<CompositeNode> result = null;
-
-            //TODO Call this in a new thread with timeout
-            try {
-              rpc = broker.rpc(
-                  (QName) request.getRoute().getType(),
-                  XmlUtils.xmlToCompositeNode((String) request.getPayload()));
-
-              result = (rpc != null) ? rpc.get() : null;
-
-              handler.sendResponse(result);
-
-            } catch (Exception e) {
-              _logger.debug("Broker threw  [{}]", e);
-              handler.sendError(e.getMessage());
-            }
-          }
-
-        }
-      } catch (Exception e) {
-        printException(e);
-      } finally {
-        closeSocket(socket);
-      }
-    }
-
-    private void printException(Exception e) {
-      try (StringWriter s = new StringWriter();
-           PrintWriter p = new PrintWriter(s)) {
-        e.printStackTrace(p);
-        _logger.debug(s.toString());
-      } catch (IOException e1) {/*Ignore and continue*/ }
-    }
-
-    private void closeSocket(ZMQ.Socket socket) {
-      try {
-        if (socket != null) socket.close();
-      } catch (Exception x) {
-        _logger.debug("Exception while closing socket [{}]", x);
-      } finally {
-        if (socket != null) socket.close();
-      }
-      _logger.debug("Closing...");
-    }
-  }
-
-
-  /**
-   *
-   */
-  public class RequestHandlerThreadPool extends ThreadPoolExecutor{
-
-    public RequestHandlerThreadPool(int corePoolSize,
-                                    int maximumPoolSize,
-                                    long keepAliveTime,
-                                    TimeUnit unit,
-                                    BlockingQueue<Runnable> workQueue) {
-      super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
-    }
-
-    @Override
-    protected void afterExecute(Runnable r, Throwable t) {
-      if (isTerminating() || isTerminated() || isShutdown())
-        return;
-
-      if ( t != null ){
-        _logger.debug("Exception caught while terminating worker [{},{}]", t.getClass(), t.getMessage());
-      }
-
-      this.execute(new Worker(threadId.incrementAndGet()));
-      super.afterExecute(r, null);
-    }
-  }
-
-  class MessageHandler{
-    private final ZMQ.Socket socket;
-    private Message message;          //parsed message received on zmq server port
-    private boolean messageForBroker = false; //if the message is valid and not a "ping" message
-
-    public MessageHandler(ZMQ.Socket socket){
-      this.socket = socket;
-    }
-
-    void receiveMessage(){
-      byte[] bytes = socket.recv(); //this blocks
-      _logger.debug("Received bytes:[{}]", bytes.length);
-
-      Object objectRecvd = null;
-      try{
-        objectRecvd = Message.deserialize(bytes);
-      }catch (Exception e){
-        sendError(e.getMessage());
-        return;
-      }
-
-      if (!(objectRecvd instanceof Message)) {
-        sendError("Invalid message received");
-        return;
-      }
-
-      message = (Message) objectRecvd;
-
-      _logger.info("Received request [{}]", message);
-
-      if (Message.MessageType.PING == message.getType()){
-        sendPong();
-        return;
-      }
-
-      messageForBroker = true;
-    }
-
-    boolean hasMessageForBroker(){
-      return messageForBroker;
-    }
-
-    Message getMessage(){
-      return message;
-    }
-
-    void sendResponse(RpcResult<CompositeNode> result){
-      CompositeNode payload = (result != null) ? result.getResult() : null;
-
-      String recipient = null;
-      RpcRouter.RouteIdentifier<?, ?, ?> routeId = null;
-
-      if (message != null) {
-        recipient = message.getSender();
-        routeId   = message.getRoute();
-      }
-
-      Message response = new Message.MessageBuilder()
-          .type(Message.MessageType.RESPONSE)
-          .sender(serverAddress)
-          .recipient(recipient)
-          .route(routeId)
-          .payload(XmlUtils.compositeNodeToXml(payload))
-          .build();
-
-      send(response);
-    }
-
-    private void sendError(String msg){
-      Message errorResponse = new Message.MessageBuilder()
-          .type(Message.MessageType.ERROR)
-          .sender(serverAddress)
-          .payload(msg)
-          .build();
-
-      send(errorResponse);
-    }
-
-    private void sendPong(){
-      Message pong = new Message.MessageBuilder()
-          .type(Message.MessageType.PONG)
-          .sender(serverAddress)
-          .build();
-
-      send(pong);
-    }
-
-    private void send(Message msg){
-      byte[] serializedMessage = null;
-      try {
-        serializedMessage = Message.serialize(msg);
-      } catch (Exception e) {
-        _logger.debug("Unexpected error during serialization of response [{}]", msg);
-        return;
-      }
-
-      if (serializedMessage != null)
-        if (socket.send(serializedMessage))
-          _logger.info("Response sent [{}]", msg);
-        else  _logger.debug("Failed to send serialized message");
-    }
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/SocketPair.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/SocketPair.java
deleted file mode 100644 (file)
index f569944..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.connector.remoterpc;
-
-import org.zeromq.ZMQ;
-
-import java.util.UUID;
-
-/**
- *
- */
-public class SocketPair implements AutoCloseable{
-  private ZMQ.Socket sender;
-  private ZMQ.Socket receiver;
-
-  private static final String INPROC_PREFIX = "inproc://";
-
-  public SocketPair(){
-    String address = new StringBuilder(INPROC_PREFIX)
-                         .append(UUID.randomUUID())
-                         .toString();
-
-    receiver = Context.getInstance().getZmqContext().socket(ZMQ.PAIR);
-    receiver.bind(address);
-
-    sender = Context.getInstance().getZmqContext().socket(ZMQ.PAIR);
-    sender.connect(address);
-  }
-
-  public ZMQ.Socket getSender(){
-    return this.sender;
-  }
-
-  public ZMQ.Socket getReceiver(){
-    return this.receiver;
-  }
-
-  @Override
-  public void close() throws Exception {
-    sender.close();
-    receiver.close();
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/dto/Message.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/dto/Message.java
deleted file mode 100644 (file)
index cbcfe3e..0000000
+++ /dev/null
@@ -1,191 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sal.connector.remoterpc.dto;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-
-import org.opendaylight.controller.sal.connector.api.RpcRouter;
-
-public class Message implements Serializable {
-    private static final long serialVersionUID = 1L;
-
- public static enum MessageType {
-    PING((byte) 0),
-    PONG((byte) 1),
-    REQUEST((byte) 2),
-    RESPONSE((byte) 3),
-    ERROR((byte)4);
-
-    private final byte type;
-
-    MessageType(byte type) {
-      this.type = type;
-    }
-
-    public byte getType(){
-      return this.type;
-    }
-  }
-
-  private MessageType type;
-  private String sender;
-  private String recipient;
-  private RpcRouter.RouteIdentifier<?, ?, ?> route;
-  private Object payload;
-
-  public MessageType getType() {
-    return type;
-  }
-
-  public void setType(MessageType type) {
-    this.type = type;
-  }
-
-  public String getSender() {
-    return sender;
-  }
-
-  public void setSender(String sender) {
-    this.sender = sender;
-  }
-
-  public RpcRouter.RouteIdentifier<?, ?, ?> getRoute() {
-    return route;
-  }
-
-  public void setRoute(RpcRouter.RouteIdentifier<?, ?, ?> route) {
-    this.route = route;
-  }
-
-  public Object getPayload() {
-    return payload;
-  }
-
-  public void setPayload(Object payload) {
-    this.payload = payload;
-  }
-
-  public String getRecipient() {
-    return recipient;
-  }
-
-  public void setRecipient(String recipient) {
-    this.recipient = recipient;
-  }
-
-  @Override
-  public String toString() {
-    return "Message{" +
-        "type=" + type +
-        ", sender='" + sender + '\'' +
-        ", recipient='" + recipient + '\'' +
-        ", route=" + route +
-        ", payload=" + payload +
-        '}';
-  }
-
-  /**
-   * Converts any {@link Serializable} object to byte[]
-   *
-   * @param obj
-   * @return
-   * @throws IOException
-   */
-  public static byte[] serialize(Object obj) throws IOException {
-    ByteArrayOutputStream b = new ByteArrayOutputStream();
-    ObjectOutputStream o = new ObjectOutputStream(b);
-    o.writeObject(obj);
-    return b.toByteArray();
-  }
-
-  /**
-   * Converts byte[] to a java object
-   *
-   * @param bytes
-   * @return
-   * @throws IOException
-   * @throws ClassNotFoundException
-   */
-  public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
-    ByteArrayInputStream b = new ByteArrayInputStream(bytes);
-    ObjectInputStream o = new ObjectInputStream(b);
-    return o.readObject();
-  }
-
-  public static class Response extends Message implements RpcRouter.RpcReply<Object> {
-    private static final long serialVersionUID = 1L;
-    private ResponseCode code; // response code
-
-    public static enum ResponseCode {
-      SUCCESS(200), BADREQUEST(400), TIMEOUT(408), GONE(410), SERVERERROR(500), SERVICEUNAVAILABLE(503);
-
-      private final int code;
-
-      ResponseCode(int code) {
-        this.code = code;
-      }
-    }
-
-    public ResponseCode getCode() {
-      return code;
-    }
-
-    public void setCode(ResponseCode code) {
-      this.code = code;
-    }
-  }
-
-  /**
-   * Builds a {@link Message} object
-   */
-  public static class MessageBuilder{
-
-    private final Message message;
-
-    public MessageBuilder(){
-      message = new Message();
-    }
-
-
-    public MessageBuilder type(MessageType type){
-      message.setType(type);
-      return this;
-    }
-
-    public MessageBuilder sender(String sender){
-      message.setSender(sender);
-      return this;
-    }
-
-    public MessageBuilder recipient(String recipient){
-      message.setRecipient(recipient);
-      return this;
-    }
-
-    public MessageBuilder route(RpcRouter.RouteIdentifier<?, ?, ?> route){
-      message.setRoute(route);
-      return this;
-    }
-
-    public MessageBuilder payload(Object obj){
-      message.setPayload(obj);
-      return this;
-    }
-
-    public Message build(){
-      return message;
-    }
-  }
-}
-
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/dto/MessageWrapper.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/dto/MessageWrapper.java
deleted file mode 100644 (file)
index 85f4113..0000000
+++ /dev/null
@@ -1,32 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sal.connector.remoterpc.dto;
-
-import org.zeromq.ZMQ;
-
-/**
- * A class encapsulating {@link Message} and the {@link ZMQ.Socket} over which it is transmitted
- */
-public class MessageWrapper {
-
-  private Message _message;
-  private ZMQ.Socket _receiveSocket;
-
-  public MessageWrapper(Message message, ZMQ.Socket receiveSocket) {
-    this._message = message;
-    this._receiveSocket = receiveSocket;
-  }
-
-  public Message getMessage() {
-    return _message;
-  }
-
-  public ZMQ.Socket getReceiveSocket() {
-    return _receiveSocket;
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/dto/RouteIdentifierImpl.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/dto/RouteIdentifierImpl.java
deleted file mode 100644 (file)
index 53c7cc0..0000000
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.connector.remoterpc.dto;
-
-import java.io.Serializable;
-
-import org.opendaylight.controller.sal.connector.api.RpcRouter;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
-
-public class RouteIdentifierImpl implements RpcRouter.RouteIdentifier<QName, QName, InstanceIdentifier>,Serializable {
-  private static final long serialVersionUID = 1L;
-
-  private QName context;
-  private QName type;
-  private InstanceIdentifier route;
-
-  @Override
-  public QName getContext() {
-    return this.context;
-  }
-
-  @Override
-  public QName getType() {
-    return this.type;
-  }
-
-  @Override
-  public InstanceIdentifier getRoute() {
-    return this.route;
-  }
-
-  public void setContext(QName context) {
-    this.context = context;
-  }
-
-  public void setType(QName type) {
-    this.type = type;
-  }
-
-  public void setRoute(InstanceIdentifier route) {
-    this.route = route;
-  }
-
-  @Override
-  public boolean equals(Object o) {
-    if (this == o) return true;
-    if (o == null || getClass() != o.getClass()) return false;
-
-    RouteIdentifierImpl that = (RouteIdentifierImpl) o;
-
-    if (context == null){
-      if (that.getContext() != null)  return false;
-    }else
-      if (!context.equals(that.context)) return false;
-
-    if (route == null){
-      if (that.getRoute() != null) return false;
-    }else
-      if (!route.equals(that.route)) return false;
-
-    if (type == null){
-      if (that.getType() != null) return false;
-    }else
-      if (!type.equals(that.type)) return false;
-
-    return true;
-  }
-
-  @Override
-  public int hashCode() {
-    int prime = 31;
-    int result = 0;
-    result = prime * result + (context == null ? 0:context.hashCode());
-    result = prime * result + (type    == null ? 0:type.hashCode());
-    result = prime * result + (route   == null ? 0:route.hashCode());
-    return result;
-  }
-
-  @Override
-  public String toString() {
-    return "RouteIdentifierImpl{" +
-        "context=" + context +
-        ", type=" + type +
-        ", route=" + route +
-        '}';
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/util/XmlUtils.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/java/org/opendaylight/controller/sal/connector/remoterpc/util/XmlUtils.java
deleted file mode 100644 (file)
index 3bc3963..0000000
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sal.connector.remoterpc.util;
-
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.impl.NodeUtils;
-import org.opendaylight.yangtools.yang.data.impl.XmlTreeBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-
-import javax.xml.stream.XMLStreamException;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-import java.io.ByteArrayInputStream;
-import java.io.StringWriter;
-
-public class XmlUtils {
-
-  private static final Logger _logger = LoggerFactory.getLogger(XmlUtils.class);
-
-  public static String compositeNodeToXml(CompositeNode cNode){
-    if (cNode == null) return new String();
-
-    Document domTree = NodeUtils.buildShadowDomTree(cNode);
-    StringWriter writer = new StringWriter();
-    try {
-      TransformerFactory tf = TransformerFactory.newInstance();
-      Transformer transformer = tf.newTransformer();
-      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
-      transformer.transform(new DOMSource(domTree), new StreamResult(writer));
-    } catch (TransformerException e) {
-      _logger.error("Error during translation of Document to OutputStream", e);
-    }
-
-    return writer.toString();
-  }
-
-  public static CompositeNode xmlToCompositeNode(String xml){
-    if (xml==null || xml.length()==0) return null;
-
-    Node<?> dataTree;
-    try {
-      dataTree = XmlTreeBuilder.buildDataTree(new ByteArrayInputStream(xml.getBytes()));
-    } catch (XMLStreamException e) {
-      _logger.error("Error during building data tree from XML", e);
-      return null;
-    }
-    if (dataTree == null) {
-      _logger.error("data tree is null");
-      return null;
-    }
-    if (dataTree instanceof SimpleNode) {
-      _logger.error("RPC XML was resolved as SimpleNode");
-      return null;
-    }
-    return (CompositeNode) dataTree;
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/yang/odl-sal-dom-rpc-remote-cfg.yang b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/main/yang/odl-sal-dom-rpc-remote-cfg.yang
deleted file mode 100644 (file)
index beeb936..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-module odl-sal-dom-rpc-remote-cfg {
-       yang-version 1;
-    namespace "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote:rpc";
-    prefix "rpc-cluster";
-
-    import config { prefix config; revision-date 2013-04-05; }
-    import opendaylight-md-sal-dom {prefix dom;}
-    
-    description
-        "Service definition for Binding Aware MD-SAL.";
-    revision "2013-10-28" {
-        description
-            "Initial revision";
-    }
-
-    identity remote-rpc-server {
-        base config:service-type;
-        config:java-class "org.opendaylight.controller.sal.connector.remoterpc.RemoteRpcServer";
-    }
-
-    identity remote-rpc-client {
-        base config:service-type;
-        config:java-class "org.opendaylight.controller.sal.connector.remoterpc.RemoteRpcClient";
-    }
-
-    identity remote-zeromq-rpc-server {
-        base config:module-type;
-        config:java-name-prefix ZeroMQServer;
-    }
-
-    augment "/config:modules/config:module/config:configuration" {
-        case remote-zeromq-rpc-server {
-            when "/config:modules/config:module/config:type = 'remote-zeromq-rpc-server'";
-            
-            container dom-broker {
-                uses config:service-ref {
-                    refine type {
-                        mandatory true;
-                        config:required-identity dom:dom-broker-osgi-registry;
-                    }
-                }
-            }
-            
-            leaf port {
-                type uint16;
-            }
-        }
-    }
-}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ClientImplTest.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ClientImplTest.java
deleted file mode 100644 (file)
index f8d14ce..0000000
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.connector.remoterpc;
-
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import java.io.IOException;
-
-import junit.framework.Assert;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.sal.connector.api.RpcRouter;
-import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable;
-import org.opendaylight.controller.sal.connector.remoterpc.dto.Message;
-import org.opendaylight.controller.sal.connector.remoterpc.utils.MessagingUtil;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-
-import com.google.common.base.Optional;
-
-/**
- *
- */
-public class ClientImplTest {
-  RoutingTableProvider routingTableProvider;
-  ClientImpl client;
-  ClientRequestHandler mockHandler;
-
-  @Before
-  public void setUp() throws Exception {
-
-    //mock routing table
-    routingTableProvider = mock(RoutingTableProvider.class);
-    RoutingTable<RpcRouter.RouteIdentifier<?, ?, ?>, String> mockRoutingTable = new MockRoutingTable<String, String>();
-    Optional<RoutingTable<RpcRouter.RouteIdentifier<?, ?, ?>, String>> optionalRoutingTable = Optional.fromNullable(mockRoutingTable);
-    when(routingTableProvider.getRoutingTable()).thenReturn(optionalRoutingTable);
-
-    //mock ClientRequestHandler
-    mockHandler = mock(ClientRequestHandler.class);
-
-    client = new ClientImpl(mockHandler);
-    client.setRoutingTableProvider(routingTableProvider);
-
-  }
-
-  @After
-  public void tearDown() throws Exception {
-
-  }
-
-  @Test
-  public void getRoutingTableProvider_Call_ShouldReturnMockProvider() throws Exception {
-    Assert.assertEquals(routingTableProvider, client.getRoutingTableProvider());
-
-  }
-
-  @Test
-  public void testStart() throws Exception {
-
-  }
-
-  @Test
-  public void testStop() throws Exception {
-
-  }
-
-  @Test
-  public void testClose() throws Exception {
-
-  }
-
-  //@Test
-  public void invokeRpc_NormalCall_ShouldReturnSuccess() throws Exception {
-
-    when(mockHandler.handle(any(Message.class))).
-            thenReturn(MessagingUtil.createEmptyMessage());
-
-    RpcResult<CompositeNode> result = client.invokeRpc(null, null).get();
-
-    Assert.assertTrue(result.isSuccessful());
-    Assert.assertTrue(result.getErrors().isEmpty());
-    Assert.assertNull(result.getResult());
-  }
-
-  //@Test
-  public void invokeRpc_HandlerThrowsException_ShouldReturnError() throws Exception {
-
-    when(mockHandler.handle(any(Message.class))).
-            thenThrow(new IOException());
-
-    RpcResult<CompositeNode> result = client.invokeRpc(null, null).get();
-
-    Assert.assertFalse(result.isSuccessful());
-    Assert.assertFalse(result.getErrors().isEmpty());
-    Assert.assertNull(result.getResult());
-  }
-
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ClientRequestHandlerTest.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ClientRequestHandlerTest.java
deleted file mode 100644 (file)
index 0918868..0000000
+++ /dev/null
@@ -1,124 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.connector.remoterpc;
-
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.FutureTask;
-import java.util.concurrent.TimeUnit;
-
-import junit.framework.Assert;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.sal.connector.remoterpc.dto.Message;
-import org.opendaylight.controller.sal.connector.remoterpc.utils.MessagingUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.zeromq.ZMQ;
-
-/**
- *
- */
-public class ClientRequestHandlerTest {
-
-  private final Logger _logger = LoggerFactory.getLogger(ClientRequestHandlerTest.class);
-
-  ZMQ.Context context;
-  ExecutorService serverThread;
-  final String SERVER_ADDRESS = "localhost:5553";
-
-  ClientRequestHandler handler;
-
-  @Before
-  public void setUp() throws Exception {
-    context = ZMQ.context(1);
-    serverThread = Executors.newCachedThreadPool();
-    handler = new ClientRequestHandler(context);
-  }
-
-  @After
-  public void tearDown() throws Exception {
-    serverThread.shutdown();
-    MessagingUtil.closeZmqContext(context);
-    handler.close();
-  }
-
- @Test
-  public void handle_SingleRemote_ShouldReturnResponse() throws Exception {
-    serverThread.execute(MessagingUtil.startReplyServer(context, SERVER_ADDRESS, 1));
-    Message request = new Message();
-    request.setRecipient(SERVER_ADDRESS);
-    Message response = handleMessageWithTimeout(request);
-    Assert.assertNotNull(response);
-    //should be connected to only 1 remote server
-    Assert.assertEquals(1, handler.getWorkerCount());
-    Assert.assertEquals(response.getRecipient(), SERVER_ADDRESS);
-  }
-
- // @Test
-  public void handle_MultiRemote_ShouldReturnResponses() throws Exception {
-    ExecutorService threadPool = Executors.newCachedThreadPool();
-    final int port = 5555;
-    String serverAddress = null;
-    for (int i = 0; i < 5; i++) {
-      serverAddress = "localhost:" + (port + i);
-      serverThread.execute(MessagingUtil.startReplyServer(context, serverAddress, 1));
-      threadPool.execute(createEmptyMessageTaskAndHandle(handler, serverAddress));
-    }
-    Thread.sleep(5000);//wait for all messages to get processed
-    //should be connected to 5 remote server
-    Assert.assertEquals(5, handler.getWorkerCount());
-  }
-
-  private Runnable createEmptyMessageTaskAndHandle(final ClientRequestHandler handler, final String serverAddress) {
-
-    return new Runnable() {
-      @Override
-      public void run() {
-        Message request = new Message();
-        request.setRecipient(serverAddress);
-        try {
-          Message response = handleMessageWithTimeout(request);
-          Assert.assertNotNull(response);
-          Assert.assertEquals(response.getRecipient(), serverAddress);
-        } catch (Exception e) {
-          throw new RuntimeException(e);
-        }
-      }
-    };
-  }
-
-  private Message handleMessageWithTimeout(final Message request) {
-    Message response = null;
-
-    FutureTask<?> task = new FutureTask<Message>(new Callable<Message>() {
-
-      @Override
-      public Message call() {
-        try {
-          return handler.handle(request);
-        } catch (Exception e) {
-          _logger.debug("Client handler failed to handle request. Exception is [{}]", e);
-        }
-        return null;
-      }
-    });
-
-    serverThread.execute(task);
-
-    try {
-      response = (Message) task.get(5L, TimeUnit.SECONDS); //wait for max 5 sec for server to respond
-    } catch (Exception e) {/*ignore and continue*/}
-
-    return response;
-  }
-
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/MockRoutingTable.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/MockRoutingTable.java
deleted file mode 100644 (file)
index 179051e..0000000
+++ /dev/null
@@ -1,79 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.connector.remoterpc;
-
-import java.util.HashSet;
-import java.util.Set;
-
-import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable;
-import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTableException;
-import org.opendaylight.controller.sal.connector.remoterpc.api.SystemException;
-
-/**
- * Mock implementation of routing table
- */
-public class MockRoutingTable<K, V> implements RoutingTable {
-
-
-  @Override
-  public void addRoute(Object o, Object o2) throws RoutingTableException, SystemException {
-
-  }
-
-  @Override
-  public void addGlobalRoute(Object o, Object o2) throws RoutingTableException, SystemException {
-
-  }
-
-  @Override
-  public void removeRoute(Object o, Object o2) {
-
-  }
-
-  @Override
-  public void addRoutes(Set set, Object o) throws RoutingTableException, SystemException {
-    //To change body of implemented methods use File | Settings | File Templates.
-  }
-
-  @Override
-  public void removeRoutes(Set set, Object o) throws RoutingTableException, SystemException {
-    //To change body of implemented methods use File | Settings | File Templates.
-  }
-
-  @Override
-  public void removeGlobalRoute(Object o) throws RoutingTableException, SystemException {
-
-  }
-
-  @Override
-  public Object getGlobalRoute(Object o) throws RoutingTableException, SystemException {
-    return null;  //To change body of implemented methods use File | Settings | File Templates.
-  }
-
-  @Override
-  public Set<String> getRoutes(Object o) {
-    Set<String> routes = new HashSet<String>();
-    routes.add("localhost:5554");
-    return routes;
-  }
-
-  @Override
-  public Object getLastAddedRoute(Object o) {
-    return null;  //To change body of implemented methods use File | Settings | File Templates.
-  }
-
-//  @Override
-//  public Set<Map.Entry> getAllRoutes() {
-//    return Collections.emptySet();
-//  }
-
-//  @Override
-//  public Object getARoute(Object o) {
-//    return null;
-//  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcProviderTest.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/RemoteRpcProviderTest.java
deleted file mode 100644 (file)
index 06360aa..0000000
+++ /dev/null
@@ -1,62 +0,0 @@
-package org.opendaylight.controller.sal.connector.remoterpc;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-public class RemoteRpcProviderTest {
-  @Before
-  public void setUp() throws Exception {
-
-  }
-
-  @After
-  public void tearDown() throws Exception {
-
-  }
-
-  @Test
-  public void testSetRoutingTableProvider() throws Exception {
-
-  }
-
-  @Test
-  public void testOnSessionInitiated() throws Exception {
-
-  }
-
-  @Test
-  public void testGetSupportedRpcs() throws Exception {
-
-  }
-
-  @Test
-  public void testGetProviderFunctionality() throws Exception {
-
-  }
-
-  @Test
-  public void testInvokeRpc() throws Exception {
-
-  }
-
-  @Test
-  public void testInvokeRoutedRpc() throws Exception {
-
-  }
-
-  @Test
-  public void testStart() throws Exception {
-
-  }
-
-  @Test
-  public void testClose() throws Exception {
-
-  }
-
-  @Test
-  public void testStop() throws Exception {
-
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/SerilizationTest.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/SerilizationTest.java
deleted file mode 100644 (file)
index 41422fd..0000000
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sal.connector.remoterpc;
-
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.impl.NodeUtils;
-import org.opendaylight.yangtools.yang.data.impl.XmlTreeBuilder;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-
-import javax.xml.stream.XMLStreamException;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-import java.io.FileNotFoundException;
-import java.io.InputStream;
-import java.io.StringWriter;
-
-public class SerilizationTest {
-
-  private static final Logger _logger = LoggerFactory.getLogger(SerilizationTest.class);
-
-  public void fromXml() {
-  }
-
-  @Test
-  public void toXml() throws FileNotFoundException {
-
-    //InputStream xmlStream = SerilizationTest.class.getResourceAsStream("/FourSimpleChildren.xml");
-    InputStream xmlStream = SerilizationTest.class.getResourceAsStream("/AddFlow.xml");
-    StringWriter writer = new StringWriter();
-
-    CompositeNode data = loadCompositeNode(xmlStream);
-    Document domTree = NodeUtils.buildShadowDomTree(data);
-    try {
-      TransformerFactory tf = TransformerFactory.newInstance();
-      Transformer transformer = tf.newTransformer();
-      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
-      //transformer.setOutputProperty(OutputKeys.METHOD, "xml");
-      //transformer.setOutputProperty(OutputKeys.INDENT, "yes");
-      //transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
-      //transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
-      transformer.transform(new DOMSource(domTree), new StreamResult(writer));
-    } catch (TransformerException e) {
-      _logger.error("Error during translation of Document to OutputStream", e);
-    }
-
-    _logger.info("Parsed xml [{}]", writer.toString());
-  }
-
-  // Figure out how to include TestUtils through pom ...was getting errors
-  private CompositeNode loadCompositeNode(InputStream xmlInputStream) throws FileNotFoundException {
-    if (xmlInputStream == null) {
-      throw new IllegalArgumentException();
-    }
-    Node<?> dataTree;
-    try {
-      dataTree = XmlTreeBuilder.buildDataTree(xmlInputStream);
-    } catch (XMLStreamException e) {
-      _logger.error("Error during building data tree from XML", e);
-      return null;
-    }
-    if (dataTree == null) {
-      _logger.error("data tree is null");
-      return null;
-    }
-    if (dataTree instanceof SimpleNode) {
-      _logger.error("RPC XML was resolved as SimpleNode");
-      return null;
-    }
-    return (CompositeNode) dataTree;
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ServerImplTest.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ServerImplTest.java
deleted file mode 100644 (file)
index 7ffdf17..0000000
+++ /dev/null
@@ -1,195 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sal.connector.remoterpc;
-
-
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-import java.lang.reflect.Field;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.ThreadPoolExecutor;
-
-import junit.framework.Assert;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.sal.connector.api.RpcRouter;
-import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable;
-import org.opendaylight.controller.sal.connector.remoterpc.utils.MessagingUtil;
-import org.opendaylight.controller.sal.core.api.Broker;
-import org.opendaylight.controller.sal.core.api.RpcRegistrationListener;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.zeromq.ZMQ;
-
-import zmq.Ctx;
-import zmq.SocketBase;
-
-import com.google.common.base.Optional;
-
-public class ServerImplTest {
-
-  private static ZMQ.Context context;
-  private ServerImpl server;
-  private Broker.ProviderSession brokerSession;
-  private RoutingTableProvider routingTableProvider;
-  private RpcRegistrationListener listener;
-
-  ExecutorService pool;
-
-  //Server configuration
-  private final int HANDLER_COUNT = 2;
-  private final int HWM = 200;
-  private final int port = 5554;
-  //server address
-  private final String SERVER_ADDRESS = "tcp://localhost:5554";
-
-  //@BeforeClass
-  public static void init() {
-    context = ZMQ.context(1);
-  }
-
-  //@AfterClass
-  public static void destroy() {
-    MessagingUtil.closeZmqContext(context);
-  }
-
-  @Before
-  public void setup() throws InterruptedException {
-    context = ZMQ.context(1);
-    brokerSession = mock(Broker.ProviderSession.class);
-    routingTableProvider = mock(RoutingTableProvider.class);
-    listener = mock(RpcRegistrationListener.class);
-
-    server = new ServerImpl(port);
-    server.setBrokerSession(brokerSession);
-
-    RoutingTable<RpcRouter.RouteIdentifier<?, ?, ?>, String> mockRoutingTable = new MockRoutingTable<String, String>();
-    Optional<RoutingTable<RpcRouter.RouteIdentifier<?, ?, ?>, String>> optionalRoutingTable = Optional.fromNullable(mockRoutingTable);
-    when(routingTableProvider.getRoutingTable()).thenReturn(optionalRoutingTable);
-
-    when(brokerSession.addRpcRegistrationListener(listener)).thenReturn(null);
-    when(brokerSession.getSupportedRpcs()).thenReturn(Collections.<QName>emptySet());
-    when(brokerSession.rpc(null, mock(CompositeNode.class))).thenReturn(null);
-    server.start();
-    Thread.sleep(5000);//wait for server to start
-  }
-
-  @After
-  public void tearDown() throws InterruptedException {
-
-    if (pool != null)
-      pool.shutdown();
-
-    if (server != null)
-      server.stop();
-
-    MessagingUtil.closeZmqContext(context);
-
-    Thread.sleep(5000);//wait for server to stop
-    Assert.assertEquals(ServerImpl.State.STOPPED, server.getStatus());
-  }
-
-  @Test
-  public void getBrokerSession_Call_ShouldReturnBrokerSession() throws Exception {
-    Optional<Broker.ProviderSession> mayBeBroker = server.getBrokerSession();
-
-    if (mayBeBroker.isPresent())
-      Assert.assertEquals(brokerSession, mayBeBroker.get());
-    else
-      Assert.fail("Broker does not exist in Remote RPC Server");
-
-  }
-
-  @Test
-  public void start_Call_ShouldSetServerStatusToStarted() throws Exception {
-    Assert.assertEquals(ServerImpl.State.STARTED, server.getStatus());
-
-  }
-
-  @Test
-  public void start_Call_ShouldCreateNZmqSockets() throws Exception {
-    final int EXPECTED_COUNT = 2 + HANDLER_COUNT; //1 ROUTER + 1 DEALER + HANDLER_COUNT
-
-    Optional<ZMQ.Context> mayBeContext = server.getZmqContext();
-    if (mayBeContext.isPresent())
-      Assert.assertEquals(EXPECTED_COUNT, findSocketCount(mayBeContext.get()));
-    else
-      Assert.fail("ZMQ Context does not exist in Remote RPC Server");
-  }
-
-  @Test
-  public void start_Call_ShouldCreate1ServerThread() {
-    final String SERVER_THREAD_NAME = "remote-rpc-server";
-    final int EXPECTED_COUNT = 1;
-    List<Thread> serverThreads = findThreadsWithName(SERVER_THREAD_NAME);
-    Assert.assertEquals(EXPECTED_COUNT, serverThreads.size());
-  }
-
-  @Test
-  public void start_Call_ShouldCreateNHandlerThreads() {
-    //final String WORKER_THREAD_NAME = "remote-rpc-worker";
-    final int EXPECTED_COUNT = HANDLER_COUNT;
-
-    Optional<ServerRequestHandler> serverRequestHandlerOptional = server.getHandler();
-    if (serverRequestHandlerOptional.isPresent()){
-      ServerRequestHandler handler = serverRequestHandlerOptional.get();
-      ThreadPoolExecutor workerPool = handler.getWorkerPool();
-      Assert.assertEquals(EXPECTED_COUNT, workerPool.getPoolSize());
-    } else {
-      Assert.fail("Server is in illegal state. ServerHandler does not exist");
-    }
-
-  }
-
-  @Test
-  public void testStop() throws Exception {
-
-  }
-
-  @Test
-  public void testOnRouteUpdated() throws Exception {
-
-  }
-
-  @Test
-  public void testOnRouteDeleted() throws Exception {
-
-  }
-
-  private int findSocketCount(ZMQ.Context context)
-      throws NoSuchFieldException, IllegalAccessException {
-    Field ctxField = context.getClass().getDeclaredField("ctx");
-    ctxField.setAccessible(true);
-    Ctx ctx = Ctx.class.cast(ctxField.get(context));
-
-    Field socketListField = ctx.getClass().getDeclaredField("sockets");
-    socketListField.setAccessible(true);
-    List<SocketBase> sockets = List.class.cast(socketListField.get(ctx));
-
-    return sockets.size();
-  }
-
-  private List<Thread> findThreadsWithName(String name) {
-    Thread[] threads = new Thread[Thread.activeCount()];
-    Thread.enumerate(threads);
-
-    List<Thread> foundThreads = new ArrayList<Thread>();
-    for (Thread t : threads) {
-      if (t.getName().startsWith(name))
-        foundThreads.add(t);
-    }
-
-    return foundThreads;
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ServerRequestHandlerTest.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ServerRequestHandlerTest.java
deleted file mode 100644 (file)
index e5fbc76..0000000
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sal.connector.remoterpc;
-
-import static org.mockito.Mockito.mock;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-
-import junit.framework.Assert;
-
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.controller.sal.connector.remoterpc.utils.MessagingUtil;
-import org.opendaylight.controller.sal.core.api.Broker;
-import org.zeromq.ZMQ;
-
-public class ServerRequestHandlerTest {
-
-  ServerRequestHandler handler;
-  ZMQ.Context context;
-  ExecutorService executorService = Executors.newCachedThreadPool();
-  private final int workerCount = 2;
-  private final String mockDealerAddress = "inproc://rpc-request-handler";
-  private final String mockServerIp = "localhost";
-  private final int mockServerPort = 5554;
-
-  @Before
-  public void setUp() throws Exception {
-    context = ZMQ.context(1);
-    String mockServerAddress = mockServerIp + ":" + mockServerPort;
-    Broker.ProviderSession mockSession = mock(Broker.ProviderSession.class);
-    handler = new ServerRequestHandler(context, mockSession, workerCount, mockDealerAddress, mockServerAddress);
-    handler.start();
-  }
-
-  @After
-  public void tearDown() throws Exception {
-    executorService.shutdown();
-    MessagingUtil.closeZmqContext(context);
-    handler.close();
-  }
-
-  @Test
-  public void testStart() throws Exception {
-    //should start workers == workerCount
-    Assert.assertEquals(workerCount, handler.getWorkerPool().getPoolSize());
-
-    //killing a thread should recreate another one
-
-    //start router-dealer bridge
-    executorService.execute(MessagingUtil.createRouterDealerBridge(context, mockDealerAddress, mockServerPort));
-    Thread.sleep(1000); //give sometime for socket initialization
-
-    //this will kill the thread
-    final String WORKER_THREAD_NAME = "remote-rpc-worker";
-    interruptAThreadWithName(WORKER_THREAD_NAME);
-
-    //send 4 message to router
-    for (int i = 0; i < 4; i++)
-      executorService.execute(MessagingUtil.sendAnEmptyMessage(context, "tcp://" + mockServerIp + ":" + mockServerPort));
-
-    //worker pool size should not change.
-    Assert.assertEquals(workerCount, handler.getWorkerPool().getPoolSize());
-
-    Thread.sleep(10000); //wait for processing to complete
-  }
-
-  @Test
-  public void testClose() throws Exception {
-
-  }
-
-  /**
-   * Interrupts the first thread found whose name starts with the provided name
-   *
-   * @param name
-   */
-  private void interruptAThreadWithName(String name) {
-    List<Thread> workerThreads = findThreadsWithName(name);
-    if (workerThreads.size() > 0) workerThreads.get(0).interrupt();
-  }
-
-  /**
-   * Find all threads that start with the given name
-   *
-   * @param name
-   * @return
-   */
-  private List<Thread> findThreadsWithName(String name) {
-    Thread[] threads = new Thread[Thread.activeCount()];
-    Thread.enumerate(threads);
-
-    List<Thread> foundThreads = new ArrayList<Thread>();
-    for (Thread t : threads) {
-      if (t.getName().startsWith(name))
-        foundThreads.add(t);
-    }
-
-    return foundThreads;
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/utils/MessagingUtil.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/utils/MessagingUtil.java
deleted file mode 100644 (file)
index 883aa52..0000000
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sal.connector.remoterpc.utils;
-
-import java.io.IOException;
-import java.io.PrintWriter;
-import java.io.StringWriter;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.FutureTask;
-import java.util.concurrent.TimeUnit;
-
-import junit.framework.Assert;
-
-import org.opendaylight.controller.sal.connector.remoterpc.dto.Message;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.zeromq.ZMQ;
-
-public class MessagingUtil {
-
-  private static final Logger _logger = LoggerFactory.getLogger(MessagingUtil.class);
-
-  public static Runnable startReplyServer(final ZMQ.Context context,
-                                          final String serverAddress,
-                                          final int numRequests /*number of requests after which server shuts down*/) {
-    return new Runnable() {
-
-      @Override
-      public void run() {
-        final ZMQ.Socket socket = context.socket(ZMQ.REP);
-        try {
-          int returnCode = socket.bind("tcp://" + serverAddress);
-          Assert.assertNotSame(-1, returnCode);
-          _logger.info(" Starting reply server[{}] for test...", serverAddress);
-
-          //for (int i=0;i<numRequests;i++) {
-          while (!Thread.currentThread().isInterrupted()) {
-            byte[] bytes = socket.recv();
-            _logger.debug(" Got request ");
-            socket.send(bytes);
-            _logger.debug(" Sent response ");
-          }
-        } catch (Exception x) {
-          StringWriter w = new StringWriter();
-          PrintWriter p = new PrintWriter(w);
-          x.printStackTrace(p);
-          _logger.debug(w.toString());
-        } finally {
-          socket.close();
-          _logger.info("Shutting down reply server");
-        }
-      }
-    };
-  }
-
-  public static Runnable createRouterDealerBridge(final ZMQ.Context context, final String dealerAddress, final int routerPort) {
-    return new Runnable() {
-      @Override
-      public void run() {
-        ZMQ.Socket router = null;
-        ZMQ.Socket dealer = null;
-        try {
-          router = context.socket(ZMQ.ROUTER);
-          dealer = context.socket(ZMQ.DEALER);
-          router.bind("tcp://*:" + routerPort);
-          dealer.bind(dealerAddress);
-          ZMQ.proxy(router, dealer, null);
-        } catch (Exception e) {/*Ignore*/} finally {
-          if (router != null) router.close();
-          if (dealer != null) dealer.close();
-        }
-      }
-    };
-  }
-
-  public static Runnable sendAMessage(final ZMQ.Context context, final String serverAddress, final Message msg)
-      throws IOException, ClassNotFoundException, InterruptedException {
-
-    return new Runnable() {
-      @Override
-      public void run() {
-        final ZMQ.Socket socket = context.socket(ZMQ.REQ);
-        try {
-
-          socket.connect(serverAddress);
-          System.out.println(Thread.currentThread().getName() + " Sending message");
-          try {
-            socket.send(Message.serialize(msg));
-          } catch (IOException e) {
-            e.printStackTrace();
-          }
-          byte[] bytes = socket.recv();
-          Message response = null;
-          try {
-            response = (Message) Message.deserialize(bytes);
-          } catch (IOException e) {
-            e.printStackTrace();
-          } catch (ClassNotFoundException e) {
-            e.printStackTrace();
-          }
-          System.out.println(Thread.currentThread().getName() + " Got response " + response);
-        } catch (Exception x) {
-          x.printStackTrace();
-        } finally {
-          socket.close();
-        }
-      }
-    };
-  }
-
-  public static Runnable sendAnEmptyMessage(final ZMQ.Context context, final String serverAddress)
-          throws IOException, ClassNotFoundException, InterruptedException {
-
-    return new Runnable() {
-      @Override
-      public void run() {
-        final ZMQ.Socket socket = context.socket(ZMQ.REQ);
-        try {
-
-          socket.connect(serverAddress);
-          System.out.println(Thread.currentThread().getName() + " Sending message");
-          try {
-            socket.send(Message.serialize(new Message()));
-          } catch (IOException e) {
-            e.printStackTrace();
-          }
-          byte[] bytes = socket.recv();
-          Message response = null;
-          try {
-            response = (Message) Message.deserialize(bytes);
-          } catch (IOException e) {
-            e.printStackTrace();
-          } catch (ClassNotFoundException e) {
-            e.printStackTrace();
-          }
-          System.out.println(Thread.currentThread().getName() + " Got response " + response);
-        } catch (Exception x) {
-          x.printStackTrace();
-        } finally {
-          socket.close();
-        }
-      }
-    };
-  }
-
-  public static Message createEmptyMessage() {
-    return new Message();
-  }
-
-  /**
-   * Closes ZMQ Context. It tries to gracefully terminate the context. If
-   * termination takes more than a second, its forcefully shutdown.
-   */
-  public static void closeZmqContext(final ZMQ.Context context) {
-    if (context == null) return;
-
-    ExecutorService exec = Executors.newSingleThreadExecutor();
-    FutureTask<?> zmqTermination = new FutureTask<Void>(new Runnable() {
-
-      @Override
-      public void run() {
-        try {
-          if (context != null)
-            context.term();
-            _logger.debug("ZMQ Context terminated gracefully!");
-        } catch (Exception e) {/*Ignore and continue shutdown*/}
-      }
-    }, null);
-
-    exec.execute(zmqTermination);
-
-    try {
-      zmqTermination.get(1L, TimeUnit.SECONDS);
-    } catch (Exception e) {
-      _logger.debug("ZMQ Context terminated forcefully!");
-    }
-
-    exec.shutdownNow();
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/utils/RemoteServerTestClient.java b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/utils/RemoteServerTestClient.java
deleted file mode 100644 (file)
index 7a4f4a5..0000000
+++ /dev/null
@@ -1,89 +0,0 @@
-package org.opendaylight.controller.sal.connector.remoterpc.utils;
-
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-
-import org.opendaylight.controller.sal.connector.api.RpcRouter;
-import org.opendaylight.controller.sal.connector.remoterpc.dto.Message;
-import org.opendaylight.controller.sal.connector.remoterpc.util.XmlUtils;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.zeromq.ZMQ;
-
-public class RemoteServerTestClient {
-
-
-
-  public static void main(String args[]) throws Exception{
-    String serverAddress = "tcp://10.195.128.108:5666";
-    ZMQ.Context ctx = ZMQ.context(1);
-    ExecutorService executor = Executors.newSingleThreadExecutor();
-    RemoteServerTestClient client = new RemoteServerTestClient();
-    executor.execute(
-        MessagingUtil.sendAMessage(ctx, serverAddress, client.createPingMessage(serverAddress))
-    );
-    MessagingUtil.sendAMessage(ctx, serverAddress, client.createPingMessage(serverAddress));
-
-    Thread.sleep(5000);
-    MessagingUtil.closeZmqContext(ctx);
-    executor.shutdown();
-  }
-
-  public Message createPingMessage(String serverAddress){
-    Message ping = new Message.MessageBuilder()
-        .type(Message.MessageType.PING)
-        .sender("localhost:5444")
-        .recipient(serverAddress)
-        .build();
-
-    return ping;
-  }
-  public Message createAddFlowMessage(String serverAddress ){
-
-    RpcRouter.RouteIdentifier<?, ?, ?> routeIdentifier = getAddFlowRpcIdentifier();
-
-    Message addFlow = new Message.MessageBuilder()
-        .type(Message.MessageType.REQUEST)
-        .sender("localhost:5444")
-        .recipient(serverAddress)
-        .route(routeIdentifier)
-        .payload(getAddFlowPayload(1,1))
-        .build();
-
-    return addFlow;
-  }
-
-  private RpcRouter.RouteIdentifier<?, ?, ?> getAddFlowRpcIdentifier(){
-    throw new UnsupportedOperationException();
-  }
-
-  private CompositeNode getAddFlowPayload(int flowId, int tableId){
-    final String xml =
-    "<flow xmlns=\"urn:opendaylight:flow:inventory\">"
-    + "<priority>5</priority>"
-    + "<flow-name>Foo</flow-name>"
-    + "<match>"
-    + "<ethernet-match>"
-    + "<ethernet-type>"
-    + "<type>2048</type>"
-    + "</ethernet-type>"
-    + "</ethernet-match>"
-    + "<ipv4-destination>10.0.10.2/24</ipv4-destination>"
-    + "</match>"
-    + "<id>" + flowId + "</id>"
-    + "<table_id>" + tableId + "</table_id>"
-    + "<instructions>"
-    + "<instruction>"
-    + "<order>0</order>"
-    + "<apply-actions>"
-    + "<action>"
-    + "<order>0</order>"
-    + "<dec-nw-ttl/>"
-    + "</action>"
-    + "</apply-actions>"
-    + "</instruction>"
-    + "</instructions>"
-    + "</flow>";
-
-    return XmlUtils.xmlToCompositeNode(xml);
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/resources/AddFlow.xml b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/resources/AddFlow.xml
deleted file mode 100644 (file)
index b042b8f..0000000
+++ /dev/null
@@ -1,36 +0,0 @@
-<add-flow xmlns="urn:opendaylight:flow:service">
-  <input>
-    <transaction-uri>BA-7</transaction-uri>
-    <table_id>4</table_id>
-    <priority>5</priority>
-    <node>
-      /(urn:opendaylight:inventory?revision=2013-08-19)nodes/(urn:opendaylight:inventory?revision=2013-08-19)node[{(urn:opendaylight:inventory?revision=2013-08-19)id=openflow:1}]
-    </node>
-    <match>
-      <ipv4-destination>10.0.10.2/24</ipv4-destination>
-      <ethernet-match>
-        <ethernet-type>
-          <type>2048</type>
-        </ethernet-type>
-      </ethernet-match>
-    </match>
-    <instructions>
-      <instruction>
-        <order>0</order>
-        <apply-actions>
-          <action>
-            <order>0</order>
-            <dec-nw-ttl/>
-          </action>
-        </apply-actions>
-      </instruction>
-    </instructions>
-    <flow-table>
-      /(urn:opendaylight:inventory?revision=2013-08-19)nodes/(urn:opendaylight:inventory?revision=2013-08-19)node[{(urn:opendaylight:inventory?revision=2013-08-19)id=openflow:1}]/(urn:opendaylight:flow:inventory?revision=2013-08-19)table[{(urn:opendaylight:flow:inventory?revision=2013-08-19)id=4}]
-    </flow-table>
-    <flow-ref>
-      /(urn:opendaylight:inventory?revision=2013-08-19)nodes/(urn:opendaylight:inventory?revision=2013-08-19)node[{(urn:opendaylight:inventory?revision=2013-08-19)id=openflow:1}]/(urn:opendaylight:flow:inventory?revision=2013-08-19)table[{(urn:opendaylight:flow:inventory?revision=2013-08-19)id=4}]/(urn:opendaylight:flow:inventory?revision=2013-08-19)flow[{(urn:opendaylight:flow:inventory?revision=2013-08-19)id=4}]
-    </flow-ref>
-    <flow-name>Foo</flow-name>
-  </input>
-</add-flow>
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/resources/FourSimpleChildren.xml b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/resources/FourSimpleChildren.xml
deleted file mode 100644 (file)
index 5ac991b..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-<rpc>
-    <name>eth0</name>
-    <type>ethernetCsmacd</type>
-    <enabled>false</enabled>
-    <description>some interface</description>
-</rpc>
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/resources/logback-test.xml b/opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/resources/logback-test.xml
deleted file mode 100644 (file)
index 7eb75b9..0000000
+++ /dev/null
@@ -1,13 +0,0 @@
-<configuration scan="true">
-
-  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
-    <encoder>
-      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
-      </pattern>
-    </encoder>
-  </appender>
-
-  <root level="DEBUG">
-    <appender-ref ref="STDOUT" />
-  </root>
-</configuration>
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/pom.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/pom.xml
deleted file mode 100644 (file)
index 8435884..0000000
+++ /dev/null
@@ -1,77 +0,0 @@
-<?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.tests</groupId>
-    <artifactId>sal-remoterpc-connector-test-parent</artifactId>
-    <version>1.1-SNAPSHOT</version>
-  </parent>
-  <artifactId>sal-remoterpc-connector-test-consumer</artifactId>
-  <packaging>bundle</packaging>
-
-  <dependencies>
-
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>containermanager</artifactId>
-    </dependency>
-
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>sal</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>sal-binding-api</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>sal-common-util</artifactId>
-    </dependency>
-
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>sal-common-util</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>sal-core-api</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.yangtools</groupId>
-      <artifactId>yang-binding</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.yangtools</groupId>
-      <artifactId>yang-common</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.yangtools</groupId>
-      <artifactId>yang-data-api</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.yangtools</groupId>
-      <artifactId>yang-data-impl</artifactId>
-      <version>${yangtools.version}</version>
-    </dependency>
-  </dependencies>
-
-  <build>
-    <plugins>
-      <plugin>
-        <groupId>org.apache.felix</groupId>
-        <artifactId>maven-bundle-plugin</artifactId>
-        <configuration>
-          <instructions>
-            <Bundle-Activator>org.opendaylight.controller.sample.zeromq.consumer.ExampleConsumer</Bundle-Activator>
-          </instructions>
-        </configuration>
-      </plugin>
-    </plugins>
-  </build>
-  <scm>
-    <connection>scm:git:ssh://git.opendaylight.org:29418/controller.git</connection>
-    <developerConnection>scm:git:ssh://git.opendaylight.org:29418/controller.git</developerConnection>
-    <url>https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL</url>
-  </scm>
-</project>
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/java/org/opendaylight/controller/sample/zeromq/consumer/ExampleConsumer.java b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/java/org/opendaylight/controller/sample/zeromq/consumer/ExampleConsumer.java
deleted file mode 100644 (file)
index aac6da4..0000000
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sample.zeromq.consumer;
-
-import java.io.FileNotFoundException;
-import java.io.InputStream;
-import java.net.URI;
-import java.util.Hashtable;
-import java.util.concurrent.Future;
-
-import org.opendaylight.controller.sal.core.api.AbstractConsumer;
-import org.opendaylight.controller.sal.core.api.Broker.ConsumerSession;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.opendaylight.yangtools.yang.data.impl.XmlTreeBuilder;
-
-import javax.xml.stream.XMLStreamException;
-
-public class ExampleConsumer extends AbstractConsumer {
-
-  private final URI namespace = URI.create("http://cisco.com/example");
-  private final QName QNAME = new QName(namespace, "heartbeat");
-
-  private ConsumerSession session;
-
-  private ServiceRegistration<ExampleConsumer> thisReg;
-  private Logger _logger = LoggerFactory.getLogger(ExampleConsumer.class);
-
-  @Override
-  public void onSessionInitiated(ConsumerSession session) {
-    this.session = session;
-  }
-
-  public RpcResult<CompositeNode> invokeRpc(QName qname, CompositeNode input) {
-    _logger.info("Invoking RPC:[{}] with Input:[{}]", qname.getLocalName(), input);
-    RpcResult<CompositeNode> result = null;
-    Future<RpcResult<CompositeNode>> future = ExampleConsumer.this.session.rpc(qname, input);
-    try {
-      result = future.get();
-    } catch (Exception e) {
-      e.printStackTrace();
-    }
-    _logger.info("Returning Result:[{}]", result);
-    return result;
-  }
-
-  @Override
-  protected void startImpl(BundleContext context){
-    thisReg = context.registerService(ExampleConsumer.class, this, new Hashtable<String,String>());
-  }
-  @Override
-  protected void stopImpl(BundleContext context) {
-    super.stopImpl(context);
-    thisReg.unregister();
-  }
-
-  public CompositeNode getValidCompositeNodeWithOneSimpleChild() throws FileNotFoundException {
-    InputStream xmlStream = ExampleConsumer.class.getResourceAsStream("/OneSimpleChild.xml");
-    return loadCompositeNode(xmlStream);
-  }
-
-  public CompositeNode getValidCompositeNodeWithTwoSimpleChildren() throws FileNotFoundException {
-    InputStream xmlStream = ExampleConsumer.class.getResourceAsStream("/TwoSimpleChildren.xml");
-    return loadCompositeNode(xmlStream);
-  }
-
-  public CompositeNode getValidCompositeNodeWithFourSimpleChildren() throws FileNotFoundException {
-    InputStream xmlStream = ExampleConsumer.class.getResourceAsStream("/FourSimpleChildren.xml");
-    return loadCompositeNode(xmlStream);
-  }
-
-  public CompositeNode getValidCompositeNodeWithOneSimpleOneCompositeChild() throws FileNotFoundException {
-    InputStream xmlStream = ExampleConsumer.class.getResourceAsStream("/OneSimpleOneCompositeChild.xml");
-    return loadCompositeNode(xmlStream);
-  }
-
-  public CompositeNode getValidCompositeNodeWithTwoCompositeChildren() throws FileNotFoundException {
-    InputStream xmlStream = ExampleConsumer.class.getResourceAsStream("/TwoCompositeChildren.xml");
-    return loadCompositeNode(xmlStream);
-  }
-
-  public CompositeNode getInvalidCompositeNodeSimpleChild() throws FileNotFoundException {
-    InputStream xmlStream = ExampleConsumer.class.getResourceAsStream("/InvalidSimpleChild.xml");
-    return loadCompositeNode(xmlStream);
-  }
-
-  public CompositeNode getInvalidCompositeNodeCompositeChild() throws FileNotFoundException {
-    InputStream xmlStream = ExampleConsumer.class.getResourceAsStream("/InvalidCompositeChild.xml");
-    return loadCompositeNode(xmlStream);
-  }
-
-  //Note to self:  Stolen from TestUtils
-  ///Users/alefan/odl/controller4/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/TestUtils.java
-  // Figure out how to include TestUtils through pom ...was getting errors
-  private CompositeNode loadCompositeNode(InputStream xmlInputStream) throws FileNotFoundException {
-    if (xmlInputStream == null) {
-      throw new IllegalArgumentException();
-    }
-    Node<?> dataTree;
-    try {
-      dataTree = XmlTreeBuilder.buildDataTree(xmlInputStream);
-    } catch (XMLStreamException e) {
-      _logger.error("Error during building data tree from XML", e);
-      return null;
-    }
-    if (dataTree == null) {
-      _logger.error("data tree is null");
-      return null;
-    }
-    if (dataTree instanceof SimpleNode) {
-      _logger.error("RPC XML was resolved as SimpleNode");
-      return null;
-    }
-    return (CompositeNode) dataTree;
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/FourSimpleChildren.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/FourSimpleChildren.xml
deleted file mode 100644 (file)
index 5ac991b..0000000
+++ /dev/null
@@ -1,6 +0,0 @@
-<rpc>
-    <name>eth0</name>
-    <type>ethernetCsmacd</type>
-    <enabled>false</enabled>
-    <description>some interface</description>
-</rpc>
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/InvalidCompositeChild.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/InvalidCompositeChild.xml
deleted file mode 100644 (file)
index 3979d02..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-<rpc>
-    <innerinterface1>
-        <name>eth1</name>
-        <type>ethernet</type>
-        <enabled>false</enabled>
-        <description>some interface</description>
-    </innerinterface1>
-    <innerinterface2>
-        <name>error</name>
-        <type>ethernet</type>
-        <enabled>true</enabled>
-        <description>some interface</description>
-    </innerinterface2>
-</rpc>
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/InvalidSimpleChild.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/InvalidSimpleChild.xml
deleted file mode 100644 (file)
index 6082d72..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<rpc>
-    <name>error</name>
-</rpc>
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/OneSimpleChild.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/OneSimpleChild.xml
deleted file mode 100644 (file)
index f431b04..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-<rpc>
-    <name>eth0</name>
-</rpc>
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/OneSimpleOneCompositeChild.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/OneSimpleOneCompositeChild.xml
deleted file mode 100644 (file)
index bca7682..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-<rpc>
-    <name>eth0</name>
-    <innerinterface>
-        <name>eth1</name>
-        <type>ethernetCsmacd</type>
-        <enabled>false</enabled>
-        <description>some interface</description>
-    </innerinterface>
-</rpc>
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/TwoCompositeChildren.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/TwoCompositeChildren.xml
deleted file mode 100644 (file)
index c49407e..0000000
+++ /dev/null
@@ -1,14 +0,0 @@
-<rpc>
-    <innerinterface1>
-        <name>eth1</name>
-        <type>ethernet</type>
-        <enabled>false</enabled>
-        <description>some interface</description>
-    </innerinterface1>
-    <innerinterface2>
-        <name>eth2</name>
-        <type>ethernet</type>
-        <enabled>true</enabled>
-        <description>some interface</description>
-    </innerinterface2>
-</rpc>
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/TwoSimpleChildren.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/consumer-service/src/main/resources/TwoSimpleChildren.xml
deleted file mode 100644 (file)
index 5f4729c..0000000
+++ /dev/null
@@ -1,4 +0,0 @@
-<rpc>
-    <name>eth0</name>
-    <type>ethernetCsmacd</type>
-</rpc>
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/pom.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/pom.xml
deleted file mode 100644 (file)
index 3f47700..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-<?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>sal-parent</artifactId>
-    <version>1.1-SNAPSHOT</version>
-    <relativePath>../..</relativePath>
-  </parent>
-  <groupId>org.opendaylight.controller.tests</groupId>
-  <artifactId>sal-remoterpc-connector-test-parent</artifactId>
-  <packaging>pom</packaging>
-
-  <modules>
-    <module>consumer-service</module>
-    <module>provider-service</module>
-    <module>test-it</module>
-    <module>test-nb</module>
-  </modules>
-  <scm>
-    <connection>scm:git:ssh://git.opendaylight.org:29418/controller.git</connection>
-    <developerConnection>scm:git:ssh://git.opendaylight.org:29418/controller.git</developerConnection>
-    <url>https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL</url>
-  </scm>
-
-</project>
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/provider-service/pom.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/provider-service/pom.xml
deleted file mode 100644 (file)
index 2b9dc0c..0000000
+++ /dev/null
@@ -1,82 +0,0 @@
-<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>
-        <artifactId>sal-remoterpc-connector-test-parent</artifactId>
-        <groupId>org.opendaylight.controller.tests</groupId>
-        <version>1.1-SNAPSHOT</version>
-  </parent>
-  <artifactId>sal-remoterpc-connector-test-provider</artifactId>
-  <packaging>bundle</packaging>
-  <scm>
-    <connection>scm:git:ssh://git.opendaylight.org:29418/controller.git</connection>
-    <developerConnection>scm:git:ssh://git.opendaylight.org:29418/controller.git</developerConnection>
-    <url>https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL</url>
-  </scm>
-
-
-  <build>
-    <plugins>
-      <plugin>
-        <groupId>org.apache.felix</groupId>
-        <artifactId>maven-bundle-plugin</artifactId>
-        <configuration>
-          <instructions>
-            <Bundle-Activator>org.opendaylight.controller.sample.zeromq.provider.ExampleProvider</Bundle-Activator>
-          </instructions>
-        </configuration>
-      </plugin>
-    </plugins>
-  </build>
-
-  <dependencies>
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>sal-binding-api</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>sal-common-util</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>sal-core-api</artifactId>
-    </dependency>
-
-
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>containermanager</artifactId>
-    </dependency>
-
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>sal</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.yangtools</groupId>
-      <artifactId>yang-binding</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.yangtools</groupId>
-      <artifactId>yang-common</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.yangtools</groupId>
-      <artifactId>yang-data-api</artifactId>
-    </dependency>
-        <dependency>
-      <groupId>org.opendaylight.yangtools</groupId>
-      <artifactId>yang-data-impl</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>sal-common-util</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>sal-remoterpc-connector</artifactId>
-    </dependency>
-
-  </dependencies>
-</project>
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/provider-service/src/main/java/org/opendaylight/controller/sample/zeromq/provider/ExampleProvider.java b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/provider-service/src/main/java/org/opendaylight/controller/sample/zeromq/provider/ExampleProvider.java
deleted file mode 100644 (file)
index ff930db..0000000
+++ /dev/null
@@ -1,130 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.sample.zeromq.provider;
-
-import org.opendaylight.controller.sal.common.util.RpcErrors;
-import org.opendaylight.controller.sal.common.util.Rpcs;
-import org.opendaylight.controller.sal.core.api.AbstractProvider;
-import org.opendaylight.controller.sal.core.api.Broker.ProviderSession;
-import org.opendaylight.controller.sal.core.api.Broker.RpcRegistration;
-import org.opendaylight.controller.sal.core.api.RpcImplementation;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.RpcError;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
-import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceRegistration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-
-public class ExampleProvider extends AbstractProvider implements RpcImplementation {
-
-  private final URI namespace = URI.create("http://cisco.com/example");
-  private final QName QNAME = new QName(namespace, "heartbeat");
-  private RpcRegistration reg;
-
-  private ServiceRegistration thisReg;
-
-  private ProviderSession session;
-  private Logger _logger = LoggerFactory.getLogger(ExampleProvider.class);
-
-  @Override
-  public void onSessionInitiated(ProviderSession session) {
-    this.session = session;
-  }
-
-  @Override
-  public Set<QName> getSupportedRpcs() {
-    Set<QName> supportedRpcs = new HashSet<QName>();
-    supportedRpcs.add(QNAME);
-    return supportedRpcs;
-  }
-
-  @Override
-  public RpcResult<CompositeNode> invokeRpc(final QName rpc, CompositeNode input) {
-    boolean success = false;
-    CompositeNode output = null;
-    Collection<RpcError> errors = new ArrayList<>();
-
-    // Only handle supported RPC calls
-    if (getSupportedRpcs().contains(rpc))  {
-      if (input == null) {
-        errors.add(RpcErrors.getRpcError("app", "tag", "info", RpcError.ErrorSeverity.WARNING, "message:null input", RpcError.ErrorType.RPC, null));
-      }
-      else {
-        if (isErroneousInput(input)) {
-          errors.add(RpcErrors.getRpcError("app", "tag", "info", RpcError.ErrorSeverity.ERROR, "message:error", RpcError.ErrorType.RPC, null));
-        }
-        else {
-          success = true;
-          output = addSuccessNode(input);
-        }
-      }
-    }
-    return Rpcs.getRpcResult(success, output, errors);
-  }
-
-  // Examines input -- dives into CompositeNodes and finds any value equal to "error"
-  private boolean isErroneousInput(CompositeNode input) {
-    for (Node<?> n : input.getChildren()) {
-      if (n instanceof CompositeNode) {
-        if (isErroneousInput((CompositeNode)n)) {
-          return true;
-        }
-      }
-      else {  //SimpleNode
-        if ((input.getChildren().get(0).getValue()).equals("error")) {
-          return true;
-        }
-      }
-    }
-    return false;
-  }
-
-  // Adds a child SimpleNode containing the value "success" to the input CompositeNode
-  private CompositeNode addSuccessNode(CompositeNode input) {
-    List<Node<?>> list = new ArrayList<Node<?>>(input.getChildren());
-    SimpleNodeTOImpl<String> simpleNode = new SimpleNodeTOImpl<String>(QNAME, input, "success");
-    list.add(simpleNode);
-    return new CompositeNodeTOImpl(QNAME, null, list);
-  }
-
-  @Override
-  protected void startImpl(BundleContext context) {
-    thisReg = context.registerService(ExampleProvider.class, this, new Hashtable<String, String>());
-  }
-
-  @Override
-  protected void stopImpl(BundleContext context) {
-    if (reg != null) {
-      try {
-        reg.close();
-        thisReg.unregister();
-      } catch (Exception e) {
-        // TODO Auto-generated catch block
-        e.printStackTrace();
-      }
-    }
-  }
-
-  public void announce(QName name) {
-    _logger.debug("Announcing [{}]\n\n\n", name);
-    reg = this.session.addRpcImplementation(name, this);
-  }
-
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-it/pom.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-it/pom.xml
deleted file mode 100644 (file)
index 0ffc330..0000000
+++ /dev/null
@@ -1,467 +0,0 @@
-<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>
-        <artifactId>sal-remoterpc-connector-test-parent</artifactId>
-        <groupId>org.opendaylight.controller.tests</groupId>
-        <version>1.1-SNAPSHOT</version>
-    </parent>
-    <artifactId>sal-remoterpc-connector-test-it</artifactId>
-    <scm>
-        <connection>scm:git:ssh://git.opendaylight.org:29418/controller.git</connection>
-        <developerConnection>scm:git:ssh://git.opendaylight.org:29418/controller.git</developerConnection>
-        <url>https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL</url>
-    </scm>
-
-
-    <build>
-        <plugins>
-            <plugin>
-                <groupId>org.ops4j.pax.exam</groupId>
-                <artifactId>maven-paxexam-plugin</artifactId>
-                <executions>
-                    <execution>
-                        <id>generate-config</id>
-                        <goals>
-                            <goal>generate-depends-file</goal>
-                        </goals>
-                    </execution>
-                </executions>
-            </plugin>
-        </plugins>
-        <pluginManagement>
-            <plugins>
-                <!--This plugin's configuration is used to store Eclipse
-                    m2e settings only. It has no influence on the Maven build itself. -->
-                <plugin>
-                    <groupId>org.eclipse.m2e</groupId>
-                    <artifactId>lifecycle-mapping</artifactId>
-                    <version>${lifecycle.mapping.version}</version>
-                    <configuration>
-                        <lifecycleMappingMetadata>
-                            <pluginExecutions>
-                                <pluginExecution>
-                                    <pluginExecutionFilter>
-                                        <groupId>
-                                            org.ops4j.pax.exam
-                                        </groupId>
-                                        <artifactId>
-                                            maven-paxexam-plugin
-                                        </artifactId>
-                                        <versionRange>
-                                            [1.2.4,)
-                                        </versionRange>
-                                        <goals>
-                                            <goal>
-                                                generate-depends-file
-                                            </goal>
-                                        </goals>
-                                    </pluginExecutionFilter>
-                                    <action>
-                                        <ignore></ignore>
-                                    </action>
-                                </pluginExecution>
-                            </pluginExecutions>
-                        </lifecycleMappingMetadata>
-                    </configuration>
-                </plugin>
-            </plugins>
-        </pluginManagement>
-    </build>
-
-    <dependencies>
-        <dependency>
-            <groupId>org.opendaylight.yangtools.thirdparty</groupId>
-            <artifactId>xtend-lib-osgi</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller.tests</groupId>
-            <artifactId>sal-remoterpc-connector-test-provider</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller.tests</groupId>
-            <artifactId>sal-remoterpc-connector-test-consumer</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>sal-broker-impl</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.ops4j.pax.exam</groupId>
-            <artifactId>pax-exam-container-native</artifactId>
-            <version>${exam.version}</version>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.ops4j.pax.exam</groupId>
-            <artifactId>pax-exam-junit4</artifactId>
-            <version>${exam.version}</version>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.ops4j.pax.exam</groupId>
-            <artifactId>pax-exam-link-mvn</artifactId>
-            <version>${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>equinoxSDK381</groupId>
-            <artifactId>org.eclipse.osgi</artifactId>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.slf4j</groupId>
-            <artifactId>log4j-over-slf4j</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>ch.qos.logback</groupId>
-            <artifactId>logback-core</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>ch.qos.logback</groupId>
-            <artifactId>logback-classic</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>sal-binding-api</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>sal-common-util</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>sal-core-api</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>sal-remoterpc-connector</artifactId>
-        </dependency>
-
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>containermanager</artifactId>
-            <exclusions>
-                <exclusion>
-                    <groupId>org.osgi</groupId>
-                    <artifactId>org.osgi.compendium</artifactId>
-                </exclusion>
-                <exclusion>
-                    <artifactId>commons-io</artifactId>
-                    <groupId>commons-io</groupId>
-                </exclusion>
-            </exclusions>
-        </dependency>
-
-        <dependency>
-            <groupId>org.opendaylight.yangtools</groupId>
-            <artifactId>yang-binding</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.yangtools</groupId>
-            <artifactId>yang-common</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.yangtools</groupId>
-            <artifactId>yang-data-api</artifactId>
-        </dependency>
-        <!--dependency> <groupId>org.opendaylight.yangtools</groupId> <artifactId>yang-data-impl</artifactId>
-            <version>${yangtools.version}</version> </dependency -->
-        <dependency>
-            <groupId>org.opendaylight.yangtools</groupId>
-            <artifactId>yang-parser-impl</artifactId>
-            <version>${yangtools.version}</version>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>sal-common-util</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.yangtools.thirdparty</groupId>
-            <artifactId>antlr4-runtime-osgi-nohead</artifactId>
-        </dependency>
-
-        <!-- routing table dependencies -->
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>zeromq-routingtable.implementation</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>clustering.services</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>sal</artifactId>
-            <exclusions>
-                <exclusion>
-                    <groupId>org.osgi</groupId>
-                    <artifactId>org.osgi.compendium</artifactId>
-                </exclusion>
-            </exclusions>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>sal.implementation</artifactId>
-            <exclusions>
-                <exclusion>
-                    <artifactId>commons-io</artifactId>
-                    <groupId>commons-io</groupId>
-                </exclusion>
-            </exclusions>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>containermanager</artifactId>
-            <exclusions>
-                <exclusion>
-                    <groupId>org.osgi</groupId>
-                    <artifactId>org.osgi.compendium</artifactId>
-                </exclusion>
-                <exclusion>
-                    <artifactId>commons-io</artifactId>
-                    <groupId>commons-io</groupId>
-                </exclusion>
-            </exclusions>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>containermanager.it.implementation</artifactId>
-            <exclusions>
-                <exclusion>
-                    <artifactId>commons-io</artifactId>
-                    <groupId>commons-io</groupId>
-                </exclusion>
-            </exclusions>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>clustering.stub</artifactId>
-            <exclusions>
-                <exclusion>
-                    <artifactId>commons-io</artifactId>
-                    <groupId>commons-io</groupId>
-                </exclusion>
-            </exclusions>
-        </dependency>
-
-        <dependency>
-            <groupId>org.apache.felix</groupId>
-            <artifactId>org.apache.felix.dependencymanager.shell</artifactId>
-            <exclusions>
-                <exclusion>
-                    <groupId>org.osgi</groupId>
-                    <artifactId>org.osgi.compendium</artifactId>
-                </exclusion>
-            </exclusions>
-        </dependency>
-        <dependency>
-            <groupId>eclipselink</groupId>
-            <artifactId>javax.resource</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>com.google.guava</groupId>
-            <artifactId>guava</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>sal</artifactId>
-        </dependency>
-        <dependency>
-          <groupId>org.opendaylight.controller</groupId>
-          <artifactId>ietf-netconf-monitoring</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.yangtools</groupId>
-            <artifactId>yang-binding</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.yangtools.model</groupId>
-            <artifactId>yang-ext</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.yangtools.model</groupId>
-            <artifactId>opendaylight-l2-types</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>sal-binding-it</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>sal-binding-config</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>sal-binding-broker-impl</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>sal-broker-impl</artifactId>
-        </dependency>
-
-        <dependency>
-            <groupId>org.opendaylight.controller.model</groupId>
-            <artifactId>model-inventory</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.yangtools</groupId>
-            <artifactId>yang-common</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>sal-connector-api</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>sal-common-util</artifactId>
-        </dependency>
-
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>clustering.services</artifactId>
-        </dependency>
-
-        <dependency>
-            <groupId>equinoxSDK381</groupId>
-            <artifactId>org.eclipse.osgi</artifactId>
-        </dependency>
-
-        <dependency>
-            <groupId>com.fasterxml.jackson.core</groupId>
-            <artifactId>jackson-databind</artifactId>
-            <version>${jackson.version}</version>
-        </dependency>
-
-        <dependency>
-            <groupId>com.fasterxml.jackson.core</groupId>
-            <artifactId>jackson-annotations</artifactId>
-            <version>${jackson.version}</version>
-        </dependency>
-
-        <dependency>
-            <groupId>com.fasterxml.jackson.core</groupId>
-            <artifactId>jackson-core</artifactId>
-            <version>${jackson.version}</version>
-        </dependency>
-
-        <dependency>
-            <groupId>org.zeromq</groupId>
-            <artifactId>jeromq</artifactId>
-        </dependency>
-
-        <dependency>
-            <groupId>org.opendaylight.yangtools.thirdparty</groupId>
-            <artifactId>xtend-lib-osgi</artifactId>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>sal-binding-broker-impl</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.ops4j.pax.exam</groupId>
-            <artifactId>pax-exam-container-native</artifactId>
-            <version>${exam.version}</version>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.ops4j.pax.exam</groupId>
-            <artifactId>pax-exam-junit4</artifactId>
-            <version>${exam.version}</version>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>config-netconf-connector</artifactId>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>logback-config</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>config-persister-impl</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>config-persister-file-xml-adapter</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>netconf-impl</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>netconf-client</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.ops4j.pax.exam</groupId>
-            <artifactId>pax-exam</artifactId>
-            <version>${exam.version}</version>
-            <!-- Compile scope here is intentional, it is used in TestHelper
-                class which could be downloaded via nexus and reused in other integration
-                tests. -->
-            <scope>compile</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.ops4j.pax.exam</groupId>
-            <artifactId>pax-exam-link-mvn</artifactId>
-            <version>${exam.version}</version>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
-            <groupId>equinoxSDK381</groupId>
-            <artifactId>org.eclipse.osgi</artifactId>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.slf4j</groupId>
-            <artifactId>log4j-over-slf4j</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>ch.qos.logback</groupId>
-            <artifactId>logback-core</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>ch.qos.logback</groupId>
-            <artifactId>logback-classic</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>org.mockito</groupId>
-            <artifactId>mockito-all</artifactId>
-            <scope>test</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller.model</groupId>
-            <artifactId>model-flow-service</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller</groupId>
-            <artifactId>config-manager</artifactId>
-            <exclusions>
-                <exclusion>
-                    <artifactId>commons-io</artifactId>
-                    <groupId>commons-io</groupId>
-                </exclusion>
-            </exclusions>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.controller.model</groupId>
-            <artifactId>model-flow-management</artifactId>
-            <scope>provided</scope>
-        </dependency>
-        <dependency>
-            <groupId>org.opendaylight.yangtools.thirdparty</groupId>
-            <artifactId>antlr4-runtime-osgi-nohead</artifactId>
-        </dependency>
-    </dependencies>
-</project>
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-it/src/test/java/org/opendaylight/controller/sample/zeromq/test/it/RouterTest.java b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-it/src/test/java/org/opendaylight/controller/sample/zeromq/test/it/RouterTest.java
deleted file mode 100644 (file)
index e02e290..0000000
+++ /dev/null
@@ -1,452 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.sample.zeromq.test.it;
-
-import junit.framework.Assert;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-
-import org.opendaylight.controller.sal.connector.remoterpc.RemoteRpcClient;
-
-import org.opendaylight.controller.sal.connector.remoterpc.dto.Message;
-import org.opendaylight.controller.sal.core.api.Broker;
-import org.opendaylight.controller.sample.zeromq.consumer.ExampleConsumer;
-import org.opendaylight.controller.sample.zeromq.provider.ExampleProvider;
-
-import org.opendaylight.controller.test.sal.binding.it.TestHelper;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.RpcError;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.ops4j.pax.exam.Configuration;
-import org.ops4j.pax.exam.Option;
-import org.ops4j.pax.exam.junit.PaxExam;
-import org.ops4j.pax.exam.util.Filter;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleException;
-import org.osgi.framework.ServiceReference;
-
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.zeromq.ZMQ;
-
-import javax.inject.Inject;
-
-import java.io.IOException;
-import java.net.URI;
-
-import static org.opendaylight.controller.test.sal.binding.it.TestHelper.baseModelBundles;
-import static org.opendaylight.controller.test.sal.binding.it.TestHelper.bindingAwareSalBundles;
-
-//import static org.ops4j.pax.exam.CoreOptions.*;
-
-@RunWith(PaxExam.class)
-public class RouterTest {
-
-  private Logger _logger = LoggerFactory.getLogger(RouterTest.class);
-
-  public static final String ODL = "org.opendaylight.controller";
-  public static final String YANG = "org.opendaylight.yangtools";
-  public static final String SAMPLE = "org.opendaylight.controller.tests";
-  private final URI namespace = URI.create("http://cisco.com/example");
-  private final QName QNAME = new QName(namespace, "heartbeat");
-
-
-  @Inject
-  org.osgi.framework.BundleContext ctx;
-
-  @Inject
-  @Filter(timeout=60*1000)
-  Broker broker;
-
-  private ZMQ.Context zmqCtx = ZMQ.context(1);
-  //private Server router;
-  //private ExampleProvider provider;
-
-  //@Test
-  public void testInvokeRpc() throws Exception{
-    //Thread.sleep(1000);
-    //Send announcement
-    ServiceReference providerRef = ctx.getServiceReference(ExampleProvider.class);
-    Assert.assertNotNull(providerRef);
-
-    ExampleProvider provider = (ExampleProvider)ctx.getService(providerRef);
-    Assert.assertNotNull(provider);
-
-    ServiceReference consumerRef = ctx.getServiceReference(ExampleConsumer.class);
-    Assert.assertNotNull(consumerRef);
-    ExampleConsumer consumer = (ExampleConsumer)ctx.getService(consumerRef);
-    Assert.assertNotNull(consumer);
-
-
-    _logger.debug("Provider sends announcement [{}]", "heartbeat");
-    provider.announce(QNAME);
-    ServiceReference routerRef = ctx.getServiceReference(RemoteRpcClient.class);
-    RemoteRpcClient router = (RemoteRpcClient) ctx.getService(routerRef);
-    _logger.debug("Found router[{}]", router);
-    _logger.debug("Invoking RPC [{}]", QNAME);
-    for (int i = 0; i < 3; i++) {
-      RpcResult<CompositeNode> result = router.invokeRpc(QNAME, consumer.getValidCompositeNodeWithOneSimpleChild());
-      _logger.debug("{}-> Result is: Successful:[{}], Payload:[{}], Errors: [{}]", i, result.isSuccessful(), result.getResult(), result.getErrors());
-      Assert.assertNotNull(result);
-    }
-  }
-
-  @Test
-  public void testInvokeRpcWithValidSimpleNode() throws Exception{
-    //Thread.sleep(1500);
-
-    ServiceReference providerRef = ctx.getServiceReference(ExampleProvider.class);
-    Assert.assertNotNull(providerRef);
-    ExampleProvider provider = (ExampleProvider)ctx.getService(providerRef);
-    Assert.assertNotNull(provider);
-    ServiceReference consumerRef = ctx.getServiceReference(ExampleConsumer.class);
-    Assert.assertNotNull(consumerRef);
-    ExampleConsumer consumer = (ExampleConsumer)ctx.getService(consumerRef);
-    Assert.assertNotNull(consumer);
-
-    // Provider sends announcement
-    _logger.debug("Provider sends announcement [{}]", "heartbeat");
-    provider.announce(QNAME);
-    // Consumer invokes RPC
-    _logger.debug("Invoking RPC [{}]", QNAME);
-    CompositeNode input = consumer.getValidCompositeNodeWithOneSimpleChild();
-    for (int i = 0; i < 3; i++) {
-      RpcResult<CompositeNode> result = consumer.invokeRpc(QNAME, input);
-      Assert.assertNotNull(result);
-      _logger.debug("{}-> Result is: Successful:[{}], Payload:[{}], Errors: [{}]", i, result.isSuccessful(), result.getResult(), result.getErrors());
-      Assert.assertTrue(result.isSuccessful());
-      Assert.assertNotNull(result.getResult());
-      Assert.assertEquals(0, result.getErrors().size());
-      Assert.assertEquals(input.getChildren().size()+1, result.getResult().getChildren().size());
-    }
-  }
-
-  @Test
-  public void testInvokeRpcWithValidSimpleNodes() throws Exception{
-    //Thread.sleep(1500);
-
-    ServiceReference providerRef = ctx.getServiceReference(ExampleProvider.class);
-    Assert.assertNotNull(providerRef);
-    ExampleProvider provider = (ExampleProvider)ctx.getService(providerRef);
-    Assert.assertNotNull(provider);
-    ServiceReference consumerRef = ctx.getServiceReference(ExampleConsumer.class);
-    Assert.assertNotNull(consumerRef);
-    ExampleConsumer consumer = (ExampleConsumer)ctx.getService(consumerRef);
-    Assert.assertNotNull(consumer);
-
-    // Provider sends announcement
-    _logger.debug("Provider sends announcement [{}]", "heartbeat");
-    provider.announce(QNAME);
-    // Consumer invokes RPC
-    _logger.debug("Invoking RPC [{}]", QNAME);
-    CompositeNode input = consumer.getValidCompositeNodeWithFourSimpleChildren();
-    for (int i = 0; i < 3; i++) {
-      RpcResult<CompositeNode> result = consumer.invokeRpc(QNAME, input);
-      Assert.assertNotNull(result);
-      _logger.debug("{}-> Result is: Successful:[{}], Payload:[{}], Errors: [{}]", i, result.isSuccessful(), result.getResult(), result.getErrors());
-      Assert.assertTrue(result.isSuccessful());
-      Assert.assertNotNull(result.getResult());
-      Assert.assertEquals(0, result.getErrors().size());
-      Assert.assertEquals(input.getChildren().size()+1, result.getResult().getChildren().size());
-    }
-  }
-
-  @Test
-  public void testInvokeRpcWithValidCompositeNode() throws Exception{
-    //Thread.sleep(1500);
-
-    ServiceReference providerRef = ctx.getServiceReference(ExampleProvider.class);
-    Assert.assertNotNull(providerRef);
-    ExampleProvider provider = (ExampleProvider)ctx.getService(providerRef);
-    Assert.assertNotNull(provider);
-    ServiceReference consumerRef = ctx.getServiceReference(ExampleConsumer.class);
-    Assert.assertNotNull(consumerRef);
-    ExampleConsumer consumer = (ExampleConsumer)ctx.getService(consumerRef);
-    Assert.assertNotNull(consumer);
-
-    // Provider sends announcement
-    _logger.debug("Provider sends announcement [{}]", "heartbeat");
-    provider.announce(QNAME);
-    // Consumer invokes RPC
-    _logger.debug("Invoking RPC [{}]", QNAME);
-    CompositeNode input = consumer.getValidCompositeNodeWithTwoCompositeChildren();
-    for (int i = 0; i < 3; i++) {
-      RpcResult<CompositeNode> result = consumer.invokeRpc(QNAME, input);
-      Assert.assertNotNull(result);
-      _logger.debug("{}-> Result is: Successful:[{}], Payload:[{}], Errors: [{}]", i, result.isSuccessful(), result.getResult(), result.getErrors());
-      Assert.assertTrue(result.isSuccessful());
-      Assert.assertNotNull(result.getResult());
-      Assert.assertEquals(0, result.getErrors().size());
-      Assert.assertEquals(input.getChildren().size()+1, result.getResult().getChildren().size());
-    }
-  }
-
-  @Test
-  public void testInvokeRpcWithNullInput() throws Exception{
-    //Thread.sleep(1500);
-
-    ServiceReference providerRef = ctx.getServiceReference(ExampleProvider.class);
-    Assert.assertNotNull(providerRef);
-    ExampleProvider provider = (ExampleProvider)ctx.getService(providerRef);
-    Assert.assertNotNull(provider);
-    ServiceReference consumerRef = ctx.getServiceReference(ExampleConsumer.class);
-    Assert.assertNotNull(consumerRef);
-    ExampleConsumer consumer = (ExampleConsumer)ctx.getService(consumerRef);
-    Assert.assertNotNull(consumer);
-
-    // Provider sends announcement
-    _logger.debug("Provider sends announcement [{}]", QNAME.getLocalName());
-    provider.announce(QNAME);
-    // Consumer invokes RPC
-    _logger.debug("Invoking RPC [{}]", QNAME);
-    for (int i = 0; i < 3; i++) {
-      RpcResult<CompositeNode> result = consumer.invokeRpc(QNAME, null);
-      Assert.assertNotNull(result);
-      _logger.debug("{}-> Result is: Successful:[{}], Payload:[{}], Errors: [{}]", i, result.isSuccessful(), result.getResult(), result.getErrors());
-      Assert.assertFalse(result.isSuccessful());
-      Assert.assertNull(result.getResult());
-      Assert.assertEquals(1, result.getErrors().size());
-      Assert.assertEquals(RpcError.ErrorSeverity.WARNING, ((RpcError)result.getErrors().toArray()[0]).getSeverity());
-    }
-  }
-
-  @Test
-  public void testInvokeRpcWithInvalidSimpleNode() throws Exception{
-    //Thread.sleep(1500);
-
-    ServiceReference providerRef = ctx.getServiceReference(ExampleProvider.class);
-    Assert.assertNotNull(providerRef);
-    ExampleProvider provider = (ExampleProvider)ctx.getService(providerRef);
-    Assert.assertNotNull(provider);
-    ServiceReference consumerRef = ctx.getServiceReference(ExampleConsumer.class);
-    Assert.assertNotNull(consumerRef);
-    ExampleConsumer consumer = (ExampleConsumer)ctx.getService(consumerRef);
-    Assert.assertNotNull(consumer);
-
-    // Provider sends announcement
-    _logger.debug("Provider sends announcement [{}]", QNAME.getLocalName());
-    provider.announce(QNAME);
-    // Consumer invokes RPC
-    _logger.debug("Invoking RPC [{}]", QNAME);
-    CompositeNode input = consumer.getInvalidCompositeNodeSimpleChild();
-    for (int i = 0; i < 3; i++) {
-      RpcResult<CompositeNode> result = consumer.invokeRpc(QNAME, input);
-      Assert.assertNotNull(result);
-      _logger.debug("{}-> Result is: Successful:[{}], Payload:[{}], Errors: [{}]", i, result.isSuccessful(), result.getResult(), result.getErrors());
-      Assert.assertFalse(result.isSuccessful());
-      Assert.assertNull(result.getResult());
-      Assert.assertEquals(1, result.getErrors().size());
-      Assert.assertEquals(RpcError.ErrorSeverity.ERROR, ((RpcError)result.getErrors().toArray()[0]).getSeverity());
-    }
-  }
-
-  @Test
-  public void testInvokeRpcWithInvalidCompositeNode() throws Exception{
-    //Thread.sleep(1500);
-
-    ServiceReference providerRef = ctx.getServiceReference(ExampleProvider.class);
-    Assert.assertNotNull(providerRef);
-    ExampleProvider provider = (ExampleProvider)ctx.getService(providerRef);
-    Assert.assertNotNull(provider);
-    ServiceReference consumerRef = ctx.getServiceReference(ExampleConsumer.class);
-    Assert.assertNotNull(consumerRef);
-    ExampleConsumer consumer = (ExampleConsumer)ctx.getService(consumerRef);
-    Assert.assertNotNull(consumer);
-
-    // Provider sends announcement
-    _logger.debug("Provider sends announcement [{}]", QNAME.getLocalName());
-    provider.announce(QNAME);
-    // Consumer invokes RPC
-    _logger.debug("Invoking RPC [{}]", QNAME);
-    CompositeNode input = consumer.getInvalidCompositeNodeCompositeChild();
-    for (int i = 0; i < 3; i++) {
-      RpcResult<CompositeNode> result = consumer.invokeRpc(QNAME, input);
-      Assert.assertNotNull(result);
-      _logger.debug("{}-> Result is: Successful:[{}], Payload:[{}], Errors: [{}]", i, result.isSuccessful(), result.getResult(), result.getErrors());
-      Assert.assertFalse(result.isSuccessful());
-      Assert.assertNull(result.getResult());
-      Assert.assertEquals(1, result.getErrors().size());
-      Assert.assertEquals(RpcError.ErrorSeverity.ERROR, ((RpcError)result.getErrors().toArray()[0]).getSeverity());
-    }
-  }
-
-  //@Test
-  // This method is UNTESTED -- need to get around the bundling issues before I know if this even work
-//  public void testInvokeRpcWithValidCompositeNode() throws Exception{
-//    Thread.sleep(10000);
-//    //Send announcement
-//    ServiceReference providerRef = ctx.getServiceReference(ExampleProvider.class);
-//    Assert.assertNotNull(providerRef);
-//
-//    ExampleProvider provider = (ExampleProvider)ctx.getService(providerRef);
-//    Assert.assertNotNull(provider);
-//
-//    ServiceReference consumerRef = ctx.getServiceReference(ExampleConsumer.class);
-//    Assert.assertNotNull(consumerRef);
-//
-//    ExampleConsumer consumer = (ExampleConsumer)ctx.getService(consumerRef);
-//    Assert.assertNotNull(consumer);
-//
-//    _logger.debug("Provider sends announcement [{}]", "heartbeat");
-//    provider.announce(QNAME);
-//    ServiceReference routerRef = ctx.getServiceReference(Client.class);
-//    Client router = (Client) ctx.getService(routerRef);
-//    _logger.debug("Found router[{}]", router);
-//    _logger.debug("Invoking RPC [{}]", QNAME);
-//    for (int i = 0; i < 3; i++) {
-//      RpcResult<CompositeNode> result = router.getInstance().invokeRpc(QNAME, consumer.getValidCompositeNodeWithOneSimpleChild());
-//      _logger.debug("{}-> Result is: Successful:[{}], Payload:[{}], Errors: [{}]", i, result.isSuccessful(), result.getResult(), result.getErrors());
-//      Assert.assertNotNull(result);
-//    }
-//  }
-
-  private Message send(Message msg) throws IOException {
-    ZMQ.Socket reqSocket = zmqCtx.socket(ZMQ.REQ);
-    reqSocket.connect("tcp://localhost:5555");
-    reqSocket.send(Message.serialize(msg));
-    Message response = parseMessage(reqSocket);
-
-    return response;
-  }
-
-  /**
-   * @param socket
-   * @return
-   */
-  private Message parseMessage(ZMQ.Socket socket) {
-
-    Message msg = null;
-    try {
-      byte[] bytes = socket.recv();
-      _logger.debug("Received bytes:[{}]", bytes.length);
-      msg = (Message) Message.deserialize(bytes);
-    } catch (Throwable t) {
-      t.printStackTrace();
-    }
-    return msg;
-  }
-
-
-  private void printState(){
-    Bundle[] b = ctx.getBundles();
-    _logger.debug("\n\nNumber of bundles [{}]\n\n]", b.length);
-    for (int i=0;i<b.length;i++){
-      _logger.debug("Bundle States {}-{} ",b[i].getSymbolicName(), stateToString(b[i].getState()));
-
-      if ( Bundle.INSTALLED == b[i].getState() || (Bundle.RESOLVED == b[i].getState())){
-        try {
-          b[i].start();
-        } catch (BundleException e) {
-          e.printStackTrace();
-        }
-      }
-    }
-  }
-
-  private String stateToString(int state) {
-    switch (state) {
-      case Bundle.ACTIVE:
-        return "ACTIVE";
-      case Bundle.INSTALLED:
-        return "INSTALLED";
-      case Bundle.RESOLVED:
-        return "RESOLVED";
-      case Bundle.UNINSTALLED:
-        return "UNINSTALLED";
-      default:
-        return "Not CONVERTED";
-    }
-  }
-
-  @Configuration
-  public Option[] config() {
-    return options(systemProperty("osgi.console").value("2401"),
-            systemProperty("rpc.port").value("5555"),
-            mavenBundle("org.slf4j", "slf4j-api").versionAsInProject(), //
-            mavenBundle("org.slf4j", "log4j-over-slf4j").versionAsInProject(), //
-            mavenBundle("ch.qos.logback", "logback-core").versionAsInProject(), //
-            mavenBundle("ch.qos.logback", "logback-classic").versionAsInProject(), //
-
-            //mavenBundle(ODL, "sal-binding-broker-impl").versionAsInProject().update(), //
-            mavenBundle(ODL, "sal-common").versionAsInProject(), //
-            mavenBundle(ODL, "sal-common-api").versionAsInProject(),//
-            mavenBundle(ODL, "sal-common-impl").versionAsInProject(), //
-            mavenBundle(ODL, "sal-common-util").versionAsInProject(), //
-            mavenBundle(ODL, "sal-core-api").versionAsInProject().update(), //
-            mavenBundle(ODL, "sal-broker-impl").versionAsInProject(), //
-            mavenBundle(ODL, "sal-core-spi").versionAsInProject().update(), //
-            mavenBundle(ODL, "sal-connector-api").versionAsInProject(), //
-
-
-            baseModelBundles(),
-            bindingAwareSalBundles(),
-            TestHelper.bindingIndependentSalBundles(),
-            TestHelper.configMinumumBundles(),
-            TestHelper.mdSalCoreBundles(),
-
-            //Added the consumer
-            mavenBundle(SAMPLE, "sal-remoterpc-connector-test-consumer").versionAsInProject(), //
-            //**** These two bundles below are NOT successfully resolved -- some of their dependencies must be missing
-            //**** This causes the "Message" error to occur, the class cannot be found
-            mavenBundle(SAMPLE, "sal-remoterpc-connector-test-provider").versionAsInProject(), //
-            mavenBundle(ODL, "sal-remoterpc-connector").versionAsInProject(), //
-
-            mavenBundle(ODL, "zeromq-routingtable.implementation").versionAsInProject(),
-            mavenBundle(YANG, "concepts").versionAsInProject(),
-            mavenBundle(YANG, "yang-binding").versionAsInProject(), //
-            mavenBundle(YANG, "yang-common").versionAsInProject(), //
-            mavenBundle(YANG, "yang-data-api").versionAsInProject(), //
-            mavenBundle(YANG, "yang-data-impl").versionAsInProject(), //
-            mavenBundle(YANG, "yang-model-api").versionAsInProject(), //
-            mavenBundle(YANG, "yang-parser-api").versionAsInProject(), //
-            mavenBundle(YANG, "yang-parser-impl").versionAsInProject(), //
-            mavenBundle(YANG, "yang-model-util").versionAsInProject(), //
-            mavenBundle(YANG + ".thirdparty", "xtend-lib-osgi").versionAsInProject(), //
-            mavenBundle(YANG + ".thirdparty", "antlr4-runtime-osgi-nohead").versionAsInProject(), //
-            mavenBundle("com.google.guava", "guava").versionAsInProject(), //
-            mavenBundle("org.zeromq", "jeromq").versionAsInProject(),
-            mavenBundle("org.codehaus.jackson", "jackson-mapper-asl").versionAsInProject(),
-            mavenBundle("org.codehaus.jackson", "jackson-core-asl").versionAsInProject(),
-            //routingtable dependencies
-            systemPackages("sun.reflect", "sun.reflect.misc", "sun.misc"),
-            // List framework bundles
-            mavenBundle("equinoxSDK381", "org.eclipse.equinox.console").versionAsInProject(),
-            mavenBundle("equinoxSDK381", "org.eclipse.equinox.util").versionAsInProject(),
-            mavenBundle("equinoxSDK381", "org.eclipse.osgi.services").versionAsInProject(),
-            mavenBundle("equinoxSDK381", "org.eclipse.equinox.ds").versionAsInProject(),
-            mavenBundle("equinoxSDK381", "org.apache.felix.gogo.command").versionAsInProject(),
-            mavenBundle("equinoxSDK381", "org.apache.felix.gogo.runtime").versionAsInProject(),
-            mavenBundle("equinoxSDK381", "org.apache.felix.gogo.shell").versionAsInProject(),
-            // List logger bundles
-
-            mavenBundle("org.opendaylight.controller", "clustering.services")
-                    .versionAsInProject(),
-            mavenBundle("org.opendaylight.controller", "clustering.stub")
-                    .versionAsInProject(),
-
-
-            // List all the bundles on which the test case depends
-            mavenBundle("org.opendaylight.controller", "sal")
-                    .versionAsInProject(),
-            mavenBundle("org.opendaylight.controller", "sal.implementation")
-                    .versionAsInProject(),
-            mavenBundle("org.jboss.spec.javax.transaction",
-                    "jboss-transaction-api_1.1_spec").versionAsInProject(),
-            mavenBundle("org.apache.commons", "commons-lang3")
-                    .versionAsInProject(),
-            mavenBundle("org.apache.felix",
-                    "org.apache.felix.dependencymanager")
-                    .versionAsInProject(),
-
-            junitBundles()
-    );
-  }
-
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-it/src/test/resources/controller.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-it/src/test/resources/controller.xml
deleted file mode 100644 (file)
index c8e3b83..0000000
+++ /dev/null
@@ -1,197 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<persisted-snapshots>
-    <snapshots>
-        <snapshot>
-            <required-capabilities>
-                <capability>urn:opendaylight:params:xml:ns:yang:controller:config?module=config&amp;revision=2013-04-05
-                </capability>
-                <capability>
-                    urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl?module=opendaylight-sal-binding-broker-impl&amp;revision=2013-10-28
-                </capability>
-                <capability>
-                    urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding?module=opendaylight-md-sal-binding&amp;revision=2013-10-28
-                </capability>
-                <capability>
-                    urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl?module=opendaylight-sal-dom-broker-impl&amp;revision=2013-10-28
-                </capability>
-                <capability>urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom?module=opendaylight-md-sal-dom&amp;revision=2013-10-28</capability>
-                <capability>
-                    urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote:rpc?module=odl-sal-dom-rpc-remote-cfg&amp;revision=2013-10-28
-                </capability>
-            </required-capabilities>
-            <configuration>
-
-                <data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
-                    <modules xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
-                        <module>
-                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl">
-                                prefix:schema-service-singleton
-                            </type>
-                            <name>yang-schema-service</name>
-                        </module>
-                        <module>
-                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl">
-                                prefix:hash-map-data-store
-                            </type>
-                            <name>hash-map-data-store</name>
-                        </module>
-                        <module>
-                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl">
-                                prefix:dom-broker-impl
-                            </type>
-                            <name>dom-broker</name>
-                            <data-store xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:impl">
-                                <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">
-                                    dom:dom-data-store
-                                </type>
-                                <name>ref_hash-map-data-store</name>
-                            </data-store>
-                        </module>
-                        <module>
-                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
-                                prefix:binding-broker-impl
-                            </type>
-                            <name>binding-broker-impl</name>
-                            <notification-service
-                                    xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
-                                <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">
-                                    binding:binding-notification-service
-                                </type>
-                                <name>ref_binding-notification-broker</name>
-                            </notification-service>
-                            <data-broker xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
-                                <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">
-                                    binding:binding-data-broker
-                                </type>
-                                <name>ref_binding-data-broker</name>
-                            </data-broker>
-                        </module>
-                        <module>
-                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
-                                prefix:runtime-generated-mapping
-                            </type>
-                            <name>runtime-mapping-singleton</name>
-                        </module>
-                        <module>
-                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
-                                prefix:binding-notification-broker
-                            </type>
-                            <name>binding-notification-broker</name>
-                        </module>
-                        <module>
-                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
-                                prefix:binding-data-broker
-                            </type>
-                            <name>binding-data-broker</name>
-                            <dom-broker xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
-                                <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">
-                                    dom:dom-broker-osgi-registry
-                                </type>
-                                <name>ref_dom-broker</name>
-                            </dom-broker>
-                            <mapping-service xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
-                                <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
-                                    binding:binding-dom-mapping-service
-                                </type>
-                                <name>ref_runtime-mapping-singleton</name>
-                            </mapping-service>
-                        </module>
-                        <module>
-                            <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote:rpc">
-                                prefix:remote-zeromq-rpc-server
-                            </type>
-                            <name>remoter</name>
-                            <port xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote:rpc">5666</port>
-                            <dom-broker xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote:rpc">
-                                <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">
-                                    prefix:dom-broker-osgi-registry
-                                </type>
-                                <name>ref_dom-broker</name>
-                            </dom-broker>
-                        </module>
-                    </modules>
-
-                    <services xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
-                        <service>
-                            <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">
-                                dom:schema-service
-                            </type>
-                            <instance>
-                                <name>ref_yang-schema-service</name>
-                                <provider>
-                                    /config/modules/module[name='schema-service-singleton']/instance[name='yang-schema-service']
-                                </provider>
-                            </instance>
-                        </service>
-                        <service>
-                            <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">
-                                binding:binding-notification-service
-                            </type>
-                            <instance>
-                                <name>ref_binding-notification-broker</name>
-                                <provider>
-                                    /config/modules/module[name='binding-notification-broker']/instance[name='binding-notification-broker']
-                                </provider>
-                            </instance>
-                        </service>
-                        <service>
-                            <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">
-                                dom:dom-data-store
-                            </type>
-                            <instance>
-                                <name>ref_hash-map-data-store</name>
-                                <provider>
-                                    /config/modules/module[name='hash-map-data-store']/instance[name='hash-map-data-store']
-                                </provider>
-                            </instance>
-                        </service>
-                        <service>
-                            <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">
-                                binding:binding-broker-osgi-registry
-                            </type>
-                            <instance>
-                                <name>ref_binding-broker-impl</name>
-                                <provider>
-                                    /config/modules/module[name='binding-broker-impl']/instance[name='binding-broker-impl']
-                                </provider>
-                            </instance>
-                        </service>
-                        <service>
-                            <type xmlns:binding-impl="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding:impl">
-                                binding-impl:binding-dom-mapping-service
-                            </type>
-                            <instance>
-                                <name>ref_runtime-mapping-singleton</name>
-                                <provider>
-                                    /config/modules/module[name='runtime-generated-mapping']/instance[name='runtime-mapping-singleton']
-                                </provider>
-                            </instance>
-                        </service>
-                        <service>
-                            <type xmlns:dom="urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom">
-                                dom:dom-broker-osgi-registry
-                            </type>
-                            <instance>
-                                <name>ref_dom-broker</name>
-                                <provider>/config/modules/module[name='dom-broker-impl']/instance[name='dom-broker']
-                                </provider>
-                            </instance>
-                        </service>
-                        <service>
-                            <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">
-                                binding:binding-data-broker
-                            </type>
-                            <instance>
-                                <name>ref_binding-data-broker</name>
-                                <provider>
-                                    /config/modules/module[name='binding-data-broker']/instance[name='binding-data-broker']
-                                </provider>
-                            </instance>
-                        </service>
-                    </services>
-                </data>
-
-            </configuration>
-        </snapshot>
-    </snapshots>
-</persisted-snapshots>
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-it/src/test/resources/logback.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-it/src/test/resources/logback.xml
deleted file mode 100644 (file)
index 1d17796..0000000
+++ /dev/null
@@ -1,16 +0,0 @@
-<configuration scan="true">
-
-  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
-    <encoder>
-      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
-      </pattern>
-    </encoder>
-  </appender>
-
-
-  <logger name="org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort" level="ERROR"/>
-
-  <root level="info">
-    <appender-ref ref="STDOUT" />
-  </root>
-</configuration>
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-nb/pom.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-nb/pom.xml
deleted file mode 100644 (file)
index b681db2..0000000
+++ /dev/null
@@ -1,101 +0,0 @@
-<?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>
-    <artifactId>sal-remoterpc-connector-test-parent</artifactId>
-    <groupId>org.opendaylight.controller.tests</groupId>
-    <version>1.1-SNAPSHOT</version>
-  </parent>
-
-  <artifactId>sal-remoterpc-connector-test-nb</artifactId>
-  <packaging>bundle</packaging>
-
-  <build>
-    <plugins>
-      <plugin>
-        <groupId>org.apache.felix</groupId>
-        <artifactId>maven-bundle-plugin</artifactId>
-        <version>${bundle.plugin.version}</version>
-        <extensions>true</extensions>
-        <configuration>
-          <instructions>
-            <Export-Package>
-            </Export-Package>
-            <Import-Package>
-              com.sun.jersey.spi.container.servlet,
-              !org.codehaus.jackson.annotate,
-              javax.ws.rs,
-              javax.ws.rs.core,
-              javax.xml.bind,
-              javax.xml.bind.annotation,
-              org.slf4j,
-              org.apache.catalina.filters,
-              !org.codehaus.jackson.jaxrs,
-              org.opendaylight.controller.sample.zeromq.provider,
-              org.opendaylight.controller.sample.zeromq.consumer,
-              org.opendaylight.controller.sal.utils,
-              org.opendaylight.yangtools.yang.common,
-              org.opendaylight.controller.sal.connector.api,
-              org.opendaylight.controller.sal.connector.remoterpc.api;version="[0.4,1)",
-              org.opendaylight.controller.sal.connector.remoterpc.impl;version="[0.4,1)",
-              org.opendaylight.controller.sal.connector.remoterpc.dto,
-              org.opendaylight.controller.sal.connector.remoterpc.util,
-              org.osgi.framework,
-              com.google.common.base,
-              org.opendaylight.yangtools.yang.data.api,
-              !org.codehaus.enunciate.jaxrs
-
-            </Import-Package>
-            <Web-ContextPath>/controller/nb/v2/zmqnb</Web-ContextPath>
-            <Jaxrs-Resources>,${classes;ANNOTATION;javax.ws.rs.Path}</Jaxrs-Resources>
-          </instructions>
-          <manifestLocation>${project.basedir}/src/main/resources/META-INF</manifestLocation>
-        </configuration>
-      </plugin>
-    </plugins>
-  </build>
-  <dependencies>
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>containermanager</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>commons.northbound</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>sal</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.controller.tests</groupId>
-      <artifactId>sal-remoterpc-connector-test-provider</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.controller.tests</groupId>
-      <artifactId>sal-remoterpc-connector-test-consumer</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>sal-remoterpc-connector</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>org.osgi</groupId>
-      <artifactId>org.osgi.core</artifactId>
-    </dependency>
-    <dependency>
-      <groupId>junit</groupId>
-      <artifactId>junit</artifactId>
-    </dependency>
-      <dependency>
-          <groupId>org.opendaylight.controller</groupId>
-          <artifactId>remoterpc-routingtable.implementation</artifactId>
-      </dependency>
-      <dependency>
-          <groupId>com.google.guava</groupId>
-          <artifactId>guava</artifactId>
-      </dependency>
-  </dependencies>
-
- </project>
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-nb/src/main/java/org/opendaylight/controller/tests/zmqrouter/rest/Router.java b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-nb/src/main/java/org/opendaylight/controller/tests/zmqrouter/rest/Router.java
deleted file mode 100644 (file)
index e97be52..0000000
+++ /dev/null
@@ -1,273 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.tests.zmqrouter.rest;
-
-import org.opendaylight.controller.sal.connector.api.RpcRouter;
-import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable;
-import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTableException;
-import org.opendaylight.controller.sal.connector.remoterpc.api.SystemException;
-import org.opendaylight.controller.sal.connector.remoterpc.impl.RoutingTableImpl;
-import org.opendaylight.controller.sal.connector.remoterpc.util.XmlUtils;
-import org.opendaylight.controller.sample.zeromq.consumer.ExampleConsumer;
-import org.opendaylight.controller.sample.zeromq.provider.ExampleProvider;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
-import org.osgi.framework.BundleContext;
-import org.osgi.framework.ServiceReference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.ws.rs.GET;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.MediaType;
-import java.io.Serializable;
-import java.net.URI;
-import java.util.Set;
-
-@Path("router")
-public class Router {
-  private Logger _logger = LoggerFactory.getLogger(Router.class);
-  private final URI namespace = URI.create("http://cisco.com/example");
-  private final QName QNAME = new QName(namespace, "heartbeat");
-
-
-  @GET
-  @Path("/hello")
-  @Produces(MediaType.TEXT_PLAIN)
-  public String hello() {
-    return "Hello";
-  }
-
-  @GET
-  @Path("/announce")
-  @Produces(MediaType.TEXT_PLAIN)
-  public String announce() {
-    _logger.info("Announce request received");
-
-    BundleContext ctx = getBundleContext();
-    ServiceReference providerRef = ctx.getServiceReference(ExampleProvider.class);
-    if (providerRef == null) {
-      _logger.debug("Could not get provider reference");
-      return "Could not get provider reference";
-    }
-
-    ExampleProvider provider = (ExampleProvider) ctx.getService(providerRef);
-    if (provider == null) {
-      _logger.info("Could not get provider service");
-      return "Could not get provider service";
-    }
-
-    provider.announce(QNAME);
-    return "Announcement sent ";
-
-  }
-
-  @GET
-  @Path("/rpc")
-  @Produces(MediaType.TEXT_PLAIN)
-  public String invokeRpc() throws Exception {
-    _logger.info("Invoking RPC");
-
-    ExampleConsumer consumer = getConsumer();
-    RpcResult<CompositeNode> result = consumer.invokeRpc(QNAME, consumer.getValidCompositeNodeWithOneSimpleChild());
-    _logger.info("Result [{}]", result.isSuccessful());
-
-    return stringify(result);
-  }
-
-  @GET
-  @Path("/rpc-success")
-  @Produces(MediaType.TEXT_PLAIN)
-  public String invokeRpcSuccess() throws Exception {
-    ExampleConsumer consumer = getConsumer();
-    RpcResult<CompositeNode> result = consumer.invokeRpc(QNAME, consumer.getValidCompositeNodeWithFourSimpleChildren()); //TODO: Change this
-    _logger.info("Result [{}]", result.isSuccessful());
-
-    return stringify(result);
-  }
-
-  @GET
-  @Path("/rpc-failure")
-  @Produces(MediaType.TEXT_PLAIN)
-  public String invokeRpcFailure() throws Exception {
-    ExampleConsumer consumer = getConsumer();
-    //RpcResult<CompositeNode> result = consumer.invokeRpc(QNAME, consumer.getInvalidCompositeNodeCompositeChild()); //TODO: Change this
-    RpcResult<CompositeNode> result = consumer.invokeRpc(QNAME, null); //TODO: Change this
-    _logger.info("Result [{}]", result.isSuccessful());
-
-    return stringify(result);
-  }
-
-  @GET
-  @Path("/routingtable")
-  @Produces(MediaType.TEXT_PLAIN)
-  public String invokeRoutingTable() {
-    _logger.info("Invoking adding an entry in routing table");
-
-    BundleContext ctx = getBundleContext();
-    ServiceReference routingTableServiceReference = ctx.getServiceReference(RoutingTable.class);
-    if (routingTableServiceReference == null) {
-      _logger.debug("Could not get routing table impl reference");
-      return "Could not get routingtable referen ";
-    }
-    RoutingTableImpl routingTable = (RoutingTableImpl) ctx.getService(routingTableServiceReference);
-    if (routingTable == null) {
-      _logger.info("Could not get routing table service");
-      return "Could not get routing table service";
-    }
-
-
-    RoutingIdentifierImpl rii = new RoutingIdentifierImpl();
-    try {
-      routingTable.addGlobalRoute(rii.toString(), "172.27.12.1:5000");
-    } catch (RoutingTableException e) {
-      _logger.error("error in adding routing identifier" + e.getMessage());
-
-    } catch (SystemException e) {
-      _logger.error("error in adding routing identifier" + e.getMessage());
-    }
-
-    String result = routingTable.dumpRoutingTableCache();
-
-
-
-
-    _logger.info("Result [{}] routes added for route" + rii + result);
-
-    return result;
-  }
-
-  @GET
-  @Path("/routingtabledelete")
-  @Produces(MediaType.TEXT_PLAIN)
-  public String invokeDeleteRoutingTable() {
-    _logger.info("Invoking adding an entry in routing table");
-
-    BundleContext ctx = getBundleContext();
-    ServiceReference routingTableServiceReference = ctx.getServiceReference(RoutingTable.class);
-    if (routingTableServiceReference == null) {
-      _logger.debug("Could not get routing table impl reference");
-      return "Could not get routingtable referen ";
-    }
-    RoutingTable routingTable = (RoutingTableImpl) ctx.getService(routingTableServiceReference);
-    if (routingTable == null) {
-      _logger.info("Could not get routing table service");
-      return "Could not get routing table service";
-    }
-
-
-    RoutingIdentifierImpl rii = new RoutingIdentifierImpl();
-    try {
-      routingTable.removeGlobalRoute(rii.toString());
-    } catch (RoutingTableException e) {
-      _logger.error("error in adding routing identifier" + e.getMessage());
-
-    } catch (SystemException e) {
-      _logger.error("error in adding routing identifier" + e.getMessage());
-    }
-
-    Set<String> routes = routingTable.getRoutes(rii.toString());
-
-    StringBuilder stringBuilder = new StringBuilder();
-    if (routes != null) {
-      for (String route : routes) {
-        stringBuilder.append(route);
-      }
-    } else {
-      stringBuilder.append(" successfully");
-    }
-
-    _logger.info("Result [{}] routes removed for route" + rii + stringBuilder.toString());
-
-    return stringBuilder.toString();
-  }
-
-  private String stringify(RpcResult<CompositeNode> result) {
-    CompositeNode node = result.getResult();
-    StringBuilder builder = new StringBuilder("result:").append(XmlUtils.compositeNodeToXml(node)).append("\n")
-        .append("error:").append(result.getErrors()).append("\n");
-
-    return builder.toString();
-  }
-
-  private BundleContext getBundleContext() {
-    ClassLoader tlcl = Thread.currentThread().getContextClassLoader();
-    Bundle bundle = null;
-
-    if (tlcl instanceof BundleReference) {
-      bundle = ((BundleReference) tlcl).getBundle();
-    } else {
-      _logger.info("Unable to determine the bundle context based on " +
-          "thread context classloader.");
-      bundle = FrameworkUtil.getBundle(this.getClass());
-    }
-    return (bundle == null ? null : bundle.getBundleContext());
-  }
-
-  private ExampleConsumer getConsumer() {
-    BundleContext ctx = getBundleContext();
-    ServiceReference consumerRef = ctx.getServiceReference(ExampleConsumer.class);
-    if (consumerRef == null) {
-      _logger.debug("Could not get consumer reference");
-      throw new NullPointerException("Could not get consumer reference");
-    }
-    ExampleConsumer consumer = (ExampleConsumer) ctx.getService(consumerRef);
-    if (consumer == null) {
-      _logger.info("Could not get consumer service");
-      throw new NullPointerException("Could not get consumer service");
-    }
-    return consumer;
-  }
-
-  class RoutingIdentifierImpl implements RpcRouter.RouteIdentifier, Serializable {
-
-    private final URI namespace = URI.create("http://cisco.com/example");
-    private final QName QNAME = new QName(namespace, "global");
-    private final QName instance = new QName(URI.create("127.0.0.1"), "local");
-
-    @Override
-    public QName getContext() {
-      return QNAME;
-    }
-
-    @Override
-    public QName getType() {
-      return QNAME;
-    }
-
-    @Override
-    public org.opendaylight.yangtools.yang.data.api.InstanceIdentifier getRoute() {
-      return InstanceIdentifier.of(instance);
-    }
-
-      @Override
-      public boolean equals(Object o) {
-          if (this == o) return true;
-          if (o == null || getClass() != o.getClass()) return false;
-
-          RoutingIdentifierImpl that = (RoutingIdentifierImpl) o;
-
-          if (!QNAME.equals(that.QNAME)) return false;
-          if (!instance.equals(that.instance)) return false;
-          if (!namespace.equals(that.namespace)) return false;
-
-          return true;
-      }
-
-      @Override
-      public int hashCode() {
-          int result = namespace.hashCode();
-          result = 31 * result + QNAME.hashCode();
-          result = 31 * result + instance.hashCode();
-          return result;
-      }
-  }
-}
diff --git a/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-nb/src/main/resources/WEB-INF/web.xml b/opendaylight/md-sal/sal-remoterpc-connector/integrationtest/test-nb/src/main/resources/WEB-INF/web.xml
deleted file mode 100644 (file)
index 5bd2139..0000000
+++ /dev/null
@@ -1,58 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
-        version="3.0">
-  <servlet>
-    <servlet-name>JAXRSZmq</servlet-name>
-    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
-    <init-param>
-      <param-name>javax.ws.rs.Application</param-name>
-      <param-value>org.opendaylight.controller.northbound.commons.NorthboundApplication</param-value>
-    </init-param>
-    <load-on-startup>1</load-on-startup>
-  </servlet>
-
-  <servlet-mapping>
-    <servlet-name>JAXRSZmq</servlet-name>
-    <url-pattern>/*</url-pattern>
-  </servlet-mapping>
-
-
-
-        <security-constraint>
-          <web-resource-collection>
-            <web-resource-name>NB api</web-resource-name>
-            <url-pattern>/*</url-pattern>
-            <http-method>POST</http-method>
-            <http-method>GET</http-method>
-            <http-method>PUT</http-method>
-            <http-method>PATCH</http-method>
-            <http-method>DELETE</http-method>
-            <http-method>HEAD</http-method>
-          </web-resource-collection>
-          <auth-constraint>
-            <role-name>System-Admin</role-name>
-            <role-name>Network-Admin</role-name>
-            <role-name>Network-Operator</role-name>
-            <role-name>Container-User</role-name>
-          </auth-constraint>
-        </security-constraint>
-
-        <security-role>
-                <role-name>System-Admin</role-name>
-        </security-role>
-        <security-role>
-                <role-name>Network-Admin</role-name>
-        </security-role>
-        <security-role>
-                <role-name>Network-Operator</role-name>
-        </security-role>
-        <security-role>
-                <role-name>Container-User</role-name>
-        </security-role>
-
-        <login-config>
-                <auth-method>BASIC</auth-method>
-                <realm-name>opendaylight</realm-name>
-        </login-config>
-</web-app>
index 46f4a2366a29e444623a0dfe525f8914add2a82f..b760263967864947268a3cc34df07e0a309e581b 100644 (file)
       <groupId>org.apache.commons</groupId>
       <artifactId>commons-lang3</artifactId>
     </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>sal-common-util</artifactId>
+    </dependency>
     <dependency>
       <groupId>org.opendaylight.controller</groupId>
       <artifactId>sal-remote</artifactId>
       <artifactId>mockito-all</artifactId>
       <scope>test</scope>
     </dependency>
-    <dependency>
-      <groupId>org.opendaylight.controller</groupId>
-      <artifactId>sal-common-util</artifactId>
-      <scope>test</scope>
-    </dependency>
   </dependencies>
 
   <build>
index af763cce0d20e0b03a76a1321580dcd71571446c..51ac43be7c7e27c1a8d32ef12f675e910309f725 100644 (file)
@@ -47,26 +47,24 @@ public class Draft02 {
 
         String ERROR_LIST_SCHEMA_NODE = "error";
 
-        QName IETF_RESTCONF_QNAME = QName.create( Draft02.RestConfModule.NAMESPACE,
-                                                  Draft02.RestConfModule.REVISION,
-                                                  Draft02.RestConfModule.NAME );
+        QName IETF_RESTCONF_QNAME = QName.create(Draft02.RestConfModule.NAMESPACE, Draft02.RestConfModule.REVISION,
+                Draft02.RestConfModule.NAME);
 
-        QName ERRORS_CONTAINER_QNAME = QName.create( IETF_RESTCONF_QNAME, ERRORS_CONTAINER_SCHEMA_NODE );
+        QName ERRORS_CONTAINER_QNAME = QName.create(IETF_RESTCONF_QNAME, ERRORS_CONTAINER_SCHEMA_NODE);
 
-        QName ERROR_LIST_QNAME = QName.create( IETF_RESTCONF_QNAME, ERROR_LIST_SCHEMA_NODE );
+        QName ERROR_LIST_QNAME = QName.create(IETF_RESTCONF_QNAME, ERROR_LIST_SCHEMA_NODE);
 
-        QName ERROR_TYPE_QNAME = QName.create( IETF_RESTCONF_QNAME, "error-type" );
+        QName ERROR_TYPE_QNAME = QName.create(IETF_RESTCONF_QNAME, "error-type");
 
-        QName ERROR_TAG_QNAME = QName.create( IETF_RESTCONF_QNAME, "error-tag" );
+        QName ERROR_TAG_QNAME = QName.create(IETF_RESTCONF_QNAME, "error-tag");
 
-        QName ERROR_APP_TAG_QNAME = QName.create( IETF_RESTCONF_QNAME, "error-app-tag" );
+        QName ERROR_APP_TAG_QNAME = QName.create(IETF_RESTCONF_QNAME, "error-app-tag");
 
-        QName ERROR_MESSAGE_QNAME = QName.create( IETF_RESTCONF_QNAME, "error-message" );
+        QName ERROR_MESSAGE_QNAME = QName.create(IETF_RESTCONF_QNAME, "error-message");
 
-        QName ERROR_INFO_QNAME = QName.create( IETF_RESTCONF_QNAME, "error-info" );
+        QName ERROR_INFO_QNAME = QName.create(IETF_RESTCONF_QNAME, "error-info");
     }
 
-
     public static interface Paths {
 
     }
index 056be72d4e057b249a17c0286e87b9b0ebe19e72..a6c4ea5ab8d7877930983ed782d4cbc318def278 100644 (file)
@@ -10,42 +10,38 @@ package org.opendaylight.controller.sal.rest.api;
 import javax.ws.rs.Consumes;
 import javax.ws.rs.DELETE;
 import javax.ws.rs.DefaultValue;
+import javax.ws.rs.Encoded;
 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.Encoded;
 import javax.ws.rs.core.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.UriInfo;
-
 import org.opendaylight.controller.sal.restconf.impl.StructuredData;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 
 /**
- *   The URI hierarchy for the RESTCONF resources consists of an entry
- *   point container, 4 top-level resources, and 1 field.
- *   <ul>
- *    <li><b>/restconf</b> - {@link #getRoot()}
- *     <ul>
- *      <li><b>/config</b> - {@link #readConfigurationData(String)}
- *                              {@link #updateConfigurationData(String, CompositeNode)}
- *                              {@link #createConfigurationData(CompositeNode)}
- *                              {@link #createConfigurationData(String, CompositeNode)}
- *                              {@link #deleteConfigurationData(String)}
- *      <li><b>/operational</b> - {@link #readOperationalData(String)}
- *      <li>/modules - {@link #getModules()}
- *       <ul>
- *        <li>/module
- *       </ul>
- *      <li><b>/operations</b> - {@link #invokeRpc(String, CompositeNode)}
- *                               {@link #invokeRpc(String, CompositeNode)}
- *      <li>/version (field)
- *     </ul>
- *   </ul>
+ * The URI hierarchy for the RESTCONF resources consists of an entry point container, 4 top-level resources, and 1
+ * field.
+ * <ul>
+ * <li><b>/restconf</b> - {@link #getRoot()}
+ * <ul>
+ * <li><b>/config</b> - {@link #readConfigurationData(String)} {@link #updateConfigurationData(String, CompositeNode)}
+ * {@link #createConfigurationData(CompositeNode)} {@link #createConfigurationData(String, CompositeNode)}
+ * {@link #deleteConfigurationData(String)}
+ * <li><b>/operational</b> - {@link #readOperationalData(String)}
+ * <li>/modules - {@link #getModules()}
+ * <ul>
+ * <li>/module
+ * </ul>
+ * <li><b>/operations</b> - {@link #invokeRpc(String, CompositeNode)} {@link #invokeRpc(String, CompositeNode)}
+ * <li>/version (field)
+ * </ul>
+ * </ul>
  */
 @Path("/")
 public interface RestconfService {
@@ -58,81 +54,83 @@ public interface RestconfService {
 
     @GET
     @Path("/modules")
-    @Produces({Draft02.MediaTypes.API+XML, Draft02.MediaTypes.API+JSON,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public StructuredData getModules();
+    @Produces({ Draft02.MediaTypes.API + XML, Draft02.MediaTypes.API + JSON, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
+    public StructuredData getModules(@Context UriInfo uriInfo);
 
     @GET
     @Path("/modules/{identifier:.+}")
-    @Produces({Draft02.MediaTypes.API+XML, Draft02.MediaTypes.API+JSON,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public StructuredData getModules(@PathParam("identifier") String identifier);
+    @Produces({ Draft02.MediaTypes.API + XML, Draft02.MediaTypes.API + JSON, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
+    public StructuredData getModules(@PathParam("identifier") String identifier, @Context UriInfo uriInfo);
 
     @GET
     @Path("/modules/module/{identifier:.+}")
-    @Produces({Draft02.MediaTypes.API+XML, Draft02.MediaTypes.API+JSON,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public StructuredData getModule(@PathParam("identifier") String identifier);
+    @Produces({ Draft02.MediaTypes.API + XML, Draft02.MediaTypes.API + JSON, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
+    public StructuredData getModule(@PathParam("identifier") String identifier, @Context UriInfo uriInfo);
 
     @GET
     @Path("/operations")
-    @Produces({Draft02.MediaTypes.API+XML, Draft02.MediaTypes.API+JSON,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public StructuredData getOperations();
+    @Produces({ Draft02.MediaTypes.API + XML, Draft02.MediaTypes.API + JSON, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
+    public StructuredData getOperations(@Context UriInfo uriInfo);
 
     @GET
     @Path("/operations/{identifier:.+}")
-    @Produces({Draft02.MediaTypes.API+XML, Draft02.MediaTypes.API+JSON,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public StructuredData getOperations(@PathParam("identifier") String identifier);
+    @Produces({ Draft02.MediaTypes.API + XML, Draft02.MediaTypes.API + JSON, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
+    public StructuredData getOperations(@PathParam("identifier") String identifier, @Context UriInfo uriInfo);
 
     @POST
     @Path("/operations/{identifier:.+}")
-    @Produces({Draft02.MediaTypes.OPERATION+JSON, Draft02.MediaTypes.OPERATION+XML,
-               Draft02.MediaTypes.DATA+JSON, Draft02.MediaTypes.DATA+XML,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    @Consumes({Draft02.MediaTypes.OPERATION+JSON, Draft02.MediaTypes.OPERATION+XML,
-               Draft02.MediaTypes.DATA+JSON, Draft02.MediaTypes.DATA+XML,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public StructuredData invokeRpc(@Encoded @PathParam("identifier") String identifier, CompositeNode payload);
+    @Produces({ Draft02.MediaTypes.OPERATION + JSON, Draft02.MediaTypes.OPERATION + XML,
+            Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
+    @Consumes({ Draft02.MediaTypes.OPERATION + JSON, Draft02.MediaTypes.OPERATION + XML,
+            Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
+    public StructuredData invokeRpc(@Encoded @PathParam("identifier") String identifier, CompositeNode payload,
+            @Context UriInfo uriInfo);
 
     @POST
     @Path("/operations/{identifier:.+}")
-    @Produces({Draft02.MediaTypes.OPERATION+JSON, Draft02.MediaTypes.OPERATION+XML,
-               Draft02.MediaTypes.DATA+JSON, Draft02.MediaTypes.DATA+XML,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public StructuredData invokeRpc(@Encoded @PathParam("identifier") String identifier, @DefaultValue("") String noPayload);
+    @Produces({ Draft02.MediaTypes.OPERATION + JSON, Draft02.MediaTypes.OPERATION + XML,
+            Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
+    public StructuredData invokeRpc(@Encoded @PathParam("identifier") String identifier,
+            @DefaultValue("") String noPayload, @Context UriInfo uriInfo);
 
     @GET
     @Path("/config/{identifier:.+}")
-    @Produces({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
+    @Produces({ Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
     public StructuredData readConfigurationData(@Encoded @PathParam("identifier") String identifier,
-                                                @Context UriInfo depth);
+            @Context UriInfo uriInfo);
 
     @GET
     @Path("/operational/{identifier:.+}")
-    @Produces({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
+    @Produces({ Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
     public StructuredData readOperationalData(@Encoded @PathParam("identifier") String identifier,
-                                              @Context UriInfo depth);
+            @Context UriInfo uriInfo);
 
     @PUT
     @Path("/config/{identifier:.+}")
-    @Consumes({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
+    @Consumes({ Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
     public Response updateConfigurationData(@Encoded @PathParam("identifier") String identifier, CompositeNode payload);
 
     @POST
     @Path("/config/{identifier:.+}")
-    @Consumes({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
+    @Consumes({ Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
     public Response createConfigurationData(@Encoded @PathParam("identifier") String identifier, CompositeNode payload);
 
     @POST
     @Path("/config")
-    @Consumes({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
-               MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
+    @Consumes({ Draft02.MediaTypes.DATA + JSON, Draft02.MediaTypes.DATA + XML, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
     public Response createConfigurationData(CompositeNode payload);
 
     @DELETE
@@ -145,9 +143,8 @@ public interface RestconfService {
 
     @GET
     @Path("/streams")
-    @Produces({Draft02.MediaTypes.API+XML, Draft02.MediaTypes.API+JSON,
-            MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public StructuredData getAvailableStreams();
-
+    @Produces({ Draft02.MediaTypes.API + XML, Draft02.MediaTypes.API + JSON, MediaType.APPLICATION_JSON,
+            MediaType.APPLICATION_XML, MediaType.TEXT_XML })
+    public StructuredData getAvailableStreams(@Context UriInfo uriInfo);
 
 }
diff --git a/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/gson/JsonParser.java b/opendaylight/md-sal/sal-rest-connector/src/main/java/org/opendaylight/controller/sal/rest/gson/JsonParser.java
new file mode 100644 (file)
index 0000000..a784be2
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.sal.rest.gson;
+
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonIOException;
+import com.google.gson.JsonNull;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonParseException;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.JsonSyntaxException;
+import com.google.gson.internal.LazilyParsedNumber;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.MalformedJsonException;
+import java.io.EOFException;
+import java.io.IOException;
+
+/**
+ * This class parses JSON elements from a gson JsonReader. It disallows multiple elements of the same name unlike the
+ * default gson JsonParser."
+ */
+public class JsonParser {
+    public JsonElement parse(JsonReader reader) throws JsonIOException, JsonSyntaxException {
+        // code copied from gson's JsonParser and Stream classes
+
+        boolean lenient = reader.isLenient();
+        reader.setLenient(true);
+        boolean isEmpty = true;
+        try {
+            reader.peek();
+            isEmpty = false;
+            return read(reader);
+        } catch (EOFException e) {
+            if (isEmpty) {
+                return JsonNull.INSTANCE;
+            }
+            // The stream ended prematurely so it is likely a syntax error.
+            throw new JsonSyntaxException(e);
+        } catch (MalformedJsonException e) {
+            throw new JsonSyntaxException(e);
+        } catch (IOException e) {
+            throw new JsonIOException(e);
+        } catch (NumberFormatException e) {
+            throw new JsonSyntaxException(e);
+        } catch (StackOverflowError | OutOfMemoryError e) {
+            throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e);
+        } finally {
+            reader.setLenient(lenient);
+        }
+    }
+
+    public JsonElement read(JsonReader in) throws IOException {
+        switch (in.peek()) {
+        case STRING:
+            return new JsonPrimitive(in.nextString());
+        case NUMBER:
+            String number = in.nextString();
+            return new JsonPrimitive(new LazilyParsedNumber(number));
+        case BOOLEAN:
+            return new JsonPrimitive(in.nextBoolean());
+        case NULL:
+            in.nextNull();
+            return JsonNull.INSTANCE;
+        case BEGIN_ARRAY:
+            JsonArray array = new JsonArray();
+            in.beginArray();
+            while (in.hasNext()) {
+                array.add(read(in));
+            }
+            in.endArray();
+            return array;
+        case BEGIN_OBJECT:
+            JsonObject object = new JsonObject();
+            in.beginObject();
+            while (in.hasNext()) {
+                final String childName = in.nextName();
+                if (object.has(childName)) {
+                    throw new JsonSyntaxException("Duplicate name " + childName + " in JSON input.");
+                }
+                object.add(childName, read(in));
+            }
+            in.endObject();
+            return object;
+        case END_DOCUMENT:
+        case NAME:
+        case END_OBJECT:
+        case END_ARRAY:
+        default:
+            throw new IllegalArgumentException();
+        }
+    }
+}
index 1e5bfbd6b93e7fe540931a0f6f828625a4a963c1..4b4cef9f70873b2c34858de93e529d91d0ea7a5e 100644 (file)
@@ -9,15 +9,15 @@ package org.opendaylight.controller.sal.rest.impl;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 
+import com.google.common.base.Preconditions;
+import com.google.gson.stream.JsonWriter;
 import java.io.IOException;
 import java.net.URI;
 import java.util.Collections;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
-
 import javax.activation.UnsupportedDataTypeException;
-
 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO;
@@ -29,6 +29,7 @@ import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.Node;
 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
+import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
@@ -48,22 +49,19 @@ import org.opendaylight.yangtools.yang.model.api.type.UnsignedIntegerTypeDefinit
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Preconditions;
-import com.google.gson.stream.JsonWriter;
-
 class JsonMapper {
+    private static final Logger LOG = LoggerFactory.getLogger(JsonMapper.class);
+    private final MountInstance mountPoint;
 
-    private final Set<LeafListSchemaNode> foundLeafLists = new HashSet<>();
-    private final Set<ListSchemaNode> foundLists = new HashSet<>();
-    private MountInstance mountPoint;
-    private final Logger logger = LoggerFactory.getLogger(JsonMapper.class);
+    public JsonMapper(final MountInstance mountPoint) {
+        this.mountPoint = mountPoint;
+    }
 
-    public void write(final JsonWriter writer, final CompositeNode data, final DataNodeContainer schema, final MountInstance mountPoint)
+    public void write(final JsonWriter writer, final CompositeNode data, final DataNodeContainer schema)
             throws IOException {
         Preconditions.checkNotNull(writer);
         Preconditions.checkNotNull(data);
         Preconditions.checkNotNull(schema);
-        this.mountPoint = mountPoint;
 
         writer.beginObject();
 
@@ -77,18 +75,16 @@ class JsonMapper {
         }
 
         writer.endObject();
-
-        foundLeafLists.clear();
-        foundLists.clear();
     }
 
-    private void writeChildrenOfParent(final JsonWriter writer, final CompositeNode parent, final DataNodeContainer parentSchema)
-            throws IOException {
+    private void writeChildrenOfParent(final JsonWriter writer, final CompositeNode parent,
+            final DataNodeContainer parentSchema) throws IOException {
         checkNotNull(parent);
 
-        Set<DataSchemaNode> parentSchemaChildNodes = parentSchema == null ?
-                                   Collections.<DataSchemaNode>emptySet() : parentSchema.getChildNodes();
+        final Set<QName> foundLists = new HashSet<>();
 
+        Set<DataSchemaNode> parentSchemaChildNodes = parentSchema == null ? Collections.<DataSchemaNode> emptySet()
+                : parentSchema.getChildNodes();
 
         for (Node<?> child : parent.getValue()) {
             DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchemaChildNodes);
@@ -96,69 +92,90 @@ class JsonMapper {
             if (childSchema == null) {
                 // Node may not conform to schema or allows "anyxml" - we'll process it.
 
-                logger.debug( "No schema found for data node \"" + child.getNodeType() );
+                LOG.debug("No schema found for data node \"{}\"", child.getNodeType());
 
-                handleNoSchemaFound( writer, child, parent );
-            }
-            else if (childSchema instanceof ContainerSchemaNode) {
+                if (!foundLists.contains(child.getNodeType())) {
+                    handleNoSchemaFound(writer, child, parent);
+
+                    // Since we don't have a schema, we don't know which nodes are supposed to be
+                    // lists so treat every one as a potential list to avoid outputting duplicates.
+
+                    foundLists.add(child.getNodeType());
+                }
+            } else if (childSchema instanceof ContainerSchemaNode) {
                 Preconditions.checkState(child instanceof CompositeNode,
-                        "Data representation of Container should be CompositeNode - " + child.getNodeType());
+                        "Data representation of Container should be CompositeNode - %s", child.getNodeType());
                 writeContainer(writer, (CompositeNode) child, (ContainerSchemaNode) childSchema);
             } else if (childSchema instanceof ListSchemaNode) {
-                if (!foundLists.contains(childSchema)) {
+                if (!foundLists.contains(child.getNodeType())) {
                     Preconditions.checkState(child instanceof CompositeNode,
-                            "Data representation of List should be CompositeNode - " + child.getNodeType());
-                    foundLists.add((ListSchemaNode) childSchema);
+                            "Data representation of List should be CompositeNode - %s", child.getNodeType());
+                    foundLists.add(child.getNodeType());
                     writeList(writer, parent, (CompositeNode) child, (ListSchemaNode) childSchema);
                 }
             } else if (childSchema instanceof LeafListSchemaNode) {
-                if (!foundLeafLists.contains(childSchema)) {
+                if (!foundLists.contains(child.getNodeType())) {
                     Preconditions.checkState(child instanceof SimpleNode<?>,
-                            "Data representation of LeafList should be SimpleNode - " + child.getNodeType());
-                    foundLeafLists.add((LeafListSchemaNode) childSchema);
+                            "Data representation of LeafList should be SimpleNode - %s", child.getNodeType());
+                    foundLists.add(child.getNodeType());
                     writeLeafList(writer, parent, (SimpleNode<?>) child, (LeafListSchemaNode) childSchema);
                 }
             } else if (childSchema instanceof LeafSchemaNode) {
                 Preconditions.checkState(child instanceof SimpleNode<?>,
-                        "Data representation of LeafList should be SimpleNode - " + child.getNodeType());
+                        "Data representation of LeafList should be SimpleNode - %s", child.getNodeType());
                 writeLeaf(writer, (SimpleNode<?>) child, (LeafSchemaNode) childSchema);
+            } else if (childSchema instanceof AnyXmlSchemaNode) {
+                if (child instanceof CompositeNode) {
+                    writeContainer(writer, (CompositeNode) child, null);
+                } else {
+                    handleNoSchemaFound(writer, child, parent);
+                }
             } else {
                 throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode, ListSchemaNode, "
                         + "LeafListSchemaNode, or LeafSchemaNode. Other types are not supported yet.");
             }
         }
+    }
 
-        for (Node<?> child : parent.getValue()) {
-            DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchemaChildNodes);
-            if (childSchema instanceof LeafListSchemaNode) {
-                foundLeafLists.remove(childSchema);
-            } else if (childSchema instanceof ListSchemaNode) {
-                foundLists.remove(childSchema);
-            }
-        }
+    private static void writeValue(final JsonWriter writer, final Object value) throws IOException {
+        writer.value(value == null ? "" : String.valueOf(value));
     }
 
-    private void handleNoSchemaFound( final JsonWriter writer, final Node<?> node,
-                                      final CompositeNode parent ) throws IOException {
-        if( node instanceof SimpleNode<?> ) {
-            writeName( node, null, writer );
-            Object value = node.getValue();
-            if( value != null ) {
-                writer.value( String.valueOf( value ) );
+    private void handleNoSchemaFound(final JsonWriter writer, final Node<?> node, final CompositeNode parent)
+            throws IOException {
+        if (node instanceof SimpleNode<?>) {
+            List<SimpleNode<?>> nodeLeafList = parent.getSimpleNodesByName(node.getNodeType());
+            if (nodeLeafList.size() == 1) {
+                writeName(node, null, writer);
+                writeValue(writer, node.getValue());
+            } else { // more than 1, write as a json array
+                writeName(node, null, writer);
+                writer.beginArray();
+                for (SimpleNode<?> leafNode : nodeLeafList) {
+                    writeValue(writer, leafNode.getValue());
+                }
+
+                writer.endArray();
             }
         } else { // CompositeNode
-            Preconditions.checkState( node instanceof CompositeNode,
-                    "Data representation of Container should be CompositeNode - " + node.getNodeType() );
-
-            writeContainer( writer, (CompositeNode) node, null );
+            Preconditions.checkState(node instanceof CompositeNode,
+                    "Data representation of Container should be CompositeNode - %s", node.getNodeType());
+
+            List<CompositeNode> nodeList = parent.getCompositesByName(node.getNodeType());
+            if (nodeList.size() == 1) {
+                writeContainer(writer, (CompositeNode) node, null);
+            } else { // more than 1, write as a json array
+                writeList(writer, parent, (CompositeNode) node, null);
+            }
         }
     }
 
-    private DataSchemaNode findFirstSchemaForNode(final Node<?> node, final Set<DataSchemaNode> dataSchemaNode) {
+    private static DataSchemaNode findFirstSchemaForNode(final Node<?> node, final Set<DataSchemaNode> dataSchemaNode) {
         for (DataSchemaNode dsn : dataSchemaNode) {
             if (node.getNodeType().equals(dsn.getQName())) {
                 return dsn;
-            } else if (dsn instanceof ChoiceNode) {
+            }
+            if (dsn instanceof ChoiceNode) {
                 for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
                     DataSchemaNode foundDsn = findFirstSchemaForNode(node, choiceCase.getChildNodes());
                     if (foundDsn != null) {
@@ -170,15 +187,16 @@ class JsonMapper {
         return null;
     }
 
-    private void writeContainer(final JsonWriter writer, final CompositeNode node, final ContainerSchemaNode schema) throws IOException {
+    private void writeContainer(final JsonWriter writer, final CompositeNode node, final ContainerSchemaNode schema)
+            throws IOException {
         writeName(node, schema, writer);
         writer.beginObject();
         writeChildrenOfParent(writer, node, schema);
         writer.endObject();
     }
 
-    private void writeList(final JsonWriter writer, final CompositeNode nodeParent, final CompositeNode node, final ListSchemaNode schema)
-            throws IOException {
+    private void writeList(final JsonWriter writer, final CompositeNode nodeParent, final CompositeNode node,
+            final ListSchemaNode schema) throws IOException {
         writeName(node, schema, writer);
         writer.beginArray();
 
@@ -210,19 +228,20 @@ class JsonMapper {
         writer.endArray();
     }
 
-    private void writeLeaf(final JsonWriter writer, final SimpleNode<?> node, final LeafSchemaNode schema) throws IOException {
+    private void writeLeaf(final JsonWriter writer, final SimpleNode<?> node, final LeafSchemaNode schema)
+            throws IOException {
         writeName(node, schema, writer);
         writeValueOfNodeByType(writer, node, schema.getType(), schema);
     }
 
-    private void writeValueOfNodeByType(final JsonWriter writer, final SimpleNode<?> node, final TypeDefinition<?> type,
-            final DataSchemaNode schema) throws IOException {
+    private void writeValueOfNodeByType(final JsonWriter writer, final SimpleNode<?> node,
+            final TypeDefinition<?> type, final DataSchemaNode schema) throws IOException {
 
         TypeDefinition<?> baseType = RestUtil.resolveBaseTypeFrom(type);
 
         if (node.getValue() == null && !(baseType instanceof EmptyTypeDefinition)) {
-            logger.debug("While generationg JSON output null value was found for type "
-                    + baseType.getClass().getSimpleName() + ".");
+            LOG.debug("While generationg JSON output null value was found for type {}.", baseType.getClass()
+                    .getSimpleName());
         }
 
         if (baseType instanceof IdentityrefTypeDefinition) {
@@ -267,25 +286,25 @@ class JsonMapper {
         }
     }
 
-    private void writeIdentityValuesDTOToJson(final JsonWriter writer, final IdentityValuesDTO valueDTO) throws IOException {
+    private static void writeIdentityValuesDTOToJson(final JsonWriter writer, final IdentityValuesDTO valueDTO)
+            throws IOException {
         StringBuilder result = new StringBuilder();
         for (IdentityValue identityValue : valueDTO.getValuesWithNamespaces()) {
-            result.append("/");
+            result.append('/');
 
             writeModuleNameAndIdentifier(result, identityValue);
             if (identityValue.getPredicates() != null && !identityValue.getPredicates().isEmpty()) {
                 for (Predicate predicate : identityValue.getPredicates()) {
                     IdentityValue identityValuePredicate = predicate.getName();
-                    result.append("[");
+                    result.append('[');
                     if (identityValuePredicate == null) {
-                        result.append(".");
+                        result.append('.');
                     } else {
                         writeModuleNameAndIdentifier(result, identityValuePredicate);
                     }
                     result.append("='");
                     result.append(predicate.getValue());
-                    result.append("'");
-                    result.append("]");
+                    result.append("']");
                 }
             }
         }
@@ -293,21 +312,21 @@ class JsonMapper {
         writer.value(result.toString());
     }
 
-    private void writeModuleNameAndIdentifier(final StringBuilder result, final IdentityValue identityValue) {
+    private static void writeModuleNameAndIdentifier(final StringBuilder result, final IdentityValue identityValue) {
         String moduleName = ControllerContext.getInstance().findModuleNameByNamespace(
                 URI.create(identityValue.getNamespace()));
         if (moduleName != null && !moduleName.isEmpty()) {
             result.append(moduleName);
-            result.append(":");
+            result.append(':');
         }
         result.append(identityValue.getValue());
     }
 
-    private void writeStringRepresentation(final JsonWriter writer, final SimpleNode<?> node, final TypeDefinition<?> baseType,
-            final Class<?> requiredType) throws IOException {
+    private static void writeStringRepresentation(final JsonWriter writer, final SimpleNode<?> node,
+            final TypeDefinition<?> baseType, final Class<?> requiredType) throws IOException {
         Object value = node.getValue();
-        logger.debug("Value of " + baseType.getQName().getNamespace() + ":" + baseType.getQName().getLocalName()
-                + " is not instance of " + requiredType.getClass() + " but is " + node.getValue().getClass());
+        LOG.debug("Value of {}:{} is not instance of {} but is {}", baseType.getQName().getNamespace(), baseType
+                .getQName().getLocalName(), requiredType.getClass(), node.getValue().getClass());
         if (value == null) {
             writer.value("");
         } else {
@@ -323,7 +342,7 @@ class JsonMapper {
 
     private void writeName(final Node<?> node, final DataSchemaNode schema, final JsonWriter writer) throws IOException {
         String nameForOutput = node.getNodeType().getLocalName();
-        if ( schema != null && schema.isAugmenting()) {
+        if (schema != null && schema.isAugmenting()) {
             ControllerContext contContext = ControllerContext.getInstance();
             CharSequence moduleName = null;
             if (mountPoint == null) {
@@ -334,7 +353,7 @@ class JsonMapper {
             if (moduleName != null) {
                 nameForOutput = moduleName.toString();
             } else {
-                logger.info("Module '{}' was not found in schema from mount point", schema.getQName());
+                LOG.info("Module '{}' was not found in schema from mount point", schema.getQName());
             }
         }
         writer.name(nameForOutput);
index 856e09fabd21a1083cbe716890ba22ae3b2d5bc6..2f3499e26968e17e9fa5f662ab66063965657815 100644 (file)
@@ -11,14 +11,12 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.lang.annotation.Annotation;
 import java.lang.reflect.Type;
-
 import javax.ws.rs.Consumes;
 import javax.ws.rs.WebApplicationException;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.MultivaluedMap;
 import javax.ws.rs.ext.MessageBodyReader;
 import javax.ws.rs.ext.Provider;
-
 import org.opendaylight.controller.sal.rest.api.Draft02;
 import org.opendaylight.controller.sal.rest.api.RestconfService;
 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
@@ -34,26 +32,26 @@ import org.slf4j.LoggerFactory;
 public enum JsonToCompositeNodeProvider implements MessageBodyReader<CompositeNode> {
     INSTANCE;
 
-    private final static Logger LOG = LoggerFactory.getLogger( JsonToCompositeNodeProvider.class );
+    private final static Logger LOG = LoggerFactory.getLogger(JsonToCompositeNodeProvider.class);
 
     @Override
-    public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
+    public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
+            final MediaType mediaType) {
         return true;
     }
 
     @Override
-    public CompositeNode readFrom(Class<CompositeNode> type, Type genericType, Annotation[] annotations,
-            MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
-            throws IOException, WebApplicationException {
-        JsonReader jsonReader = new JsonReader();
+    public CompositeNode readFrom(final Class<CompositeNode> type, final Type genericType,
+            final Annotation[] annotations, final MediaType mediaType,
+            final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
+            WebApplicationException {
         try {
-            return jsonReader.read(entityStream);
+            return JsonToCompositeNodeReader.read(entityStream);
         } catch (Exception e) {
-            LOG.debug( "Error parsing json input", e );
-            throw new RestconfDocumentedException(
-                            "Error parsing input: " + e.getMessage(),
-                            ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE );
+            LOG.debug("Error parsing json input", e);
+
+            throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
+                    ErrorTag.MALFORMED_MESSAGE);
         }
     }
-
 }
@@ -7,33 +7,41 @@
  */
 package org.opendaylight.controller.sal.rest.impl;
 
+import com.google.common.base.Splitter;
+import com.google.common.collect.Iterators;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonObject;
+import com.google.gson.JsonPrimitive;
+import com.google.gson.stream.JsonReader;
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.net.URI;
+import java.util.Iterator;
 import java.util.Map.Entry;
 import java.util.Set;
-
+import org.opendaylight.controller.sal.rest.gson.JsonParser;
 import org.opendaylight.controller.sal.rest.impl.RestUtil.PrefixMapingFromJson;
 import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
 import org.opendaylight.controller.sal.restconf.impl.EmptyNodeWrapper;
 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO;
 import org.opendaylight.controller.sal.restconf.impl.SimpleNodeWrapper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
-import com.google.common.collect.Lists;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonObject;
-import com.google.gson.JsonParser;
-import com.google.gson.JsonPrimitive;
+class JsonToCompositeNodeReader {
+    private static final Logger LOG = LoggerFactory.getLogger(JsonReader.class);
+    private static final Splitter COLON_SPLITTER = Splitter.on(':');
+
+    private JsonToCompositeNodeReader() {
 
-class JsonReader {
+    }
 
-    public CompositeNodeWrapper read(InputStream entityStream) throws UnsupportedFormatException {
+    public static CompositeNodeWrapper read(final InputStream entityStream) throws UnsupportedFormatException {
         JsonParser parser = new JsonParser();
 
-        JsonElement rootElement = parser.parse(new InputStreamReader(entityStream));
-        if( rootElement.isJsonNull() )
-        {
-            //no content, so return null to indicate no input
+        JsonElement rootElement = parser.parse(new JsonReader(new InputStreamReader(entityStream)));
+        if (rootElement.isJsonNull()) {
+            // no content, so return null to indicate no input
             return null;
         }
 
@@ -44,29 +52,31 @@ class JsonReader {
         Set<Entry<String, JsonElement>> entrySetsOfRootJsonObject = rootElement.getAsJsonObject().entrySet();
         if (entrySetsOfRootJsonObject.size() != 1) {
             throw new UnsupportedFormatException("Json Object should contain one element");
-        } else {
-            Entry<String, JsonElement> childEntry = Lists.newArrayList(entrySetsOfRootJsonObject).get(0);
-            String firstElementName = childEntry.getKey();
-            JsonElement firstElementType = childEntry.getValue();
-            if (firstElementType.isJsonObject()) { // container in yang
-                return createStructureWithRoot(firstElementName, firstElementType.getAsJsonObject());
-            }
-            if (firstElementType.isJsonArray()) { // list in yang
-                if (firstElementType.getAsJsonArray().size() == 1) {
-                    JsonElement firstElementInArray = firstElementType.getAsJsonArray().get(0);
-                    if (firstElementInArray.isJsonObject()) {
-                        return createStructureWithRoot(firstElementName, firstElementInArray.getAsJsonObject());
-                    }
-                    throw new UnsupportedFormatException(
-                            "Array as the first element in Json Object can have only Object element");
+        }
+
+        Entry<String, JsonElement> childEntry = entrySetsOfRootJsonObject.iterator().next();
+        String firstElementName = childEntry.getKey();
+        JsonElement firstElementType = childEntry.getValue();
+        if (firstElementType.isJsonObject()) {
+            // container in yang
+            return createStructureWithRoot(firstElementName, firstElementType.getAsJsonObject());
+        }
+        if (firstElementType.isJsonArray()) {
+            // list in yang
+            if (firstElementType.getAsJsonArray().size() == 1) {
+                JsonElement firstElementInArray = firstElementType.getAsJsonArray().get(0);
+                if (firstElementInArray.isJsonObject()) {
+                    return createStructureWithRoot(firstElementName, firstElementInArray.getAsJsonObject());
                 }
+                throw new UnsupportedFormatException(
+                        "Array as the first element in Json Object can have only Object element");
             }
-            throw new UnsupportedFormatException(
-                    "First element in Json Object has to be \"Object\" or \"Array with one Object element\". Other scenarios are not supported yet.");
         }
+        throw new UnsupportedFormatException(
+                "First element in Json Object has to be \"Object\" or \"Array with one Object element\". Other scenarios are not supported yet.");
     }
 
-    private CompositeNodeWrapper createStructureWithRoot(String rootObjectName, JsonObject rootObject) {
+    private static CompositeNodeWrapper createStructureWithRoot(final String rootObjectName, final JsonObject rootObject) {
         CompositeNodeWrapper firstNode = new CompositeNodeWrapper(getNamespaceFor(rootObjectName),
                 getLocalNameFor(rootObjectName));
         for (Entry<String, JsonElement> childOfFirstNode : rootObject.entrySet()) {
@@ -75,9 +85,11 @@ class JsonReader {
         return firstNode;
     }
 
-    private void addChildToParent(String childName, JsonElement childType, CompositeNodeWrapper parent) {
+    private static void addChildToParent(final String childName, final JsonElement childType,
+            final CompositeNodeWrapper parent) {
         if (childType.isJsonObject()) {
-            CompositeNodeWrapper child = new CompositeNodeWrapper(getNamespaceFor(childName), getLocalNameFor(childName));
+            CompositeNodeWrapper child = new CompositeNodeWrapper(getNamespaceFor(childName),
+                    getLocalNameFor(childName));
             parent.addValue(child);
             for (Entry<String, JsonElement> childOfChild : childType.getAsJsonObject().entrySet()) {
                 addChildToParent(childOfChild.getKey(), childOfChild.getValue(), child);
@@ -96,40 +108,48 @@ class JsonReader {
             String value = childPrimitive.getAsString().trim();
             parent.addValue(new SimpleNodeWrapper(getNamespaceFor(childName), getLocalNameFor(childName),
                     resolveValueOfElement(value)));
+        } else {
+            LOG.debug("Ignoring unhandled child type {}", childType);
         }
     }
 
-    private URI getNamespaceFor(String jsonElementName) {
-        String[] moduleNameAndLocalName = jsonElementName.split(":");
-        // it is not "moduleName:localName"
-        if (moduleNameAndLocalName.length != 2) {
-            return null;
+    private static URI getNamespaceFor(final String jsonElementName) {
+        final Iterator<String> it = COLON_SPLITTER.split(jsonElementName).iterator();
+
+        // The string needs to me in form "moduleName:localName"
+        if (it.hasNext()) {
+            final String maybeURI = it.next();
+            if (Iterators.size(it) == 1) {
+                return URI.create(maybeURI);
+            }
         }
-        return URI.create(moduleNameAndLocalName[0]);
+
+        return null;
     }
 
-    private String getLocalNameFor(String jsonElementName) {
-        String[] moduleNameAndLocalName = jsonElementName.split(":");
-        // it is not "moduleName:localName"
-        if (moduleNameAndLocalName.length != 2) {
-            return jsonElementName;
-        }
-        return moduleNameAndLocalName[1];
+    private static String getLocalNameFor(final String jsonElementName) {
+        final Iterator<String> it = COLON_SPLITTER.split(jsonElementName).iterator();
+
+        // The string needs to me in form "moduleName:localName"
+        final String ret = Iterators.get(it, 1, null);
+        return ret != null && !it.hasNext() ? ret : jsonElementName;
     }
 
-    private Object resolveValueOfElement(String value) {
+    private static Object resolveValueOfElement(final String value) {
         // it could be instance-identifier Built-In Type
-        if (value.startsWith("/")) {
+        if (!value.isEmpty() && value.charAt(0) == '/') {
             IdentityValuesDTO resolvedValue = RestUtil.asInstanceIdentifier(value, new PrefixMapingFromJson());
             if (resolvedValue != null) {
                 return resolvedValue;
             }
         }
+
         // it could be identityref Built-In Type
         URI namespace = getNamespaceFor(value);
         if (namespace != null) {
-            return new IdentityValuesDTO(namespace.toString(), getLocalNameFor(value), null,value);
+            return new IdentityValuesDTO(namespace.toString(), getLocalNameFor(value), null, value);
         }
+
         // it is not "prefix:value" but just "value"
         return value;
     }
index 290d976b2857c493e7c638592e2715e963a03277..7890931a27fea2585de986ce524718f9df5db6a2 100644 (file)
@@ -11,9 +11,7 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
-
 import javax.xml.stream.events.StartElement;
-
 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO;
 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.IdentityValue;
 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.Predicate;
@@ -21,11 +19,13 @@ import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
 
 public final class RestUtil {
 
+    // FIXME: BUG-1275: this is code duplicates data.impl.codec
+
     public static final String SQUOTE = "'";
     public static final String DQUOTE = "\"";
     private static final Pattern PREDICATE_PATTERN = Pattern.compile("\\[(.*?)\\]");
 
-    public final static TypeDefinition<?> resolveBaseTypeFrom(TypeDefinition<?> type) {
+    public final static TypeDefinition<?> resolveBaseTypeFrom(final TypeDefinition<?> type) {
         TypeDefinition<?> superType = type;
         while (superType.getBaseType() != null) {
             superType = superType.getBaseType();
@@ -33,7 +33,7 @@ public final class RestUtil {
         return superType;
     }
 
-    public static IdentityValuesDTO asInstanceIdentifier(String value, PrefixesMaping prefixMap) {
+    public static IdentityValuesDTO asInstanceIdentifier(final String value, final PrefixesMaping prefixMap) {
         String valueTrimmed = value.trim();
         if (!valueTrimmed.startsWith("/")) {
             return null;
@@ -63,12 +63,12 @@ public final class RestUtil {
         return identityValuesDTO.getValuesWithNamespaces().isEmpty() ? null : identityValuesDTO;
     }
 
-    private static String getIdAndPrefixAsStr(String pathPart) {
+    private static String getIdAndPrefixAsStr(final String pathPart) {
         int predicateStartIndex = pathPart.indexOf("[");
         return predicateStartIndex == -1 ? pathPart : pathPart.substring(0, predicateStartIndex);
     }
 
-    private static IdentityValue toIdentity(String xPathPart, PrefixesMaping prefixMap) {
+    private static IdentityValue toIdentity(final String xPathPart, final PrefixesMaping prefixMap) {
         String xPathPartTrimmed = xPathPart.trim();
         if (xPathPartTrimmed.isEmpty()) {
             return null;
@@ -87,7 +87,7 @@ public final class RestUtil {
         return new IdentityValue(namespace, identifier, namespace.equals(prefix) ? null : prefix);
     }
 
-    private static List<Predicate> toPredicates(String predicatesStr, PrefixesMaping prefixMap) {
+    private static List<Predicate> toPredicates(final String predicatesStr, final PrefixesMaping prefixMap) {
         List<Predicate> result = new ArrayList<>();
         List<String> predicates = new ArrayList<>();
         Matcher matcher = PREDICATE_PATTERN.matcher(predicatesStr);
@@ -104,8 +104,7 @@ public final class RestUtil {
                     }
                     result.add(new Predicate(null, predicateValue));
                 } else {
-                    IdentityValue identityValue = toIdentity(predicate.substring(0, indexOfEqualityMark),
-                            prefixMap);
+                    IdentityValue identityValue = toIdentity(predicate.substring(0, indexOfEqualityMark), prefixMap);
                     if (identityValue == null || predicateValue == null) {
                         return null;
                     }
@@ -116,7 +115,7 @@ public final class RestUtil {
         return result;
     }
 
-    private static String toPredicateValue(String predicatedValue) {
+    private static String toPredicateValue(final String predicatedValue) {
         String predicatedValueTrimmed = predicatedValue.trim();
         if ((predicatedValueTrimmed.startsWith(DQUOTE) || predicatedValueTrimmed.startsWith(SQUOTE))
                 && (predicatedValueTrimmed.endsWith(DQUOTE) || predicatedValueTrimmed.endsWith(SQUOTE))) {
@@ -132,12 +131,12 @@ public final class RestUtil {
     public static class PrefixMapingFromXml implements PrefixesMaping {
         StartElement startElement = null;
 
-        public PrefixMapingFromXml(StartElement startElement) {
+        public PrefixMapingFromXml(final StartElement startElement) {
             this.startElement = startElement;
         }
 
         @Override
-        public String getNamespace(String prefix) {
+        public String getNamespace(final String prefix) {
             return startElement.getNamespaceContext().getNamespaceURI(prefix);
         }
     }
@@ -145,7 +144,7 @@ public final class RestUtil {
     public static class PrefixMapingFromJson implements PrefixesMaping {
 
         @Override
-        public String getNamespace(String prefix) {
+        public String getNamespace(final String prefix) {
             return prefix;
         }
     }
index a5fd7bdaab2646f35e7463f9698f15ca217de11f..b4b2a1f9ef7249734e128456a33876abc3862ae8 100644 (file)
@@ -7,22 +7,19 @@
  */
 package org.opendaylight.controller.sal.rest.impl;
 
+import com.google.common.collect.ImmutableSet;
 import java.util.HashSet;
 import java.util.Set;
-
 import javax.ws.rs.core.Application;
-
 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
 import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
 
-import com.google.common.collect.ImmutableSet;
-
 public class RestconfApplication extends Application {
 
     @Override
     public Set<Class<?>> getClasses() {
-        return ImmutableSet.<Class<?>>of( RestconfDocumentedExceptionMapper.class );
+        return ImmutableSet.<Class<?>> of(RestconfDocumentedExceptionMapper.class);
     }
 
     @Override
@@ -43,5 +40,4 @@ public class RestconfApplication extends Application {
         return singletons;
     }
 
-
 }
index 5f6909cea8e3e15d2b7887fe975d2d3e613163b5..63a5b1b54055a81cd3f8f3f736365c4e99e1d8b8 100644 (file)
@@ -17,6 +17,10 @@ import static org.opendaylight.controller.sal.rest.api.Draft02.RestConfModule.ER
 import static org.opendaylight.controller.sal.rest.api.Draft02.RestConfModule.ERROR_TYPE_QNAME;
 import static org.opendaylight.controller.sal.rest.api.Draft02.RestConfModule.NAMESPACE;
 
+import com.google.common.base.Charsets;
+import com.google.common.base.Strings;
+import com.google.common.collect.ImmutableList;
+import com.google.gson.stream.JsonWriter;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.OutputStreamWriter;
@@ -24,7 +28,6 @@ import java.io.StringReader;
 import java.io.UnsupportedEncodingException;
 import java.util.List;
 import java.util.Map.Entry;
-
 import javax.activation.UnsupportedDataTypeException;
 import javax.ws.rs.core.Context;
 import javax.ws.rs.core.HttpHeaders;
@@ -41,7 +44,6 @@ import javax.xml.transform.TransformerFactory;
 import javax.xml.transform.TransformerFactoryConfigurationError;
 import javax.xml.transform.dom.DOMSource;
 import javax.xml.transform.stream.StreamResult;
-
 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
 import org.opendaylight.controller.sal.restconf.impl.RestconfError;
@@ -57,29 +59,24 @@ import org.slf4j.LoggerFactory;
 import org.w3c.dom.Document;
 import org.xml.sax.InputSource;
 
-import com.google.common.base.Strings;
-import com.google.common.collect.ImmutableList;
-import com.google.gson.stream.JsonWriter;
-
 /**
- * This class defines an ExceptionMapper that handles RestconfDocumentedExceptions thrown by
- * resource implementations and translates appropriately to restconf error response as defined in
- * the RESTCONF RFC draft.
+ * This class defines an ExceptionMapper that handles RestconfDocumentedExceptions thrown by resource implementations
+ * and translates appropriately to restconf error response as defined in the RESTCONF RFC draft.
  *
  * @author Thomas Pantelis
  */
 @Provider
 public class RestconfDocumentedExceptionMapper implements ExceptionMapper<RestconfDocumentedException> {
 
-    private final static Logger LOG = LoggerFactory.getLogger( RestconfDocumentedExceptionMapper.class );
+    private final static Logger LOG = LoggerFactory.getLogger(RestconfDocumentedExceptionMapper.class);
 
     @Context
     private HttpHeaders headers;
 
     @Override
-    public Response toResponse( final RestconfDocumentedException exception ) {
+    public Response toResponse(final RestconfDocumentedException exception) {
 
-        LOG.debug( "In toResponse: {}", exception.getMessage() );
+        LOG.debug("In toResponse: {}", exception.getMessage());
 
         // Default to the content type if there's no Accept header
 
@@ -87,172 +84,158 @@ public class RestconfDocumentedExceptionMapper implements ExceptionMapper<Restco
 
         List<MediaType> accepts = headers.getAcceptableMediaTypes();
 
-        LOG.debug( "Accept headers: {}", accepts );
+        LOG.debug("Accept headers: {}", accepts);
 
-        if( accepts != null && accepts.size() > 0 ) {
-            mediaType = accepts.get( 0 ); // just pick the first one
+        if (accepts != null && accepts.size() > 0) {
+            mediaType = accepts.get(0); // just pick the first one
         }
 
-        LOG.debug( "Using MediaType: {}",  mediaType );
+        LOG.debug("Using MediaType: {}", mediaType);
 
         List<RestconfError> errors = exception.getErrors();
-        if( errors.isEmpty() ) {
+        if (errors.isEmpty()) {
             // We don't actually want to send any content but, if we don't set any content here,
             // the tomcat front-end will send back an html error report. To prevent that, set a
             // single space char in the entity.
 
-            return Response.status( exception.getStatus() )
-                    .type( MediaType.TEXT_PLAIN_TYPE )
-                    .entity( " " ).build();
+            return Response.status(exception.getStatus()).type(MediaType.TEXT_PLAIN_TYPE).entity(" ").build();
         }
 
         int status = errors.iterator().next().getErrorTag().getStatusCode();
 
         ControllerContext context = ControllerContext.getInstance();
-        DataNodeContainer errorsSchemaNode = (DataNodeContainer)context.getRestconfModuleErrorsSchemaNode();
+        DataNodeContainer errorsSchemaNode = (DataNodeContainer) context.getRestconfModuleErrorsSchemaNode();
 
-        if( errorsSchemaNode == null ) {
-            return Response.status( status )
-                    .type( MediaType.TEXT_PLAIN_TYPE )
-                    .entity( exception.getMessage() ).build();
+        if (errorsSchemaNode == null) {
+            return Response.status(status).type(MediaType.TEXT_PLAIN_TYPE).entity(exception.getMessage()).build();
         }
 
         ImmutableList.Builder<Node<?>> errorNodes = ImmutableList.<Node<?>> builder();
-        for( RestconfError error: errors ) {
-            errorNodes.add( toDomNode( error ) );
+        for (RestconfError error : errors) {
+            errorNodes.add(toDomNode(error));
         }
 
-        ImmutableCompositeNode errorsNode =
-                ImmutableCompositeNode.create( ERRORS_CONTAINER_QNAME, errorNodes.build() );
+        ImmutableCompositeNode errorsNode = ImmutableCompositeNode.create(ERRORS_CONTAINER_QNAME, errorNodes.build());
 
         Object responseBody;
-        if( mediaType.getSubtype().endsWith( "json" ) ) {
-            responseBody = toJsonResponseBody( errorsNode, errorsSchemaNode );
-        }
-        else {
-            responseBody = toXMLResponseBody( errorsNode, errorsSchemaNode );
+        if (mediaType.getSubtype().endsWith("json")) {
+            responseBody = toJsonResponseBody(errorsNode, errorsSchemaNode);
+        } else {
+            responseBody = toXMLResponseBody(errorsNode, errorsSchemaNode);
         }
 
-        return Response.status( status ).type( mediaType ).entity( responseBody ).build();
+        return Response.status(status).type(mediaType).entity(responseBody).build();
     }
 
-    private Object toJsonResponseBody( final ImmutableCompositeNode errorsNode,
-            final DataNodeContainer errorsSchemaNode ) {
+    private Object toJsonResponseBody(final ImmutableCompositeNode errorsNode, final DataNodeContainer errorsSchemaNode) {
 
-        JsonMapper jsonMapper = new JsonMapper();
+        JsonMapper jsonMapper = new JsonMapper(null);
 
         Object responseBody = null;
         try {
             ByteArrayOutputStream outStream = new ByteArrayOutputStream();
-            JsonWriter writer = new JsonWriter( new OutputStreamWriter( outStream, "UTF-8" ) );
-            writer.setIndent( "    " );
+            JsonWriter writer = new JsonWriter(new OutputStreamWriter(outStream, Charsets.UTF_8));
+            writer.setIndent("    ");
 
-            jsonMapper.write( writer, errorsNode, errorsSchemaNode, null );
+            jsonMapper.write(writer, errorsNode, errorsSchemaNode);
             writer.flush();
 
-            responseBody = outStream.toString( "UTF-8" );
-        }
-        catch( IOException e ) {
-            LOG.error( "Error writing error response body", e );
+            responseBody = outStream.toString("UTF-8");
+        } catch (IOException e) {
+            LOG.error("Error writing error response body", e);
         }
 
         return responseBody;
     }
 
-    private Object toXMLResponseBody( final ImmutableCompositeNode errorsNode,
-            final DataNodeContainer errorsSchemaNode ) {
+    private Object toXMLResponseBody(final ImmutableCompositeNode errorsNode, final DataNodeContainer errorsSchemaNode) {
 
         XmlMapper xmlMapper = new XmlMapper();
 
         Object responseBody = null;
         try {
-            Document xmlDoc = xmlMapper.write( errorsNode, errorsSchemaNode );
+            Document xmlDoc = xmlMapper.write(errorsNode, errorsSchemaNode);
 
-            responseBody = documentToString( xmlDoc );
-        }
-        catch( TransformerException | UnsupportedDataTypeException | UnsupportedEncodingException e ) {
-            LOG.error( "Error writing error response body", e );
+            responseBody = documentToString(xmlDoc);
+        } catch (TransformerException | UnsupportedDataTypeException | UnsupportedEncodingException e) {
+            LOG.error("Error writing error response body", e);
         }
 
         return responseBody;
     }
 
-    private String documentToString( final Document doc ) throws TransformerException, UnsupportedEncodingException {
+    private String documentToString(final Document doc) throws TransformerException, UnsupportedEncodingException {
         Transformer transformer = createTransformer();
         ByteArrayOutputStream outStream = new ByteArrayOutputStream();
 
-        transformer.transform( new DOMSource( doc ), new StreamResult( outStream ) );
+        transformer.transform(new DOMSource(doc), new StreamResult(outStream));
 
-        return outStream.toString( "UTF-8" );
+        return outStream.toString("UTF-8");
     }
 
     private Transformer createTransformer() throws TransformerFactoryConfigurationError,
-    TransformerConfigurationException {
+            TransformerConfigurationException {
         TransformerFactory tf = TransformerFactory.newInstance();
         Transformer transformer = tf.newTransformer();
-        transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "no" );
-        transformer.setOutputProperty( OutputKeys.METHOD, "xml" );
-        transformer.setOutputProperty( OutputKeys.INDENT, "yes" );
-        transformer.setOutputProperty( OutputKeys.ENCODING, "UTF-8" );
-        transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", "4" );
+        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
+        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
+        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
+        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
         return transformer;
     }
 
-    private Node<?> toDomNode( final RestconfError error ) {
+    private Node<?> toDomNode(final RestconfError error) {
 
         CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
-        builder.setQName( ERROR_LIST_QNAME );
+        builder.setQName(ERROR_LIST_QNAME);
 
-        addLeaf( builder, ERROR_TYPE_QNAME, error.getErrorType().getErrorTypeTag() );
-        addLeaf( builder, ERROR_TAG_QNAME, error.getErrorTag().getTagValue() );
-        addLeaf( builder, ERROR_MESSAGE_QNAME, error.getErrorMessage() );
-        addLeaf( builder, ERROR_APP_TAG_QNAME, error.getErrorAppTag() );
+        addLeaf(builder, ERROR_TYPE_QNAME, error.getErrorType().getErrorTypeTag());
+        addLeaf(builder, ERROR_TAG_QNAME, error.getErrorTag().getTagValue());
+        addLeaf(builder, ERROR_MESSAGE_QNAME, error.getErrorMessage());
+        addLeaf(builder, ERROR_APP_TAG_QNAME, error.getErrorAppTag());
 
-        Node<?> errorInfoNode = parseErrorInfo( error.getErrorInfo() );
-        if( errorInfoNode != null ) {
-            builder.add( errorInfoNode );
+        Node<?> errorInfoNode = parseErrorInfo(error.getErrorInfo());
+        if (errorInfoNode != null) {
+            builder.add(errorInfoNode);
         }
 
         return builder.toInstance();
     }
 
-    private Node<?> parseErrorInfo( final String errorInfo ) {
-        if( Strings.isNullOrEmpty( errorInfo ) ) {
+    private Node<?> parseErrorInfo(final String errorInfo) {
+        if (Strings.isNullOrEmpty(errorInfo)) {
             return null;
         }
 
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
-        factory.setNamespaceAware( true );
-        factory.setCoalescing( true );
-        factory.setIgnoringElementContentWhitespace( true );
-        factory.setIgnoringComments( true );
+        factory.setNamespaceAware(true);
+        factory.setCoalescing(true);
+        factory.setIgnoringElementContentWhitespace(true);
+        factory.setIgnoringComments(true);
 
         // Wrap the error info content in a root <error-info> element so it can be parsed
         // as XML. The error info content may or may not be XML. If not then it will be
         // parsed as text content of the <error-info> element.
 
-        String errorInfoWithRoot =
-                new StringBuilder( "<error-info xmlns=\"" ).append( NAMESPACE ).append( "\">" )
-                .append( errorInfo ).append( "</error-info>" ).toString();
+        String errorInfoWithRoot = new StringBuilder("<error-info xmlns=\"").append(NAMESPACE).append("\">")
+                .append(errorInfo).append("</error-info>").toString();
 
         Document doc = null;
         try {
-            doc = factory.newDocumentBuilder().parse(
-                    new InputSource( new StringReader( errorInfoWithRoot ) ) );
-        }
-        catch( Exception e ) {
-            // TODO: what if the content is text that happens to contain invalid markup? Could
-            // wrap in CDATA and try again.
+            doc = factory.newDocumentBuilder().parse(new InputSource(new StringReader(errorInfoWithRoot)));
+        } catch (Exception e) {
+            // TODO: what if the content is text that happens to contain invalid markup?
+            // Could wrap in CDATA and try again.
 
-            LOG.warn( "Error parsing restconf error-info, \"" + errorInfo + "\", as XML: " +
-                    e.toString() );
+            LOG.warn("Error parsing restconf error-info, \"{}\", as XML", errorInfo, e);
             return null;
         }
 
-        Node<?> errorInfoNode = XmlDocumentUtils.toDomNode( doc );
+        Node<?> errorInfoNode = XmlDocumentUtils.toDomNode(doc);
 
-        if( errorInfoNode instanceof CompositeNode ) {
-            CompositeNode compositeNode = (CompositeNode)XmlDocumentUtils.toDomNode( doc );
+        if (errorInfoNode instanceof CompositeNode) {
+            CompositeNode compositeNode = (CompositeNode) XmlDocumentUtils.toDomNode(doc);
 
             // At this point the QName for the "error-info" CompositeNode doesn't contain the revision
             // as it isn't present in the XML. So we'll copy all the child nodes and create a new
@@ -260,20 +243,20 @@ public class RestconfDocumentedExceptionMapper implements ExceptionMapper<Restco
             // locate the schema.
 
             ImmutableList.Builder<Node<?>> childNodes = ImmutableList.builder();
-            for( Entry<QName, List<Node<?>>> entry: compositeNode.entrySet() ) {
-                childNodes.addAll( entry.getValue() );
+            for (Entry<QName, List<Node<?>>> entry : compositeNode.entrySet()) {
+                childNodes.addAll(entry.getValue());
             }
 
-            errorInfoNode = ImmutableCompositeNode.create( ERROR_INFO_QNAME, childNodes.build() );
+            errorInfoNode = ImmutableCompositeNode.create(ERROR_INFO_QNAME, childNodes.build());
         }
 
         return errorInfoNode;
     }
 
-    private void addLeaf( final CompositeNodeBuilder<ImmutableCompositeNode> builder, final QName qname,
-            final String value ) {
-        if( !Strings.isNullOrEmpty( value ) ) {
-            builder.addLeaf( qname, value );
+    private void addLeaf(final CompositeNodeBuilder<ImmutableCompositeNode> builder, final QName qname,
+            final String value) {
+        if (!Strings.isNullOrEmpty(value)) {
+            builder.addLeaf(qname, value);
         }
     }
 }
index 2abd4b6a3ab5b9a08c56e782257a262db80fbfe2..1f1d0eb83147533d1171a4e81a36a73d7f72acd0 100644 (file)
@@ -9,7 +9,6 @@ package org.opendaylight.controller.sal.rest.impl;
 
 import java.util.Collection;
 import java.util.Collections;
-
 import org.opendaylight.controller.sal.core.api.Broker;
 import org.opendaylight.controller.sal.core.api.Broker.ProviderSession;
 import org.opendaylight.controller.sal.core.api.Provider;
@@ -51,12 +50,15 @@ public class RestconfProvider implements BundleActivator, Provider, ServiceTrack
 
     @Override
     public void start(BundleContext context) throws Exception {
+        String websocketPortStr = context.getProperty(WebSocketServer.WEBSOCKET_SERVER_CONFIG_PROPERTY);
+        int websocketPort = (websocketPortStr != null && !"".equals(websocketPortStr)) ? Integer
+                .parseInt(websocketPortStr) : WebSocketServer.DEFAULT_PORT;
         bundleContext = context;
-        brokerServiceTrancker = new ServiceTracker<>(context, Broker.class, this);
-        brokerServiceTrancker.open();
-        webSocketServerThread = new Thread(new WebSocketServer());
+        webSocketServerThread = new Thread(WebSocketServer.createInstance(websocketPort));
         webSocketServerThread.setName("Web socket server");
         webSocketServerThread.start();
+        brokerServiceTrancker = new ServiceTracker<>(context, Broker.class, this);
+        brokerServiceTrancker.open();
     }
 
     @Override
index 422cf04cca82f7d0bf5d2f535df40a6f7688215e..933ed0f849e7171b7c16c423c5462aa8de1bb25a 100644 (file)
@@ -7,12 +7,13 @@
  */
 package org.opendaylight.controller.sal.rest.impl;
 
+import com.google.common.base.Charsets;
+import com.google.gson.stream.JsonWriter;
 import java.io.IOException;
 import java.io.OutputStream;
 import java.io.OutputStreamWriter;
 import java.lang.annotation.Annotation;
 import java.lang.reflect.Type;
-
 import javax.ws.rs.Produces;
 import javax.ws.rs.WebApplicationException;
 import javax.ws.rs.core.MediaType;
@@ -20,7 +21,6 @@ import javax.ws.rs.core.MultivaluedMap;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.ext.MessageBodyWriter;
 import javax.ws.rs.ext.Provider;
-
 import org.opendaylight.controller.sal.rest.api.Draft02;
 import org.opendaylight.controller.sal.rest.api.RestconfService;
 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
@@ -28,8 +28,6 @@ import org.opendaylight.controller.sal.restconf.impl.StructuredData;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 
-import com.google.gson.stream.JsonWriter;
-
 @Provider
 @Produces({ Draft02.MediaTypes.API + RestconfService.JSON, Draft02.MediaTypes.DATA + RestconfService.JSON,
         Draft02.MediaTypes.OPERATION + RestconfService.JSON, MediaType.APPLICATION_JSON })
@@ -37,29 +35,36 @@ public enum StructuredDataToJsonProvider implements MessageBodyWriter<Structured
     INSTANCE;
 
     @Override
-    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
-        return type.equals( StructuredData.class );
+    public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations,
+            final MediaType mediaType) {
+        return type.equals(StructuredData.class);
     }
 
     @Override
-    public long getSize(StructuredData t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
+    public long getSize(final StructuredData t, final Class<?> type, final Type genericType,
+            final Annotation[] annotations, final MediaType mediaType) {
         return -1;
     }
 
     @Override
-    public void writeTo(StructuredData t, Class<?> type, Type genericType, Annotation[] annotations,
-            MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
-            throws IOException, WebApplicationException {
+    public void writeTo(final StructuredData t, final Class<?> type, final Type genericType,
+            final Annotation[] annotations, final MediaType mediaType,
+            final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException,
+            WebApplicationException {
         CompositeNode data = t.getData();
         if (data == null) {
             throw new RestconfDocumentedException(Response.Status.NOT_FOUND);
         }
 
-        JsonWriter writer = new JsonWriter(new OutputStreamWriter(entityStream, "UTF-8"));
-        writer.setIndent("    ");
-        JsonMapper jsonMapper = new JsonMapper();
-        jsonMapper.write(writer, data, (DataNodeContainer) t.getSchema(), t.getMountPoint());
+        JsonWriter writer = new JsonWriter(new OutputStreamWriter(entityStream, Charsets.UTF_8));
+
+        if (t.isPrettyPrintMode()) {
+            writer.setIndent("    ");
+        } else {
+            writer.setIndent("");
+        }
+        JsonMapper jsonMapper = new JsonMapper(t.getMountPoint());
+        jsonMapper.write(writer, data, (DataNodeContainer) t.getSchema());
         writer.flush();
     }
-
 }
index bcb3c422ff8dc0c33c8a44d27d20b63ec1e3852d..703a2a463476bcfd4704c34419cc17c73a6af3fc 100644 (file)
@@ -11,7 +11,6 @@ import java.io.IOException;
 import java.io.OutputStream;
 import java.lang.annotation.Annotation;
 import java.lang.reflect.Type;
-
 import javax.ws.rs.Produces;
 import javax.ws.rs.WebApplicationException;
 import javax.ws.rs.core.MediaType;
@@ -21,11 +20,11 @@ import javax.ws.rs.ext.MessageBodyWriter;
 import javax.ws.rs.ext.Provider;
 import javax.xml.transform.OutputKeys;
 import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerConfigurationException;
 import javax.xml.transform.TransformerException;
 import javax.xml.transform.TransformerFactory;
 import javax.xml.transform.dom.DOMSource;
 import javax.xml.transform.stream.StreamResult;
-
 import org.opendaylight.controller.sal.rest.api.Draft02;
 import org.opendaylight.controller.sal.rest.api.RestconfService;
 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
@@ -44,42 +43,70 @@ import org.w3c.dom.Document;
 public enum StructuredDataToXmlProvider implements MessageBodyWriter<StructuredData> {
     INSTANCE;
 
-    private final static Logger logger = LoggerFactory.getLogger(StructuredDataToXmlProvider.class);
+    private static final Logger LOG = LoggerFactory.getLogger(StructuredDataToXmlProvider.class);
+    private static final TransformerFactory FACTORY = TransformerFactory.newInstance();
+    private static final ThreadLocal<Transformer> TRANSFORMER = new ThreadLocal<Transformer>() {
+        @Override
+        protected Transformer initialValue() {
+            final Transformer ret;
+            try {
+                ret = FACTORY.newTransformer();
+            } catch (TransformerConfigurationException e) {
+                LOG.error("Failed to instantiate XML transformer", e);
+                throw new IllegalStateException("XML encoding currently unavailable", e);
+            }
+
+            ret.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
+            ret.setOutputProperty(OutputKeys.METHOD, "xml");
+            ret.setOutputProperty(OutputKeys.INDENT, "yes");
+            ret.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
+            ret.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
+
+            return ret;
+        }
+    };
 
     @Override
-    public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
-        return type.equals( StructuredData.class );
+    public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations,
+            final MediaType mediaType) {
+        return type.equals(StructuredData.class);
     }
 
     @Override
-    public long getSize(StructuredData t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
+    public long getSize(final StructuredData t, final Class<?> type, final Type genericType,
+            final Annotation[] annotations, final MediaType mediaType) {
         return -1;
     }
 
     @Override
-    public void writeTo(StructuredData t, Class<?> type, Type genericType, Annotation[] annotations,
-            MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
-            throws IOException, WebApplicationException {
+    public void writeTo(final StructuredData t, final Class<?> type, final Type genericType,
+            final Annotation[] annotations, final MediaType mediaType,
+            final MultivaluedMap<String, Object> httpHeaders, final OutputStream entityStream) throws IOException,
+            WebApplicationException {
         CompositeNode data = t.getData();
         if (data == null) {
             throw new RestconfDocumentedException(Response.Status.NOT_FOUND);
         }
 
-        XmlMapper xmlMapper = new XmlMapper();
-        Document domTree = xmlMapper.write(data, (DataNodeContainer) t.getSchema());
+        final Transformer trans;
+        try {
+            trans = TRANSFORMER.get();
+            if (t.isPrettyPrintMode()) {
+                trans.setOutputProperty(OutputKeys.INDENT, "yes");
+            } else {
+                trans.setOutputProperty(OutputKeys.INDENT, "no");
+            }
+        } catch (RuntimeException e) {
+            throw new RestconfDocumentedException(e.getMessage(), ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED);
+        }
+
+        // FIXME: BUG-1281: eliminate the intermediate Document
+        final Document domTree = new XmlMapper().write(data, (DataNodeContainer) t.getSchema());
         try {
-            TransformerFactory tf = TransformerFactory.newInstance();
-            Transformer transformer = tf.newTransformer();
-            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
-            transformer.setOutputProperty(OutputKeys.METHOD, "xml");
-            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
-            transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
-            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
-            transformer.transform(new DOMSource(domTree), new StreamResult(entityStream));
+            trans.transform(new DOMSource(domTree), new StreamResult(entityStream));
         } catch (TransformerException e) {
-            logger.error("Error during translation of Document to OutputStream", e);
-            throw new RestconfDocumentedException( e.getMessage(), ErrorType.TRANSPORT,
-                                                   ErrorTag.OPERATION_FAILED );
+            LOG.error("Error during translation of Document to OutputStream", e);
+            throw new RestconfDocumentedException(e.getMessage(), ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED);
         }
     }
 
index e76e1962a058bea7c0bdb8a22b6a2c7285e785cd..b0b2cc5e2f0898dd0bc0d7572ec480884b3f9308 100644 (file)
@@ -7,8 +7,8 @@
  */
 package org.opendaylight.controller.sal.rest.impl;
 
+import com.google.common.base.Optional;
 import javax.activation.UnsupportedDataTypeException;
-
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.codec.LeafrefCodec;
 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
@@ -20,8 +20,6 @@ import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
 import org.opendaylight.yangtools.yang.model.util.Leafref;
 import org.w3c.dom.Document;
 
-import com.google.common.base.Optional;
-
 public class XmlMapper {
     private static final LeafrefCodecImpl LEAFREF_DEFAULT_CODEC = new LeafrefCodecImpl(
             Optional.<LeafrefTypeDefinition> absent());
index bc7473864cbb3ffa553c78fbf8a96fb64a7dad6d..31e9c96462541e75205d9ef9c6aac9508abc6e43 100644 (file)
@@ -11,7 +11,6 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.lang.annotation.Annotation;
 import java.lang.reflect.Type;
-
 import javax.ws.rs.Consumes;
 import javax.ws.rs.WebApplicationException;
 import javax.ws.rs.core.MediaType;
@@ -19,7 +18,6 @@ import javax.ws.rs.core.MultivaluedMap;
 import javax.ws.rs.ext.MessageBodyReader;
 import javax.ws.rs.ext.Provider;
 import javax.xml.stream.XMLStreamException;
-
 import org.opendaylight.controller.sal.rest.api.Draft02;
 import org.opendaylight.controller.sal.rest.api.RestconfService;
 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
@@ -35,7 +33,7 @@ import org.slf4j.LoggerFactory;
 public enum XmlToCompositeNodeProvider implements MessageBodyReader<CompositeNode> {
     INSTANCE;
 
-    private final static Logger LOG = LoggerFactory.getLogger( XmlToCompositeNodeProvider.class );
+    private final static Logger LOG = LoggerFactory.getLogger(XmlToCompositeNodeProvider.class);
 
     @Override
     public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
@@ -46,14 +44,13 @@ public enum XmlToCompositeNodeProvider implements MessageBodyReader<CompositeNod
     public CompositeNode readFrom(Class<CompositeNode> type, Type genericType, Annotation[] annotations,
             MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
             throws IOException, WebApplicationException {
-        XmlReader xmlReader = new XmlReader();
+        XmlToCompositeNodeReader xmlReader = new XmlToCompositeNodeReader();
         try {
             return xmlReader.read(entityStream);
         } catch (XMLStreamException | UnsupportedFormatException e) {
-            LOG.debug( "Error parsing json input", e );
-            throw new RestconfDocumentedException(
-                            "Error parsing input: " + e.getMessage(),
-                            ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE );
+            LOG.debug("Error parsing json input", e);
+            throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
+                    ErrorTag.MALFORMED_MESSAGE);
         }
     }
 
@@ -28,19 +28,18 @@ import org.opendaylight.controller.sal.restconf.impl.NodeWrapper;
 import org.opendaylight.controller.sal.restconf.impl.SimpleNodeWrapper;
 import org.opendaylight.yangtools.yang.data.api.Node;
 
-public class XmlReader {
+public class XmlToCompositeNodeReader {
 
     private final static XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
     private XMLEventReader eventReader;
 
-    public CompositeNodeWrapper read(InputStream entityStream) throws XMLStreamException,
-                                                                      UnsupportedFormatException,
-                                                                      IOException {
-        //Get an XML stream which can be marked, and reset, so we can check and see if there is
-        //any content being provided.
+    public CompositeNodeWrapper read(InputStream entityStream) throws XMLStreamException, UnsupportedFormatException,
+            IOException {
+        // Get an XML stream which can be marked, and reset, so we can check and
+        // see if there is any content being provided.
         entityStream = getMarkableStream(entityStream);
 
-        if( isInputStreamEmpty( entityStream ) ) {
+        if (isInputStreamEmpty(entityStream)) {
             return null;
         }
 
@@ -103,24 +102,23 @@ public class XmlReader {
     }
 
     /**
-     * If the input stream is not markable, then it wraps the input stream with a buffered stream,
-     * which is mark able. That way we can check if the stream is empty safely.
+     * If the input stream is not markable, then it wraps the input stream with a buffered stream, which is mark able.
+     * That way we can check if the stream is empty safely.
+     *
      * @param entityStream
      * @return
      */
     private InputStream getMarkableStream(InputStream entityStream) {
-        if( !entityStream.markSupported() )
-        {
-            entityStream = new BufferedInputStream( entityStream );
+        if (!entityStream.markSupported()) {
+            entityStream = new BufferedInputStream(entityStream);
         }
         return entityStream;
     }
 
-    private boolean isInputStreamEmpty(InputStream entityStream)
-            throws IOException {
+    private boolean isInputStreamEmpty(InputStream entityStream) throws IOException {
         boolean isEmpty = false;
-        entityStream.mark( 1 );
-        if( entityStream.read() == -1 ){
+        entityStream.mark(1);
+        if (entityStream.read() == -1) {
             isEmpty = true;
         }
         entityStream.reset();
@@ -131,7 +129,7 @@ public class XmlReader {
         checkArgument(event != null, "XML Event cannot be NULL!");
         if (event.isStartElement()) {
             XMLEvent innerEvent = skipCommentsAndWhitespace();
-            if ( innerEvent != null && (innerEvent.isCharacters() || innerEvent.isEndElement())) {
+            if (innerEvent != null && (innerEvent.isCharacters() || innerEvent.isEndElement())) {
                 return true;
             }
         }
@@ -142,7 +140,7 @@ public class XmlReader {
         checkArgument(event != null, "XML Event cannot be NULL!");
         if (event.isStartElement()) {
             XMLEvent innerEvent = skipCommentsAndWhitespace();
-            if( innerEvent != null ) {
+            if (innerEvent != null) {
                 if (innerEvent.isStartElement()) {
                     return true;
                 }
@@ -152,16 +150,16 @@ public class XmlReader {
     }
 
     private XMLEvent skipCommentsAndWhitespace() throws XMLStreamException {
-        while( eventReader.hasNext() ) {
+        while (eventReader.hasNext()) {
             XMLEvent event = eventReader.peek();
-            if( event.getEventType() == XMLStreamConstants.COMMENT ) {
+            if (event.getEventType() == XMLStreamConstants.COMMENT) {
                 eventReader.nextEvent();
                 continue;
             }
 
-            if( event.isCharacters() ) {
+            if (event.isCharacters()) {
                 Characters chars = event.asCharacters();
-                if( chars.isWhiteSpace() ) {
+                if (chars.isWhiteSpace()) {
                     eventReader.nextEvent();
                     continue;
                 }
@@ -235,7 +233,8 @@ public class XmlReader {
     private Object resolveValueOfElement(String value, StartElement startElement) {
         // it could be instance-identifier Built-In Type
         if (value.startsWith("/")) {
-            IdentityValuesDTO iiValue = RestUtil.asInstanceIdentifier(value, new RestUtil.PrefixMapingFromXml(startElement));
+            IdentityValuesDTO iiValue = RestUtil.asInstanceIdentifier(value, new RestUtil.PrefixMapingFromXml(
+                    startElement));
             if (iiValue != null) {
                 return iiValue;
             }
@@ -245,7 +244,7 @@ public class XmlReader {
         if (namespaceAndValue.length == 2) {
             String namespace = startElement.getNamespaceContext().getNamespaceURI(namespaceAndValue[0]);
             if (namespace != null && !namespace.isEmpty()) {
-                return new IdentityValuesDTO(namespace, namespaceAndValue[1], namespaceAndValue[0],value);
+                return new IdentityValuesDTO(namespace, namespaceAndValue[1], namespaceAndValue[0], value);
             }
         }
         // it is not "prefix:value" but just "value"
index 62afdbd10df31df5f5a577f3520dec8ab8b59dcd..9560333e711b3e56224f5ca7dab6118bedcb6d7a 100644 (file)
@@ -5,4 +5,4 @@
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
-package org.opendaylight.controller.sal.rest.impl;
+package org.opendaylight.controller.sal.rest.impl;
\ No newline at end of file
index 062d03a49f56e12ca6bb178fa39303b78fc059da..ead1740ffd8befb557d85688b4a443f7edfd1134 100644 (file)
@@ -7,6 +7,8 @@
  */
 package org.opendaylight.controller.sal.restconf.impl;
 
+import com.google.common.util.concurrent.Futures;
+
 import java.util.concurrent.Future;
 
 import javax.ws.rs.core.Response.Status;
@@ -24,13 +26,14 @@ import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
 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.InstanceIdentifier;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 public class BrokerFacade implements DataReader<InstanceIdentifier, CompositeNode> {
-    private final static Logger LOG = LoggerFactory.getLogger( BrokerFacade.class );
+    private final static Logger LOG = LoggerFactory.getLogger(BrokerFacade.class);
 
     private final static BrokerFacade INSTANCE = new BrokerFacade();
 
@@ -40,11 +43,11 @@ public class BrokerFacade implements DataReader<InstanceIdentifier, CompositeNod
     private BrokerFacade() {
     }
 
-    public void setContext( final ConsumerSession context ) {
+    public void setContext(final ConsumerSession context) {
         this.context = context;
     }
 
-    public void setDataService( final DataBrokerService dataService ) {
+    public void setDataService(final DataBrokerService dataService) {
         this.dataService = dataService;
     }
 
@@ -53,141 +56,145 @@ public class BrokerFacade implements DataReader<InstanceIdentifier, CompositeNod
     }
 
     private void checkPreconditions() {
-        if( context == null || dataService == null ) {
-            throw new RestconfDocumentedException( Status.SERVICE_UNAVAILABLE );
+        if (context == null || dataService == null) {
+            throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
         }
     }
 
     @Override
-    public CompositeNode readConfigurationData( final InstanceIdentifier path ) {
+    public CompositeNode readConfigurationData(final InstanceIdentifier path) {
         this.checkPreconditions();
 
-        LOG.trace( "Read Configuration via Restconf: {}", path );
+        LOG.trace("Read Configuration via Restconf: {}", path);
 
-        return dataService.readConfigurationData( path );
+        return dataService.readConfigurationData(path);
     }
 
-    public CompositeNode readConfigurationDataBehindMountPoint( final MountInstance mountPoint,
-                                                                final InstanceIdentifier path ) {
+    public CompositeNode readConfigurationDataBehindMountPoint(final MountInstance mountPoint,
+            final InstanceIdentifier path) {
         this.checkPreconditions();
 
-        LOG.trace( "Read Configuration via Restconf: {}", path );
+        LOG.trace("Read Configuration via Restconf: {}", path);
 
-        return mountPoint.readConfigurationData( path );
+        return mountPoint.readConfigurationData(path);
     }
 
     @Override
-    public CompositeNode readOperationalData( final InstanceIdentifier path ) {
+    public CompositeNode readOperationalData(final InstanceIdentifier path) {
         this.checkPreconditions();
 
-        BrokerFacade.LOG.trace( "Read Operational via Restconf: {}", path );
+        BrokerFacade.LOG.trace("Read Operational via Restconf: {}", path);
 
-        return dataService.readOperationalData( path );
+        return dataService.readOperationalData(path);
     }
 
-    public CompositeNode readOperationalDataBehindMountPoint( final MountInstance mountPoint,
-                                                              final InstanceIdentifier path ) {
+    public CompositeNode readOperationalDataBehindMountPoint(final MountInstance mountPoint,
+            final InstanceIdentifier path) {
         this.checkPreconditions();
 
-        BrokerFacade.LOG.trace( "Read Operational via Restconf: {}", path );
+        BrokerFacade.LOG.trace("Read Operational via Restconf: {}", path);
 
-        return mountPoint.readOperationalData( path );
+        return mountPoint.readOperationalData(path);
     }
 
-    public Future<RpcResult<CompositeNode>> invokeRpc( final QName type, final CompositeNode payload ) {
+    public Future<RpcResult<CompositeNode>> invokeRpc(final QName type, final CompositeNode payload) {
         this.checkPreconditions();
 
-        return context.rpc( type, payload );
+        return context.rpc(type, payload);
     }
 
-    public Future<RpcResult<TransactionStatus>> commitConfigurationDataPut( final InstanceIdentifier path,
-                                                                            final CompositeNode payload ) {
+    public Future<RpcResult<TransactionStatus>> commitConfigurationDataPut(final InstanceIdentifier path,
+            final CompositeNode payload) {
         this.checkPreconditions();
 
         final DataModificationTransaction transaction = dataService.beginTransaction();
-        BrokerFacade.LOG.trace( "Put Configuration via Restconf: {}", path );
-        transaction.putConfigurationData( path, payload );
+        BrokerFacade.LOG.trace("Put Configuration via Restconf: {}", path);
+        transaction.putConfigurationData(path, payload);
         return transaction.commit();
     }
 
     public Future<RpcResult<TransactionStatus>> commitConfigurationDataPutBehindMountPoint(
-            final MountInstance mountPoint, final InstanceIdentifier path, final CompositeNode payload ) {
+            final MountInstance mountPoint, final InstanceIdentifier path, final CompositeNode payload) {
         this.checkPreconditions();
 
         final DataModificationTransaction transaction = mountPoint.beginTransaction();
-        BrokerFacade.LOG.trace( "Put Configuration via Restconf: {}", path );
-        transaction.putConfigurationData( path, payload );
+        BrokerFacade.LOG.trace("Put Configuration via Restconf: {}", path);
+        transaction.putConfigurationData(path, payload);
         return transaction.commit();
     }
 
-    public Future<RpcResult<TransactionStatus>> commitConfigurationDataPost( final InstanceIdentifier path,
-                                                                             final CompositeNode payload) {
+    public Future<RpcResult<TransactionStatus>> commitConfigurationDataPost(final InstanceIdentifier path,
+            final CompositeNode payload) {
         this.checkPreconditions();
 
         final DataModificationTransaction transaction = dataService.beginTransaction();
         /* check for available Node in Configuration DataStore by path */
-        CompositeNode availableNode = transaction.readConfigurationData( path );
+        CompositeNode availableNode = transaction.readConfigurationData(path);
         if (availableNode != null) {
             String errMsg = "Post Configuration via Restconf was not executed because data already exists";
             BrokerFacade.LOG.warn((new StringBuilder(errMsg)).append(" : ").append(path).toString());
 
-            throw new RestconfDocumentedException(
-                    "Data already exists for path: " + path, ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS );
+            throw new RestconfDocumentedException("Data already exists for path: " + path, ErrorType.PROTOCOL,
+                    ErrorTag.DATA_EXISTS);
         }
-        BrokerFacade.LOG.trace( "Post Configuration via Restconf: {}", path );
-        transaction.putConfigurationData( path, payload );
+        BrokerFacade.LOG.trace("Post Configuration via Restconf: {}", path);
+        transaction.putConfigurationData(path, payload);
         return transaction.commit();
     }
 
     public Future<RpcResult<TransactionStatus>> commitConfigurationDataPostBehindMountPoint(
-            final MountInstance mountPoint, final InstanceIdentifier path, final CompositeNode payload ) {
+            final MountInstance mountPoint, final InstanceIdentifier path, final CompositeNode payload) {
         this.checkPreconditions();
 
         final DataModificationTransaction transaction = mountPoint.beginTransaction();
         /* check for available Node in Configuration DataStore by path */
-        CompositeNode availableNode = transaction.readConfigurationData( path );
+        CompositeNode availableNode = transaction.readConfigurationData(path);
         if (availableNode != null) {
             String errMsg = "Post Configuration via Restconf was not executed because data already exists";
             BrokerFacade.LOG.warn((new StringBuilder(errMsg)).append(" : ").append(path).toString());
 
-            throw new RestconfDocumentedException(
-                    "Data already exists for path: " + path, ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS );
+            throw new RestconfDocumentedException("Data already exists for path: " + path, ErrorType.PROTOCOL,
+                    ErrorTag.DATA_EXISTS);
         }
-        BrokerFacade.LOG.trace( "Post Configuration via Restconf: {}", path );
-        transaction.putConfigurationData( path, payload );
+        BrokerFacade.LOG.trace("Post Configuration via Restconf: {}", path);
+        transaction.putConfigurationData(path, payload);
         return transaction.commit();
     }
 
-    public Future<RpcResult<TransactionStatus>> commitConfigurationDataDelete( final InstanceIdentifier path ) {
+    public Future<RpcResult<TransactionStatus>> commitConfigurationDataDelete(final InstanceIdentifier path) {
         this.checkPreconditions();
-
-        final DataModificationTransaction transaction = dataService.beginTransaction();
-        LOG.info( "Delete Configuration via Restconf: {}", path );
-        transaction.removeConfigurationData( path );
-        return transaction.commit();
+        return deleteDataAtTarget(path, dataService.beginTransaction());
     }
 
     public Future<RpcResult<TransactionStatus>> commitConfigurationDataDeleteBehindMountPoint(
-                                          final MountInstance mountPoint, final InstanceIdentifier path ) {
+            final MountInstance mountPoint, final InstanceIdentifier path) {
         this.checkPreconditions();
+        return deleteDataAtTarget(path, mountPoint.beginTransaction());
+    }
 
-        final DataModificationTransaction transaction = mountPoint.beginTransaction();
-        LOG.info( "Delete Configuration via Restconf: {}", path );
-        transaction.removeConfigurationData( path );
+    private Future<RpcResult<TransactionStatus>> deleteDataAtTarget(final InstanceIdentifier path,
+            final DataModificationTransaction transaction) {
+        LOG.info("Delete Configuration via Restconf: {}", path);
+        CompositeNode redDataAtPath = transaction.readConfigurationData(path);
+        if (redDataAtPath == null) {
+            return Futures.immediateFuture(RpcResultBuilder.<TransactionStatus>
+                                                    success(TransactionStatus.COMMITED).build());
+        }
+        transaction.removeConfigurationData(path);
         return transaction.commit();
     }
 
-    public void registerToListenDataChanges( final ListenerAdapter listener ) {
+    public void registerToListenDataChanges(final ListenerAdapter listener) {
         this.checkPreconditions();
 
-        if( listener.isListening() ) {
+        if (listener.isListening()) {
             return;
         }
 
         InstanceIdentifier path = listener.getPath();
-        final ListenerRegistration<DataChangeListener> registration =
-                                             dataService.registerDataChangeListener( path, listener );
+        final ListenerRegistration<DataChangeListener> registration = dataService.registerDataChangeListener(path,
+                listener);
 
-        listener.setRegistration( registration );
+        listener.setRegistration(registration);
     }
 }
index 96ad528a0dd3f9e0591b78b2be702e9b1d004c4c..206dbdeab60a20dff4d13f9fbd3c96c68ac45b4d 100644 (file)
@@ -7,6 +7,7 @@
  */
 package org.opendaylight.controller.sal.restconf.impl;
 
+import com.google.common.base.Preconditions;
 import java.net.URI;
 import java.util.ArrayList;
 import java.util.Collection;
@@ -14,7 +15,6 @@ import java.util.Collections;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
@@ -23,8 +23,6 @@ import org.opendaylight.yangtools.yang.data.api.Node;
 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
 
-import com.google.common.base.Preconditions;
-
 public final class CompositeNodeWrapper implements NodeWrapper<CompositeNode>, CompositeNode {
 
     private MutableCompositeNode compositeNode;
@@ -104,7 +102,7 @@ public final class CompositeNodeWrapper implements NodeWrapper<CompositeNode>, C
                 name = new QName(namespace, localName);
             }
 
-            List<Node<?>> nodeValues = new ArrayList<>();
+            List<Node<?>> nodeValues = new ArrayList<>(values.size());
             for (NodeWrapper<?> nodeWrapper : values) {
                 nodeValues.add(nodeWrapper.unwrap());
             }
index b0916f4500d65d9dfb3291f4435e7c2aad31cc1b..29672f39d47c4222b297972be5b1dbeef3f1d6fe 100644 (file)
@@ -7,6 +7,17 @@
  */
 package org.opendaylight.controller.sal.restconf.impl;
 
+import com.google.common.base.Function;
+import com.google.common.base.Objects;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Predicate;
+import com.google.common.base.Splitter;
+import com.google.common.base.Strings;
+import com.google.common.collect.BiMap;
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.HashBiMap;
+import com.google.common.collect.Iterables;
 import java.io.UnsupportedEncodingException;
 import java.net.URI;
 import java.net.URLDecoder;
@@ -20,9 +31,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
-
 import javax.ws.rs.core.Response.Status;
-
 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
 import org.opendaylight.controller.sal.core.api.mount.MountService;
 import org.opendaylight.controller.sal.rest.api.Draft02;
@@ -36,6 +45,7 @@ import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.InstanceIdent
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
@@ -54,21 +64,8 @@ import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Function;
-import com.google.common.base.Objects;
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Predicate;
-import com.google.common.base.Splitter;
-import com.google.common.base.Strings;
-import com.google.common.collect.BiMap;
-import com.google.common.collect.FluentIterable;
-import com.google.common.collect.HashBiMap;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-
 public class ControllerContext implements SchemaContextListener {
-    private final static Logger LOG = LoggerFactory.getLogger( ControllerContext.class );
+    private final static Logger LOG = LoggerFactory.getLogger(ControllerContext.class);
 
     private final static ControllerContext INSTANCE = new ControllerContext();
 
@@ -82,6 +79,10 @@ public class ControllerContext implements SchemaContextListener {
 
     private final static String URI_ENCODING_CHAR_SET = "ISO-8859-1";
 
+    private static final Splitter SLASH_SPLITTER = Splitter.on('/');
+
+    private static final Splitter COLON_SPLITTER = Splitter.on(':');
+
     private final BiMap<URI, String> uriToModuleName = HashBiMap.<URI, String> create();
 
     private final Map<String, URI> moduleNameToUri = uriToModuleName.inverse();
@@ -91,11 +92,11 @@ public class ControllerContext implements SchemaContextListener {
     private volatile SchemaContext globalSchema;
     private volatile MountService mountService;
 
-    public void setGlobalSchema( final SchemaContext globalSchema ) {
+    public void setGlobalSchema(final SchemaContext globalSchema) {
         this.globalSchema = globalSchema;
     }
 
-    public void setMountService( final MountService mountService ) {
+    public void setMountService(final MountService mountService) {
         this.mountService = mountService;
     }
 
@@ -107,164 +108,157 @@ public class ControllerContext implements SchemaContextListener {
     }
 
     private void checkPreconditions() {
-        if( globalSchema == null ) {
-            throw new RestconfDocumentedException( Status.SERVICE_UNAVAILABLE );
+        if (globalSchema == null) {
+            throw new RestconfDocumentedException(Status.SERVICE_UNAVAILABLE);
         }
     }
 
-    public void setSchemas( final SchemaContext schemas ) {
-        this.onGlobalContextUpdated( schemas );
+    public void setSchemas(final SchemaContext schemas) {
+        this.onGlobalContextUpdated(schemas);
     }
 
-    public InstanceIdWithSchemaNode toInstanceIdentifier( final String restconfInstance ) {
-        return this.toIdentifier( restconfInstance, false );
+    public InstanceIdWithSchemaNode toInstanceIdentifier(final String restconfInstance) {
+        return this.toIdentifier(restconfInstance, false);
     }
 
-    public InstanceIdWithSchemaNode toMountPointIdentifier( final String restconfInstance ) {
-        return this.toIdentifier( restconfInstance, true );
+    public InstanceIdWithSchemaNode toMountPointIdentifier(final String restconfInstance) {
+        return this.toIdentifier(restconfInstance, true);
     }
 
-    private InstanceIdWithSchemaNode toIdentifier( final String restconfInstance,
-            final boolean toMountPointIdentifier ) {
+    private InstanceIdWithSchemaNode toIdentifier(final String restconfInstance, final boolean toMountPointIdentifier) {
         this.checkPreconditions();
 
-        Iterable<String> split = Splitter.on( "/" ).split( restconfInstance );
-        final ArrayList<String> encodedPathArgs = Lists.<String> newArrayList( split );
-        final List<String> pathArgs = this.urlPathArgsDecode( encodedPathArgs );
-        this.omitFirstAndLastEmptyString( pathArgs );
-        if( pathArgs.isEmpty() ) {
+        final List<String> pathArgs = urlPathArgsDecode(SLASH_SPLITTER.split(restconfInstance));
+        omitFirstAndLastEmptyString(pathArgs);
+        if (pathArgs.isEmpty()) {
             return null;
         }
 
         String first = pathArgs.iterator().next();
-        final String startModule = ControllerContext.toModuleName( first );
-        if( startModule == null ) {
-            throw new RestconfDocumentedException(
-                    "First node in URI has to be in format \"moduleName:nodeName\"",
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+        final String startModule = ControllerContext.toModuleName(first);
+        if (startModule == null) {
+            throw new RestconfDocumentedException("First node in URI has to be in format \"moduleName:nodeName\"",
+                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
         InstanceIdentifierBuilder builder = InstanceIdentifier.builder();
-        Module latestModule = this.getLatestModule( globalSchema, startModule );
-        InstanceIdWithSchemaNode iiWithSchemaNode = this.collectPathArguments( builder, pathArgs,
-                latestModule, null, toMountPointIdentifier );
+        Module latestModule = this.getLatestModule(globalSchema, startModule);
+        InstanceIdWithSchemaNode iiWithSchemaNode = this.collectPathArguments(builder, pathArgs, latestModule, null,
+                toMountPointIdentifier);
 
-        if( iiWithSchemaNode == null ) {
-            throw new RestconfDocumentedException(
-                    "URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+        if (iiWithSchemaNode == null) {
+            throw new RestconfDocumentedException("URI has bad format", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
         return iiWithSchemaNode;
     }
 
-    private List<String> omitFirstAndLastEmptyString( final List<String> list ) {
-        if( list.isEmpty() ) {
+    private static List<String> omitFirstAndLastEmptyString(final List<String> list) {
+        if (list.isEmpty()) {
             return list;
         }
 
         String head = list.iterator().next();
-        if( head.isEmpty() ) {
-            list.remove( 0 );
+        if (head.isEmpty()) {
+            list.remove(0);
         }
 
-        if( list.isEmpty() ) {
+        if (list.isEmpty()) {
             return list;
         }
 
-        String last = list.get( list.size() - 1 );
-        if( last.isEmpty() ) {
-            list.remove( list.size() - 1 );
+        String last = list.get(list.size() - 1);
+        if (last.isEmpty()) {
+            list.remove(list.size() - 1);
         }
 
         return list;
     }
 
-    private Module getLatestModule( final SchemaContext schema, final String moduleName ) {
-        Preconditions.checkArgument( schema != null );
-        Preconditions.checkArgument( moduleName != null && !moduleName.isEmpty() );
+    private Module getLatestModule(final SchemaContext schema, final String moduleName) {
+        Preconditions.checkArgument(schema != null);
+        Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
 
         Predicate<Module> filter = new Predicate<Module>() {
             @Override
-            public boolean apply( final Module m ) {
-                return Objects.equal( m.getName(), moduleName );
+            public boolean apply(final Module m) {
+                return Objects.equal(m.getName(), moduleName);
             }
         };
 
-        Iterable<Module> modules = Iterables.filter( schema.getModules(), filter );
-        return this.filterLatestModule( modules );
+        Iterable<Module> modules = Iterables.filter(schema.getModules(), filter);
+        return this.filterLatestModule(modules);
     }
 
-    private Module filterLatestModule( final Iterable<Module> modules ) {
+    private Module filterLatestModule(final Iterable<Module> modules) {
         Module latestModule = modules.iterator().hasNext() ? modules.iterator().next() : null;
-        for( final Module module : modules ) {
-            if( module.getRevision().after( latestModule.getRevision() ) ) {
+        for (final Module module : modules) {
+            if (module.getRevision().after(latestModule.getRevision())) {
                 latestModule = module;
             }
         }
         return latestModule;
     }
 
-    public Module findModuleByName( final String moduleName ) {
+    public Module findModuleByName(final String moduleName) {
         this.checkPreconditions();
-        Preconditions.checkArgument( moduleName != null && !moduleName.isEmpty() );
-        return this.getLatestModule( globalSchema, moduleName );
+        Preconditions.checkArgument(moduleName != null && !moduleName.isEmpty());
+        return this.getLatestModule(globalSchema, moduleName);
     }
 
-    public Module findModuleByName( final MountInstance mountPoint, final String moduleName ) {
-        Preconditions.checkArgument( moduleName != null && mountPoint != null );
+    public Module findModuleByName(final MountInstance mountPoint, final String moduleName) {
+        Preconditions.checkArgument(moduleName != null && mountPoint != null);
 
         final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
-        return mountPointSchema == null ? null : this.getLatestModule( mountPointSchema, moduleName );
+        return mountPointSchema == null ? null : this.getLatestModule(mountPointSchema, moduleName);
     }
 
-    public Module findModuleByNamespace( final URI namespace ) {
+    public Module findModuleByNamespace(final URI namespace) {
         this.checkPreconditions();
-        Preconditions.checkArgument( namespace != null );
+        Preconditions.checkArgument(namespace != null);
 
-        final Set<Module> moduleSchemas = globalSchema.findModuleByNamespace( namespace );
-        return moduleSchemas == null ? null : this.filterLatestModule( moduleSchemas );
+        final Set<Module> moduleSchemas = globalSchema.findModuleByNamespace(namespace);
+        return moduleSchemas == null ? null : this.filterLatestModule(moduleSchemas);
     }
 
-    public Module findModuleByNamespace( final MountInstance mountPoint, final URI namespace ) {
-        Preconditions.checkArgument( namespace != null && mountPoint != null );
+    public Module findModuleByNamespace(final MountInstance mountPoint, final URI namespace) {
+        Preconditions.checkArgument(namespace != null && mountPoint != null);
 
         final SchemaContext mountPointSchema = mountPoint.getSchemaContext();
-        Set<Module> moduleSchemas = mountPointSchema == null ? null :
-            mountPointSchema.findModuleByNamespace( namespace );
-        return moduleSchemas == null ? null : this.filterLatestModule( moduleSchemas );
+        Set<Module> moduleSchemas = mountPointSchema == null ? null : mountPointSchema.findModuleByNamespace(namespace);
+        return moduleSchemas == null ? null : this.filterLatestModule(moduleSchemas);
     }
 
-    public Module findModuleByNameAndRevision( final QName module ) {
+    public Module findModuleByNameAndRevision(final QName module) {
         this.checkPreconditions();
-        Preconditions.checkArgument( module != null && module.getLocalName() != null &&
-                module.getRevision() != null );
+        Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null);
 
-        return globalSchema.findModuleByName( module.getLocalName(), module.getRevision() );
+        return globalSchema.findModuleByName(module.getLocalName(), module.getRevision());
     }
 
-    public Module findModuleByNameAndRevision( final MountInstance mountPoint, final QName module ) {
+    public Module findModuleByNameAndRevision(final MountInstance mountPoint, final QName module) {
         this.checkPreconditions();
-        Preconditions.checkArgument( module != null && module.getLocalName() != null &&
-                module.getRevision() != null && mountPoint != null );
+        Preconditions.checkArgument(module != null && module.getLocalName() != null && module.getRevision() != null
+                && mountPoint != null);
 
         SchemaContext schemaContext = mountPoint.getSchemaContext();
-        return schemaContext == null ? null :
-            schemaContext.findModuleByName( module.getLocalName(), module.getRevision() );
+        return schemaContext == null ? null : schemaContext.findModuleByName(module.getLocalName(),
+                module.getRevision());
     }
 
-    public DataNodeContainer getDataNodeContainerFor( final InstanceIdentifier path ) {
+    public DataNodeContainer getDataNodeContainerFor(final InstanceIdentifier path) {
         this.checkPreconditions();
 
-        final List<PathArgument> elements = path.getPath();
+        final Iterable<PathArgument> elements = path.getPathArguments();
         PathArgument head = elements.iterator().next();
         final QName startQName = head.getNodeType();
-        final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(
-                startQName.getNamespace(), startQName.getRevision() );
+        final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
+                startQName.getRevision());
         DataNodeContainer node = initialModule;
-        for( final PathArgument element : elements ) {
+        for (final PathArgument element : elements) {
             QName _nodeType = element.getNodeType();
-            final DataSchemaNode potentialNode = ControllerContext.childByQName( node, _nodeType );
-            if( potentialNode == null || !this.isListOrContainer( potentialNode ) ) {
+            final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
+            if (potentialNode == null || !this.isListOrContainer(potentialNode)) {
                 return null;
             }
             node = (DataNodeContainer) potentialNode;
@@ -273,68 +267,68 @@ public class ControllerContext implements SchemaContextListener {
         return node;
     }
 
-    public String toFullRestconfIdentifier( final InstanceIdentifier path ) {
+    public String toFullRestconfIdentifier(final InstanceIdentifier path) {
         this.checkPreconditions();
 
-        final List<PathArgument> elements = path.getPath();
+        final Iterable<PathArgument> elements = path.getPathArguments();
         final StringBuilder builder = new StringBuilder();
         PathArgument head = elements.iterator().next();
         final QName startQName = head.getNodeType();
-        final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(
-                startQName.getNamespace(), startQName.getRevision() );
+        final Module initialModule = globalSchema.findModuleByNamespaceAndRevision(startQName.getNamespace(),
+                startQName.getRevision());
         DataNodeContainer node = initialModule;
-        for( final PathArgument element : elements ) {
+        for (final PathArgument element : elements) {
             QName _nodeType = element.getNodeType();
-            final DataSchemaNode potentialNode = ControllerContext.childByQName( node, _nodeType );
-            if( !this.isListOrContainer( potentialNode ) ) {
+            final DataSchemaNode potentialNode = ControllerContext.childByQName(node, _nodeType);
+            if (!this.isListOrContainer(potentialNode)) {
                 return null;
             }
             node = ((DataNodeContainer) potentialNode);
-            builder.append( this.convertToRestconfIdentifier( element, node ) );
+            builder.append(this.convertToRestconfIdentifier(element, node));
         }
 
         return builder.toString();
     }
 
-    public String findModuleNameByNamespace( final URI namespace ) {
+    public String findModuleNameByNamespace(final URI namespace) {
         this.checkPreconditions();
 
-        String moduleName = this.uriToModuleName.get( namespace );
-        if( moduleName == null ) {
-            final Module module = this.findModuleByNamespace( namespace );
-            if( module != null ) {
+        String moduleName = this.uriToModuleName.get(namespace);
+        if (moduleName == null) {
+            final Module module = this.findModuleByNamespace(namespace);
+            if (module != null) {
                 moduleName = module.getName();
-                this.uriToModuleName.put( namespace, moduleName );
+                this.uriToModuleName.put(namespace, moduleName);
             }
         }
 
         return moduleName;
     }
 
-    public String findModuleNameByNamespace( final MountInstance mountPoint, final URI namespace ) {
-        final Module module = this.findModuleByNamespace( mountPoint, namespace );
+    public String findModuleNameByNamespace(final MountInstance mountPoint, final URI namespace) {
+        final Module module = this.findModuleByNamespace(mountPoint, namespace);
         return module == null ? null : module.getName();
     }
 
-    public URI findNamespaceByModuleName( final String moduleName ) {
-        URI namespace = this.moduleNameToUri.get( moduleName );
-        if( namespace == null ) {
-            Module module = this.findModuleByName( moduleName );
-            if( module != null ) {
+    public URI findNamespaceByModuleName(final String moduleName) {
+        URI namespace = this.moduleNameToUri.get(moduleName);
+        if (namespace == null) {
+            Module module = this.findModuleByName(moduleName);
+            if (module != null) {
                 URI _namespace = module.getNamespace();
                 namespace = _namespace;
-                this.uriToModuleName.put( namespace, moduleName );
+                this.uriToModuleName.put(namespace, moduleName);
             }
         }
         return namespace;
     }
 
-    public URI findNamespaceByModuleName( final MountInstance mountPoint, final String moduleName ) {
-        final Module module = this.findModuleByName( mountPoint, moduleName );
+    public URI findNamespaceByModuleName(final MountInstance mountPoint, final String moduleName) {
+        final Module module = this.findModuleByName(mountPoint, moduleName);
         return module == null ? null : module.getNamespace();
     }
 
-    public Set<Module> getAllModules( final MountInstance mountPoint ) {
+    public Set<Module> getAllModules(final MountInstance mountPoint) {
         this.checkPreconditions();
 
         SchemaContext schemaContext = mountPoint == null ? null : mountPoint.getSchemaContext();
@@ -346,55 +340,55 @@ public class ControllerContext implements SchemaContextListener {
         return globalSchema.getModules();
     }
 
-    public CharSequence toRestconfIdentifier( final QName qname ) {
+    public CharSequence toRestconfIdentifier(final QName qname) {
         this.checkPreconditions();
 
-        String module = this.uriToModuleName.get( qname.getNamespace() );
-        if( module == null ) {
-            final Module moduleSchema = globalSchema.findModuleByNamespaceAndRevision(
-                    qname.getNamespace(), qname.getRevision() );
-            if( moduleSchema == null ) {
+        String module = this.uriToModuleName.get(qname.getNamespace());
+        if (module == null) {
+            final Module moduleSchema = globalSchema.findModuleByNamespaceAndRevision(qname.getNamespace(),
+                    qname.getRevision());
+            if (moduleSchema == null) {
                 return null;
             }
 
-            this.uriToModuleName.put( qname.getNamespace(), moduleSchema.getName() );
+            this.uriToModuleName.put(qname.getNamespace(), moduleSchema.getName());
             module = moduleSchema.getName();
         }
 
         StringBuilder builder = new StringBuilder();
-        builder.append( module );
-        builder.append( ":" );
-        builder.append( qname.getLocalName() );
+        builder.append(module);
+        builder.append(":");
+        builder.append(qname.getLocalName());
         return builder.toString();
     }
 
-    public CharSequence toRestconfIdentifier( final MountInstance mountPoint, final QName qname ) {
-        if( mountPoint == null ) {
+    public CharSequence toRestconfIdentifier(final MountInstance mountPoint, final QName qname) {
+        if (mountPoint == null) {
             return null;
         }
 
         SchemaContext schemaContext = mountPoint.getSchemaContext();
 
-        final Module moduleSchema = schemaContext.findModuleByNamespaceAndRevision(
-                qname.getNamespace(), qname.getRevision() );
-        if( moduleSchema == null ) {
+        final Module moduleSchema = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
+                qname.getRevision());
+        if (moduleSchema == null) {
             return null;
         }
 
         StringBuilder builder = new StringBuilder();
-        builder.append( moduleSchema.getName() );
-        builder.append( ":" );
-        builder.append( qname.getLocalName() );
+        builder.append(moduleSchema.getName());
+        builder.append(":");
+        builder.append(qname.getLocalName());
         return builder.toString();
     }
 
     public Module getRestconfModule() {
-        return findModuleByNameAndRevision( Draft02.RestConfModule.IETF_RESTCONF_QNAME );
+        return findModuleByNameAndRevision(Draft02.RestConfModule.IETF_RESTCONF_QNAME);
     }
 
     public DataSchemaNode getRestconfModuleErrorsSchemaNode() {
         Module restconfModule = getRestconfModule();
-        if( restconfModule == null ) {
+        if (restconfModule == null) {
             return null;
         }
 
@@ -403,8 +397,7 @@ public class ControllerContext implements SchemaContextListener {
         final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
             @Override
             public boolean apply(final GroupingDefinition g) {
-                return Objects.equal(g.getQName().getLocalName(),
-                        Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE);
+                return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.ERRORS_GROUPING_SCHEMA_NODE);
             }
         };
 
@@ -412,20 +405,18 @@ public class ControllerContext implements SchemaContextListener {
 
         final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
 
-        List<DataSchemaNode> instanceDataChildrenByName =
-                this.findInstanceDataChildrenByName(restconfGrouping,
-                        Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
+        List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
+                Draft02.RestConfModule.ERRORS_CONTAINER_SCHEMA_NODE);
         return Iterables.getFirst(instanceDataChildrenByName, null);
     }
 
-    public DataSchemaNode getRestconfModuleRestConfSchemaNode( final Module inRestconfModule,
-            final String schemaNodeName ) {
+    public DataSchemaNode getRestconfModuleRestConfSchemaNode(final Module inRestconfModule, final String schemaNodeName) {
         Module restconfModule = inRestconfModule;
-        if( restconfModule == null ) {
+        if (restconfModule == null) {
             restconfModule = getRestconfModule();
         }
 
-        if( restconfModule == null ) {
+        if (restconfModule == null) {
             return null;
         }
 
@@ -434,8 +425,7 @@ public class ControllerContext implements SchemaContextListener {
         final Predicate<GroupingDefinition> filter = new Predicate<GroupingDefinition>() {
             @Override
             public boolean apply(final GroupingDefinition g) {
-                return Objects.equal(g.getQName().getLocalName(),
-                        Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE);
+                return Objects.equal(g.getQName().getLocalName(), Draft02.RestConfModule.RESTCONF_GROUPING_SCHEMA_NODE);
             }
         };
 
@@ -443,61 +433,49 @@ public class ControllerContext implements SchemaContextListener {
 
         final GroupingDefinition restconfGrouping = Iterables.getFirst(filteredGroups, null);
 
-        List<DataSchemaNode> instanceDataChildrenByName =
-                this.findInstanceDataChildrenByName(restconfGrouping,
-                        Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
+        List<DataSchemaNode> instanceDataChildrenByName = this.findInstanceDataChildrenByName(restconfGrouping,
+                Draft02.RestConfModule.RESTCONF_CONTAINER_SCHEMA_NODE);
         final DataSchemaNode restconfContainer = Iterables.getFirst(instanceDataChildrenByName, null);
 
         if (Objects.equal(schemaNodeName, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE)) {
-            List<DataSchemaNode> instances =
-                    this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer),
-                            Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
+            List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
+                    ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
             return Iterables.getFirst(instances, null);
-        }
-        else if(Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
-            List<DataSchemaNode> instances =
-                    this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer),
-                            Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
+        } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
+            List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
+                    ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
             return Iterables.getFirst(instances, null);
-        }
-        else if(Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
-            List<DataSchemaNode> instances =
-                    this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer),
-                            Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
+        } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE)) {
+            List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
+                    ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
             final DataSchemaNode modules = Iterables.getFirst(instances, null);
             instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
                     Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
             return Iterables.getFirst(instances, null);
-        }
-        else if(Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
-            List<DataSchemaNode> instances =
-                    this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer),
-                            Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
+        } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE)) {
+            List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
+                    ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
             return Iterables.getFirst(instances, null);
-        }
-        else if(Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
-            List<DataSchemaNode> instances =
-                    this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer),
-                            Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
+        } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE)) {
+            List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
+                    ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
             final DataSchemaNode modules = Iterables.getFirst(instances, null);
             instances = this.findInstanceDataChildrenByName(((DataNodeContainer) modules),
                     Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
             return Iterables.getFirst(instances, null);
-        }
-        else if(Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
-            List<DataSchemaNode> instances =
-                    this.findInstanceDataChildrenByName(((DataNodeContainer) restconfContainer),
-                            Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
+        } else if (Objects.equal(schemaNodeName, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE)) {
+            List<DataSchemaNode> instances = this.findInstanceDataChildrenByName(
+                    ((DataNodeContainer) restconfContainer), Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
             return Iterables.getFirst(instances, null);
         }
 
         return null;
     }
 
-    private static DataSchemaNode childByQName( final ChoiceNode container, final QName name ) {
-        for( final ChoiceCaseNode caze : container.getCases() ) {
-            final DataSchemaNode ret = ControllerContext.childByQName( caze, name );
-            if( ret != null ) {
+    private static DataSchemaNode childByQName(final ChoiceNode container, final QName name) {
+        for (final ChoiceCaseNode caze : container.getCases()) {
+            final DataSchemaNode ret = ControllerContext.childByQName(caze, name);
+            if (ret != null) {
                 return ret;
             }
         }
@@ -505,34 +483,34 @@ public class ControllerContext implements SchemaContextListener {
         return null;
     }
 
-    private static DataSchemaNode childByQName( final ChoiceCaseNode container, final QName name ) {
-        return container.getDataChildByName( name );
+    private static DataSchemaNode childByQName(final ChoiceCaseNode container, final QName name) {
+        return container.getDataChildByName(name);
     }
 
-    private static DataSchemaNode childByQName( final ContainerSchemaNode container, final QName name ) {
-        return ControllerContext.dataNodeChildByQName( container, name );
+    private static DataSchemaNode childByQName(final ContainerSchemaNode container, final QName name) {
+        return ControllerContext.dataNodeChildByQName(container, name);
     }
 
-    private static DataSchemaNode childByQName( final ListSchemaNode container, final QName name ) {
-        return ControllerContext.dataNodeChildByQName( container, name );
+    private static DataSchemaNode childByQName(final ListSchemaNode container, final QName name) {
+        return ControllerContext.dataNodeChildByQName(container, name);
     }
 
-    private static DataSchemaNode childByQName( final Module container, final QName name ) {
-        return ControllerContext.dataNodeChildByQName( container, name );
+    private static DataSchemaNode childByQName(final Module container, final QName name) {
+        return ControllerContext.dataNodeChildByQName(container, name);
     }
 
-    private static DataSchemaNode childByQName( final DataSchemaNode container, final QName name ) {
+    private static DataSchemaNode childByQName(final DataSchemaNode container, final QName name) {
         return null;
     }
 
-    private static DataSchemaNode dataNodeChildByQName( final DataNodeContainer container, final QName name ) {
-        DataSchemaNode ret = container.getDataChildByName( name );
-        if( ret == null ) {
-            for( final DataSchemaNode node : container.getChildNodes() ) {
-                if( (node instanceof ChoiceCaseNode) ) {
+    private static DataSchemaNode dataNodeChildByQName(final DataNodeContainer container, final QName name) {
+        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( childByQName != null ) {
+                    DataSchemaNode childByQName = ControllerContext.childByQName(caseNode, name);
+                    if (childByQName != null) {
                         return childByQName;
                     }
                 }
@@ -541,462 +519,427 @@ public class ControllerContext implements SchemaContextListener {
         return ret;
     }
 
-    private String toUriString( final Object object ) throws UnsupportedEncodingException {
-        return object == null ? "" :
-            URLEncoder.encode( object.toString(), ControllerContext.URI_ENCODING_CHAR_SET );
+    private String toUriString(final Object object) throws UnsupportedEncodingException {
+        return object == null ? "" : URLEncoder.encode(object.toString(), ControllerContext.URI_ENCODING_CHAR_SET);
     }
 
-    private InstanceIdWithSchemaNode collectPathArguments( final InstanceIdentifierBuilder builder,
+    private InstanceIdWithSchemaNode collectPathArguments(final InstanceIdentifierBuilder builder,
             final List<String> strings, final DataNodeContainer parentNode, final MountInstance mountPoint,
-            final boolean returnJustMountPoint ) {
-        Preconditions.<List<String>> checkNotNull( strings );
+            final boolean returnJustMountPoint) {
+        Preconditions.<List<String>> checkNotNull(strings);
 
-        if( parentNode == null ) {
+        if (parentNode == null) {
             return null;
         }
 
-        if( strings.isEmpty() ) {
-            return new InstanceIdWithSchemaNode( builder.toInstance(),
-                    ((DataSchemaNode) parentNode), mountPoint );
+        if (strings.isEmpty()) {
+            return new InstanceIdWithSchemaNode(builder.toInstance(), ((DataSchemaNode) parentNode), mountPoint);
         }
 
         String head = strings.iterator().next();
-        final String nodeName = this.toNodeName( head );
-        final String moduleName = ControllerContext.toModuleName( head );
+        final String nodeName = toNodeName(head);
+        final String moduleName = ControllerContext.toModuleName(head);
 
         DataSchemaNode targetNode = null;
-        if( !Strings.isNullOrEmpty( moduleName ) ) {
-            if( Objects.equal( moduleName, ControllerContext.MOUNT_MODULE ) &&
-                    Objects.equal( nodeName, ControllerContext.MOUNT_NODE ) ) {
-                if( mountPoint != null ) {
-                    throw new RestconfDocumentedException(
-                            "Restconf supports just one mount point in URI.",
-                            ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED );
+        if (!Strings.isNullOrEmpty(moduleName)) {
+            if (Objects.equal(moduleName, ControllerContext.MOUNT_MODULE)
+                    && Objects.equal(nodeName, ControllerContext.MOUNT_NODE)) {
+                if (mountPoint != null) {
+                    throw new RestconfDocumentedException("Restconf supports just one mount point in URI.",
+                            ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
                 }
 
-                if( mountService == null ) {
+                if (mountService == null) {
                     throw new RestconfDocumentedException(
                             "MountService was not found. Finding behind mount points does not work.",
-                            ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED );
+                            ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED);
                 }
 
                 final InstanceIdentifier partialPath = builder.toInstance();
-                final MountInstance mount = mountService.getMountPoint( partialPath );
-                if( mount == null ) {
-                    LOG.debug( "Instance identifier to missing mount point: {}", partialPath );
-                    throw new RestconfDocumentedException(
-                            "Mount point does not exist.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT );
+                final MountInstance mount = mountService.getMountPoint(partialPath);
+                if (mount == null) {
+                    LOG.debug("Instance identifier to missing mount point: {}", partialPath);
+                    throw new RestconfDocumentedException("Mount point does not exist.", ErrorType.PROTOCOL,
+                            ErrorTag.UNKNOWN_ELEMENT);
                 }
 
                 final SchemaContext mountPointSchema = mount.getSchemaContext();
-                if( mountPointSchema == null ) {
-                    throw new RestconfDocumentedException(
-                            "Mount point does not contain any schema with modules.",
-                            ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT );
+                if (mountPointSchema == null) {
+                    throw new RestconfDocumentedException("Mount point does not contain any schema with modules.",
+                            ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
                 }
 
-                if( returnJustMountPoint ) {
+                if (returnJustMountPoint) {
                     InstanceIdentifier instance = InstanceIdentifier.builder().toInstance();
-                    return new InstanceIdWithSchemaNode( instance, mountPointSchema, mount );
+                    return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
                 }
 
-                if( strings.size() == 1 ) {
+                if (strings.size() == 1) {
                     InstanceIdentifier instance = InstanceIdentifier.builder().toInstance();
-                    return new InstanceIdWithSchemaNode( instance, mountPointSchema, mount );
+                    return new InstanceIdWithSchemaNode(instance, mountPointSchema, mount);
                 }
 
-                final String moduleNameBehindMountPoint = toModuleName(  strings.get( 1 ) );
-                if( moduleNameBehindMountPoint == null ) {
+                final String moduleNameBehindMountPoint = toModuleName(strings.get(1));
+                if (moduleNameBehindMountPoint == null) {
                     throw new RestconfDocumentedException(
                             "First node after mount point in URI has to be in format \"moduleName:nodeName\"",
-                            ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                            ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
                 }
 
-                final Module moduleBehindMountPoint = this.getLatestModule( mountPointSchema,
-                        moduleNameBehindMountPoint );
-                if( moduleBehindMountPoint == null ) {
-                    throw new RestconfDocumentedException(
-                            "\"" +moduleName + "\" module does not exist in mount point.",
-                            ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT );
+                final Module moduleBehindMountPoint = this
+                        .getLatestModule(mountPointSchema, moduleNameBehindMountPoint);
+                if (moduleBehindMountPoint == null) {
+                    throw new RestconfDocumentedException("\"" + moduleName
+                            + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
                 }
 
-                List<String> subList = strings.subList( 1, strings.size() );
-                return this.collectPathArguments( InstanceIdentifier.builder(), subList, moduleBehindMountPoint,
-                        mount, returnJustMountPoint );
+                List<String> subList = strings.subList(1, strings.size());
+                return this.collectPathArguments(InstanceIdentifier.builder(), subList, moduleBehindMountPoint, mount,
+                        returnJustMountPoint);
             }
 
             Module module = null;
-            if( mountPoint == null ) {
-                module = this.getLatestModule( globalSchema, moduleName );
-                if( module == null ) {
-                    throw new RestconfDocumentedException(
-                            "\"" + moduleName + "\" module does not exist.",
-                            ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT );
+            if (mountPoint == null) {
+                module = this.getLatestModule(globalSchema, moduleName);
+                if (module == null) {
+                    throw new RestconfDocumentedException("\"" + moduleName + "\" module does not exist.",
+                            ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
                 }
-            }
-            else {
+            } else {
                 SchemaContext schemaContext = mountPoint.getSchemaContext();
-                module = schemaContext == null ? null :
-                    this.getLatestModule( schemaContext, moduleName );
-                if( module == null ) {
-                    throw new RestconfDocumentedException(
-                            "\"" + moduleName + "\" module does not exist in mount point.",
-                            ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT );
+                module = schemaContext == null ? null : this.getLatestModule(schemaContext, moduleName);
+                if (module == null) {
+                    throw new RestconfDocumentedException("\"" + moduleName
+                            + "\" module does not exist in mount point.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
                 }
             }
 
-            targetNode = this.findInstanceDataChildByNameAndNamespace(
-                    parentNode, nodeName, module.getNamespace() );
-            if( targetNode == null ) {
-                throw new RestconfDocumentedException(
-                        "URI has bad format. Possible reasons:\n" +
-                                " 1. \"" + head + "\" was not found in parent data node.\n" +
-                                " 2. \"" + head + "\" is behind mount point. Then it should be in format \"/" +
-                                MOUNT + "/" + head + "\".", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+            targetNode = this.findInstanceDataChildByNameAndNamespace(parentNode, nodeName, module.getNamespace());
+            if (targetNode == null) {
+                throw new RestconfDocumentedException("URI has bad format. Possible reasons:\n" + " 1. \"" + head
+                        + "\" was not found in parent data node.\n" + " 2. \"" + head
+                        + "\" is behind mount point. Then it should be in format \"/" + MOUNT + "/" + head + "\".",
+                        ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
             }
         } else {
-            final List<DataSchemaNode> potentialSchemaNodes =
-                    this.findInstanceDataChildrenByName( parentNode, nodeName );
-            if( potentialSchemaNodes.size() > 1 ) {
+            final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(parentNode, nodeName);
+            if (potentialSchemaNodes.size() > 1) {
                 final StringBuilder strBuilder = new StringBuilder();
-                for( final DataSchemaNode potentialNodeSchema : potentialSchemaNodes ) {
-                    strBuilder.append( "   " )
-                    .append( potentialNodeSchema.getQName().getNamespace() )
-                    .append( "\n" );
+                for (final DataSchemaNode potentialNodeSchema : potentialSchemaNodes) {
+                    strBuilder.append("   ").append(potentialNodeSchema.getQName().getNamespace()).append("\n");
                 }
 
                 throw new RestconfDocumentedException(
-                        "URI has bad format. Node \"" + nodeName +
-                        "\" is added as augment from more than one module. " +
-                        "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"." +
-                        "\nThe node is added as augment from modules with namespaces:\n" +
-                        strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                        "URI has bad format. Node \""
+                                + nodeName
+                                + "\" is added as augment from more than one module. "
+                                + "Therefore the node must have module name and it has to be in format \"moduleName:nodeName\"."
+                                + "\nThe node is added as augment from modules with namespaces:\n"
+                                + strBuilder.toString(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
             }
 
-            if( potentialSchemaNodes.isEmpty() ) {
-                throw new RestconfDocumentedException(
-                        "\"" + nodeName + "\" in URI was not found in parent data node",
-                        ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT );
+            if (potentialSchemaNodes.isEmpty()) {
+                throw new RestconfDocumentedException("\"" + nodeName + "\" in URI was not found in parent data node",
+                        ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
             }
 
             targetNode = potentialSchemaNodes.iterator().next();
         }
 
-        if( !this.isListOrContainer( targetNode ) ) {
-            throw new RestconfDocumentedException(
-                    "URI has bad format. Node \"" + head + "\" must be Container or List yang type.",
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+        if (!this.isListOrContainer(targetNode)) {
+            throw new RestconfDocumentedException("URI has bad format. Node \"" + head
+                    + "\" must be Container or List yang type.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
         int consumed = 1;
-        if( (targetNode instanceof ListSchemaNode) ) {
+        if ((targetNode instanceof ListSchemaNode)) {
             final ListSchemaNode listNode = ((ListSchemaNode) targetNode);
             final int keysSize = listNode.getKeyDefinition().size();
-            if( (strings.size() - consumed) < keysSize ) {
-                throw new RestconfDocumentedException(
-                        "Missing key for list \"" + listNode.getQName().getLocalName() + "\".",
-                        ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+            if ((strings.size() - consumed) < keysSize) {
+                throw new RestconfDocumentedException("Missing key for list \"" + listNode.getQName().getLocalName()
+                        + "\".", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
             }
 
-            final List<String> uriKeyValues = strings.subList( consumed, consumed + keysSize );
+            final List<String> uriKeyValues = strings.subList(consumed, consumed + keysSize);
             final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
             int i = 0;
-            for( final QName key : listNode.getKeyDefinition() ) {
+            for (final QName key : listNode.getKeyDefinition()) {
                 {
-                    final String uriKeyValue = uriKeyValues.get( i );
-                    if( uriKeyValue.equals( NULL_VALUE ) ) {
-                        throw new RestconfDocumentedException(
-                                "URI has bad format. List \"" + listNode.getQName().getLocalName() +
-                                "\" cannot contain \"null\" value as a key.",
-                                ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                    final String uriKeyValue = uriKeyValues.get(i);
+                    if (uriKeyValue.equals(NULL_VALUE)) {
+                        throw new RestconfDocumentedException("URI has bad format. List \""
+                                + listNode.getQName().getLocalName() + "\" cannot contain \"null\" value as a key.",
+                                ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
                     }
 
-                    this.addKeyValue( keyValues, listNode.getDataChildByName( key ),
-                            uriKeyValue, mountPoint );
+                    this.addKeyValue(keyValues, listNode.getDataChildByName(key), uriKeyValue, mountPoint);
                     i++;
                 }
             }
 
             consumed = consumed + i;
-            builder.nodeWithKey( targetNode.getQName(), keyValues );
-        }
-        else {
-            builder.node( targetNode.getQName() );
+            builder.nodeWithKey(targetNode.getQName(), keyValues);
+        } else {
+            builder.node(targetNode.getQName());
         }
 
-        if( (targetNode instanceof DataNodeContainer) ) {
-            final List<String> remaining = strings.subList( consumed, strings.size() );
-            return this.collectPathArguments( builder, remaining,
-                    ((DataNodeContainer) targetNode), mountPoint, returnJustMountPoint );
+        if ((targetNode instanceof DataNodeContainer)) {
+            final List<String> remaining = strings.subList(consumed, strings.size());
+            return this.collectPathArguments(builder, remaining, ((DataNodeContainer) targetNode), mountPoint,
+                    returnJustMountPoint);
         }
 
-        return new InstanceIdWithSchemaNode( builder.toInstance(), targetNode, mountPoint );
+        return new InstanceIdWithSchemaNode(builder.toInstance(), targetNode, mountPoint);
     }
 
-    public DataSchemaNode findInstanceDataChildByNameAndNamespace( final DataNodeContainer container,
-            final String name, final URI namespace ) {
-        Preconditions.<URI> checkNotNull( namespace );
+    public DataSchemaNode findInstanceDataChildByNameAndNamespace(final DataNodeContainer container, final String name,
+            final URI namespace) {
+        Preconditions.<URI> checkNotNull(namespace);
 
-        final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName( container, name );
+        final List<DataSchemaNode> potentialSchemaNodes = this.findInstanceDataChildrenByName(container, name);
 
         Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
             @Override
-            public boolean apply( final DataSchemaNode node ) {
-                return Objects.equal( node.getQName().getNamespace(), namespace );
+            public boolean apply(final DataSchemaNode node) {
+                return Objects.equal(node.getQName().getNamespace(), namespace);
             }
         };
 
-        Iterable<DataSchemaNode> result = Iterables.filter( potentialSchemaNodes, filter );
-        return Iterables.getFirst( result, null );
+        Iterable<DataSchemaNode> result = Iterables.filter(potentialSchemaNodes, filter);
+        return Iterables.getFirst(result, null);
     }
 
-    public List<DataSchemaNode> findInstanceDataChildrenByName( final DataNodeContainer container,
-            final String name ) {
-        Preconditions.<DataNodeContainer> checkNotNull( container );
-        Preconditions.<String> checkNotNull( name );
+    public List<DataSchemaNode> findInstanceDataChildrenByName(final DataNodeContainer container, final String name) {
+        Preconditions.<DataNodeContainer> checkNotNull(container);
+        Preconditions.<String> checkNotNull(name);
 
         List<DataSchemaNode> instantiatedDataNodeContainers = new ArrayList<DataSchemaNode>();
-        this.collectInstanceDataNodeContainers( instantiatedDataNodeContainers, container, name );
+        this.collectInstanceDataNodeContainers(instantiatedDataNodeContainers, container, name);
         return instantiatedDataNodeContainers;
     }
 
-    private void collectInstanceDataNodeContainers( final List<DataSchemaNode> potentialSchemaNodes,
-            final DataNodeContainer container, final String name ) {
+    private void collectInstanceDataNodeContainers(final List<DataSchemaNode> potentialSchemaNodes,
+            final DataNodeContainer container, final String name) {
 
         Set<DataSchemaNode> childNodes = container.getChildNodes();
 
         Predicate<DataSchemaNode> filter = new Predicate<DataSchemaNode>() {
             @Override
-            public boolean apply( final DataSchemaNode node ) {
-                return Objects.equal( node.getQName().getLocalName(), name );
+            public boolean apply(final DataSchemaNode node) {
+                return Objects.equal(node.getQName().getLocalName(), name);
             }
         };
 
-        Iterable<DataSchemaNode> nodes = Iterables.filter( childNodes, filter );
+        Iterable<DataSchemaNode> nodes = Iterables.filter(childNodes, filter);
 
-        // Can't combine this loop with the filter above because the filter is lazily-applied
-        // by Iterables.filter.
-        for( final DataSchemaNode potentialNode : nodes ) {
-            if( this.isInstantiatedDataSchema( potentialNode ) ) {
-                potentialSchemaNodes.add( potentialNode );
+        // Can't combine this loop with the filter above because the filter is
+        // lazily-applied by Iterables.filter.
+        for (final DataSchemaNode potentialNode : nodes) {
+            if (this.isInstantiatedDataSchema(potentialNode)) {
+                potentialSchemaNodes.add(potentialNode);
             }
         }
 
-        Iterable<ChoiceNode> choiceNodes = Iterables.<ChoiceNode> filter( container.getChildNodes(),
-                ChoiceNode.class );
+        Iterable<ChoiceNode> choiceNodes = Iterables.<ChoiceNode> filter(container.getChildNodes(), ChoiceNode.class);
 
-        final Function<ChoiceNode, Set<ChoiceCaseNode>> choiceFunction =
-                new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
+        final Function<ChoiceNode, Set<ChoiceCaseNode>> choiceFunction = new Function<ChoiceNode, Set<ChoiceCaseNode>>() {
             @Override
-            public Set<ChoiceCaseNode> apply( final ChoiceNode node ) {
+            public Set<ChoiceCaseNode> apply(final ChoiceNode node) {
                 return node.getCases();
             }
         };
 
-        Iterable<Set<ChoiceCaseNode>> map = Iterables.<ChoiceNode, Set<ChoiceCaseNode>> transform(
-                choiceNodes, choiceFunction );
+        Iterable<Set<ChoiceCaseNode>> map = Iterables.<ChoiceNode, Set<ChoiceCaseNode>> transform(choiceNodes,
+                choiceFunction);
 
-        final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat( map );
-        for( final ChoiceCaseNode caze : allCases ) {
-            this.collectInstanceDataNodeContainers( potentialSchemaNodes, caze, name );
+        final Iterable<ChoiceCaseNode> allCases = Iterables.<ChoiceCaseNode> concat(map);
+        for (final ChoiceCaseNode caze : allCases) {
+            this.collectInstanceDataNodeContainers(potentialSchemaNodes, caze, name);
         }
     }
 
-    public boolean isInstantiatedDataSchema( final DataSchemaNode node ) {
-        return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode ||
-                node instanceof ContainerSchemaNode || node instanceof ListSchemaNode;
+    public boolean isInstantiatedDataSchema(final DataSchemaNode node) {
+        return node instanceof LeafSchemaNode || node instanceof LeafListSchemaNode
+                || node instanceof ContainerSchemaNode || node instanceof ListSchemaNode
+                || node instanceof AnyXmlSchemaNode;
     }
 
-    private void addKeyValue( final HashMap<QName, Object> map, final DataSchemaNode node,
-            final String uriValue, final MountInstance mountPoint ) {
-        Preconditions.<String> checkNotNull( uriValue );
-        Preconditions.checkArgument( (node instanceof LeafSchemaNode) );
+    private void addKeyValue(final HashMap<QName, Object> map, final DataSchemaNode node, final String uriValue,
+            final MountInstance mountPoint) {
+        Preconditions.<String> checkNotNull(uriValue);
+        Preconditions.checkArgument((node instanceof LeafSchemaNode));
 
-        final String urlDecoded = urlPathArgDecode( uriValue );
+        final String urlDecoded = urlPathArgDecode(uriValue);
         final TypeDefinition<? extends Object> typedef = ((LeafSchemaNode) node).getType();
-        Codec<Object, Object> codec = RestCodec.from( typedef, mountPoint );
+        Codec<Object, Object> codec = RestCodec.from(typedef, mountPoint);
 
-        Object decoded = codec == null ? null : codec.deserialize( urlDecoded );
+        Object decoded = codec == null ? null : codec.deserialize(urlDecoded);
         String additionalInfo = "";
-        if( decoded == null ) {
-            TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom( typedef );
-            if( (baseType instanceof IdentityrefTypeDefinition) ) {
-                decoded = this.toQName( urlDecoded );
+        if (decoded == null) {
+            TypeDefinition<? extends Object> baseType = RestUtil.resolveBaseTypeFrom(typedef);
+            if ((baseType instanceof IdentityrefTypeDefinition)) {
+                decoded = this.toQName(urlDecoded);
                 additionalInfo = "For key which is of type identityref it should be in format module_name:identity_name.";
             }
         }
 
-        if( decoded == null ) {
-            throw new RestconfDocumentedException(
-                    uriValue + " from URI can't be resolved. " + additionalInfo,
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+        if (decoded == null) {
+            throw new RestconfDocumentedException(uriValue + " from URI can't be resolved. " + additionalInfo,
+                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
-        map.put( node.getQName(), decoded );
+        map.put(node.getQName(), decoded);
     }
 
-    private static String toModuleName( final String str ) {
-        Preconditions.<String> checkNotNull( str );
-        if( str.contains( ":" ) ) {
-            final String[] args = str.split( ":" );
-            if( args.length == 2 ) {
-                return args[0];
+    private static String toModuleName(final String str) {
+        Preconditions.<String> checkNotNull(str);
+        if (str.indexOf(':') != -1) {
+            final Iterable<String> args = COLON_SPLITTER.split(str);
+            if (Iterables.size(args) == 2) {
+                return args.iterator().next();
             }
         }
         return null;
     }
 
-    private String toNodeName( final String str ) {
-        if( str.contains( ":" ) ) {
-            final String[] args = str.split( ":" );
-            if( args.length == 2 ) {
-                return args[1];
+    private static String toNodeName(final String str) {
+        if (str.indexOf(':') != -1) {
+            final Iterable<String> args = COLON_SPLITTER.split(str);
+            if (Iterables.size(args) == 2) {
+                return Iterables.get(args, 1);
             }
         }
         return str;
     }
 
-    private QName toQName( final String name ) {
-        final String module = toModuleName( name );
-        final String node = this.toNodeName( name );
+    private QName toQName(final String name) {
+        final String module = toModuleName(name);
+        final String node = toNodeName(name);
         Set<Module> modules = globalSchema.getModules();
 
         final Comparator<Module> comparator = new Comparator<Module>() {
             @Override
-            public int compare( final Module o1, final Module o2 ) {
-                return o1.getRevision().compareTo( o2.getRevision() );
+            public int compare(final Module o1, final Module o2) {
+                return o1.getRevision().compareTo(o2.getRevision());
             }
         };
 
-        List<Module> sorted = new ArrayList<Module>( modules );
-        Collections.<Module> sort( new ArrayList<Module>( modules ), comparator );
+        List<Module> sorted = new ArrayList<Module>(modules);
+        Collections.<Module> sort(new ArrayList<Module>(modules), comparator);
 
         final Function<Module, QName> transform = new Function<Module, QName>() {
             @Override
-            public QName apply( final Module m ) {
-                return QName.create( m.getNamespace(), m.getRevision(), m.getName() );
+            public QName apply(final Module m) {
+                return QName.create(m.getNamespace(), m.getRevision(), m.getName());
             }
         };
 
         final Predicate<QName> findFirst = new Predicate<QName>() {
             @Override
-            public boolean apply( final QName qn ) {
-                return Objects.equal( module, qn.getLocalName() );
+            public boolean apply(final QName qn) {
+                return Objects.equal(module, qn.getLocalName());
             }
         };
 
-        Optional<QName> namespace = FluentIterable.from( sorted )
-                .transform( transform )
-                .firstMatch( findFirst );
-        return namespace.isPresent() ? QName.create( namespace.get(), node ) : null;
+        Optional<QName> namespace = FluentIterable.from(sorted).transform(transform).firstMatch(findFirst);
+        return namespace.isPresent() ? QName.create(namespace.get(), node) : null;
     }
 
-    private boolean isListOrContainer( final DataSchemaNode node ) {
+    private boolean isListOrContainer(final DataSchemaNode node) {
         return node instanceof ListSchemaNode || node instanceof ContainerSchemaNode;
     }
 
-    public RpcDefinition getRpcDefinition( final String name ) {
-        final QName validName = this.toQName( name );
-        return validName == null ? null : this.qnameToRpc.get( validName );
+    public RpcDefinition getRpcDefinition(final String name) {
+        final QName validName = this.toQName(name);
+        return validName == null ? null : this.qnameToRpc.get(validName);
     }
 
     @Override
-    public void onGlobalContextUpdated( final SchemaContext context ) {
-        if( context != null ) {
+    public void onGlobalContextUpdated(final SchemaContext context) {
+        if (context != null) {
             this.qnameToRpc.clear();
-            this.setGlobalSchema( context );
+            this.setGlobalSchema(context);
             Set<RpcDefinition> _operations = context.getOperations();
-            for( final RpcDefinition operation : _operations ) {
+            for (final RpcDefinition operation : _operations) {
                 {
-                    this.qnameToRpc.put( operation.getQName(), operation );
+                    this.qnameToRpc.put(operation.getQName(), operation);
                 }
             }
         }
     }
 
-    public List<String> urlPathArgsDecode( final List<String> strings ) {
+    public static List<String> urlPathArgsDecode(final Iterable<String> strings) {
         try {
             List<String> decodedPathArgs = new ArrayList<String>();
-            for( final String pathArg : strings ) {
-                String _decode = URLDecoder.decode( pathArg, URI_ENCODING_CHAR_SET );
-                decodedPathArgs.add( _decode );
+            for (final String pathArg : strings) {
+                String _decode = URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
+                decodedPathArgs.add(_decode);
             }
             return decodedPathArgs;
-        }
-        catch( UnsupportedEncodingException e ) {
-            throw new RestconfDocumentedException(
-                    "Invalid URL path '" + strings + "': " + e.getMessage(),
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+        } catch (UnsupportedEncodingException e) {
+            throw new RestconfDocumentedException("Invalid URL path '" + strings + "': " + e.getMessage(),
+                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
     }
 
-    public String urlPathArgDecode( final String pathArg ) {
-        if( pathArg != null ) {
+    public String urlPathArgDecode(final String pathArg) {
+        if (pathArg != null) {
             try {
-                return URLDecoder.decode( pathArg, URI_ENCODING_CHAR_SET );
-            }
-            catch( UnsupportedEncodingException e ) {
-                throw new RestconfDocumentedException(
-                        "Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
-                        ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                return URLDecoder.decode(pathArg, URI_ENCODING_CHAR_SET);
+            } catch (UnsupportedEncodingException e) {
+                throw new RestconfDocumentedException("Invalid URL path arg '" + pathArg + "': " + e.getMessage(),
+                        ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
             }
         }
 
         return null;
     }
 
-    private CharSequence convertToRestconfIdentifier( final PathArgument argument,
-            final DataNodeContainer node ) {
-        if( argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode ) {
-            return convertToRestconfIdentifier( (NodeIdentifier) argument, (ContainerSchemaNode) node );
-        }
-        else if( argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode ) {
-            return convertToRestconfIdentifier( (NodeIdentifierWithPredicates) argument, (ListSchemaNode) node );
-        }
-        else if( argument != null && node != null ) {
-            throw new IllegalArgumentException(
-                    "Conversion of generic path argument is not supported" );
-        }
-        else {
-            throw new IllegalArgumentException( "Unhandled parameter types: "
-                    + Arrays.<Object> asList( argument, node ).toString() );
+    private CharSequence convertToRestconfIdentifier(final PathArgument argument, final DataNodeContainer node) {
+        if (argument instanceof NodeIdentifier && node instanceof ContainerSchemaNode) {
+            return convertToRestconfIdentifier((NodeIdentifier) argument, (ContainerSchemaNode) node);
+        } else if (argument instanceof NodeIdentifierWithPredicates && node instanceof ListSchemaNode) {
+            return convertToRestconfIdentifier((NodeIdentifierWithPredicates) argument, (ListSchemaNode) node);
+        } else if (argument != null && node != null) {
+            throw new IllegalArgumentException("Conversion of generic path argument is not supported");
+        } else {
+            throw new IllegalArgumentException("Unhandled parameter types: "
+                    + Arrays.<Object> asList(argument, node).toString());
         }
     }
 
-    private CharSequence convertToRestconfIdentifier( final NodeIdentifier argument,
-            final ContainerSchemaNode node ) {
+    private CharSequence convertToRestconfIdentifier(final NodeIdentifier argument, final ContainerSchemaNode node) {
         StringBuilder builder = new StringBuilder();
-        builder.append( "/" );
+        builder.append("/");
         QName nodeType = argument.getNodeType();
-        builder.append( this.toRestconfIdentifier( nodeType ) );
+        builder.append(this.toRestconfIdentifier(nodeType));
         return builder.toString();
     }
 
-    private CharSequence convertToRestconfIdentifier( final NodeIdentifierWithPredicates argument,
-            final ListSchemaNode node ) {
+    private CharSequence convertToRestconfIdentifier(final NodeIdentifierWithPredicates argument,
+            final ListSchemaNode node) {
         QName nodeType = argument.getNodeType();
-        final CharSequence nodeIdentifier = this.toRestconfIdentifier( nodeType );
+        final CharSequence nodeIdentifier = this.toRestconfIdentifier(nodeType);
         final Map<QName, Object> keyValues = argument.getKeyValues();
 
         StringBuilder builder = new StringBuilder();
-        builder.append( "/" );
-        builder.append( nodeIdentifier );
-        builder.append( "/" );
+        builder.append("/");
+        builder.append(nodeIdentifier);
+        builder.append("/");
 
         List<QName> keyDefinition = node.getKeyDefinition();
         boolean hasElements = false;
-        for( final QName key : keyDefinition ) {
-            if( !hasElements ) {
+        for (final QName key : keyDefinition) {
+            if (!hasElements) {
                 hasElements = true;
-            }
-            else {
-                builder.append( "/" );
+            } else {
+                builder.append("/");
             }
 
             try {
-                builder.append( this.toUriString( keyValues.get( key ) ) );
-            } catch( UnsupportedEncodingException e ) {
-                LOG.error( "Error parsing URI: " + keyValues.get( key ), e );
+                builder.append(this.toUriString(keyValues.get(key)));
+            } catch (UnsupportedEncodingException e) {
+                LOG.error("Error parsing URI: {}", keyValues.get(key), e);
                 return null;
             }
         }
@@ -1004,28 +947,22 @@ public class ControllerContext implements SchemaContextListener {
         return builder.toString();
     }
 
-    private static DataSchemaNode childByQName( final Object container, final QName name ) {
-        if( container instanceof ChoiceCaseNode ) {
-            return childByQName( (ChoiceCaseNode) container, name );
-        }
-        else if( container instanceof ChoiceNode ) {
-            return childByQName( (ChoiceNode) container, name );
-        }
-        else if( container instanceof ContainerSchemaNode ) {
-            return childByQName( (ContainerSchemaNode) container, name );
-        }
-        else if( container instanceof ListSchemaNode ) {
-            return childByQName( (ListSchemaNode) container, name );
-        }
-        else if( container instanceof DataSchemaNode ) {
-            return childByQName( (DataSchemaNode) container, name );
-        }
-        else if( container instanceof Module ) {
-            return childByQName( (Module) container, name );
-        }
-        else {
-            throw new IllegalArgumentException( "Unhandled parameter types: "
-                    + Arrays.<Object> asList( container, name ).toString() );
+    private static DataSchemaNode childByQName(final Object container, final QName name) {
+        if (container instanceof ChoiceCaseNode) {
+            return childByQName((ChoiceCaseNode) container, name);
+        } else if (container instanceof ChoiceNode) {
+            return childByQName((ChoiceNode) container, name);
+        } else if (container instanceof ContainerSchemaNode) {
+            return childByQName((ContainerSchemaNode) container, name);
+        } else if (container instanceof ListSchemaNode) {
+            return childByQName((ListSchemaNode) container, name);
+        } else if (container instanceof DataSchemaNode) {
+            return childByQName((DataSchemaNode) container, name);
+        } else if (container instanceof Module) {
+            return childByQName((Module) container, name);
+        } else {
+            throw new IllegalArgumentException("Unhandled parameter types: "
+                    + Arrays.<Object> asList(container, name).toString());
         }
     }
 }
index 934d4434c38a3e724279405da05198099eba2f70..a3d44d3572106232e10edaad73e91d1b4d46039a 100644 (file)
@@ -7,16 +7,14 @@
  */
 package org.opendaylight.controller.sal.restconf.impl;
 
+import com.google.common.base.Preconditions;
 import java.net.URI;
 import java.util.Collections;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.Node;
 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
 
-import com.google.common.base.Preconditions;
-
 public final class EmptyNodeWrapper implements NodeWrapper<Node<?>>, Node<Void> {
 
     private Node<?> unwrapped;
@@ -31,17 +29,17 @@ public final class EmptyNodeWrapper implements NodeWrapper<Node<?>>, Node<Void>
         return composite;
     }
 
-    public void setComposite(boolean composite) {
+    public void setComposite(final boolean composite) {
         this.composite = composite;
     }
 
-    public EmptyNodeWrapper(URI namespace, String localName) {
+    public EmptyNodeWrapper(final URI namespace, final String localName) {
         this.localName = Preconditions.checkNotNull(localName);
         this.namespace = namespace;
     }
 
     @Override
-    public void setQname(QName name) {
+    public void setQname(final QName name) {
         Preconditions.checkState(unwrapped == null, "Cannot change the object, due to data inconsistencies.");
         this.name = name;
     }
@@ -68,7 +66,7 @@ public final class EmptyNodeWrapper implements NodeWrapper<Node<?>>, Node<Void>
     }
 
     @Override
-    public void setNamespace(URI namespace) {
+    public void setNamespace(final URI namespace) {
         Preconditions.checkState(unwrapped == null, "Cannot change the object, due to data inconsistencies.");
         this.namespace = namespace;
     }
@@ -85,8 +83,9 @@ public final class EmptyNodeWrapper implements NodeWrapper<Node<?>>, Node<Void>
                 Preconditions.checkNotNull(namespace);
                 name = new QName(namespace, localName);
             }
-            if(composite) {
-                unwrapped = NodeFactory.createImmutableCompositeNode(name, null, Collections.<Node<?>>emptyList(),null);
+            if (composite) {
+                unwrapped = NodeFactory.createImmutableCompositeNode(name, null, Collections.<Node<?>> emptyList(),
+                        null);
             } else {
                 unwrapped = NodeFactory.createImmutableSimpleNode(name, null, null);
             }
@@ -103,6 +102,7 @@ public final class EmptyNodeWrapper implements NodeWrapper<Node<?>>, Node<Void>
     }
 
     @Override
+    @Deprecated
     public CompositeNode getParent() {
         return unwrap().getParent();
     }
@@ -118,7 +118,7 @@ public final class EmptyNodeWrapper implements NodeWrapper<Node<?>>, Node<Void>
     }
 
     @Override
-    public Void setValue(Void value) {
+    public Void setValue(final Void value) {
         return null;
     }
 
index d66e1610a58e62b07a1834b0c7b61197f49b2ab4..4e797d905739a6b894d2c6a9179b2219af621943 100644 (file)
@@ -16,7 +16,7 @@ public final class IdentityValuesDTO {
     private final List<IdentityValue> elementData = new ArrayList<>();
     private final String originValue;
 
-    public IdentityValuesDTO(String namespace, String value, String prefix,String originValue) {
+    public IdentityValuesDTO(String namespace, String value, String prefix, String originValue) {
         elementData.add(new IdentityValue(namespace, value, prefix));
         this.originValue = originValue;
     }
@@ -37,7 +37,6 @@ public final class IdentityValuesDTO {
         elementData.add(identityValue);
     }
 
-
     public List<IdentityValue> getValuesWithNamespaces() {
         return Collections.unmodifiableList(elementData);
     }
index 68135dea95f1e90e8574d230d7adb202355e8d4d..08e0ce1f24dcc5a8a68e0bd3513fb4bad093b030 100644 (file)
@@ -17,7 +17,8 @@ public class InstanceIdWithSchemaNode {
     private final DataSchemaNode schemaNode;
     private final MountInstance mountPoint;
 
-    public InstanceIdWithSchemaNode(InstanceIdentifier instanceIdentifier, DataSchemaNode schemaNode, MountInstance mountPoint) {
+    public InstanceIdWithSchemaNode(InstanceIdentifier instanceIdentifier, DataSchemaNode schemaNode,
+            MountInstance mountPoint) {
         this.instanceIdentifier = instanceIdentifier;
         this.schemaNode = schemaNode;
         this.mountPoint = mountPoint;
index 48fd1a3dfc49e4abf6d22ae040cf504781ff0bc8..9637a36268860e13e8ac296004089aed6c8ce825 100644 (file)
@@ -8,7 +8,6 @@
 package org.opendaylight.controller.sal.restconf.impl;
 
 import java.net.URI;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.Node;
 
index 265cc5db4536c96ecbf51bf4005ff4ced54e8c14..92a7014438cff009299fdd3a2cf37ae8959d0d6b 100644 (file)
@@ -12,7 +12,6 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-
 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
 import org.opendaylight.controller.sal.rest.impl.RestUtil;
 import org.opendaylight.controller.sal.restconf.impl.IdentityValuesDTO.IdentityValue;
@@ -47,7 +46,8 @@ public class RestCodec {
     private RestCodec() {
     }
 
-    public static final Codec<Object, Object> from(TypeDefinition<?> typeDefinition, MountInstance mountPoint) {
+    public static final Codec<Object, Object> from(final TypeDefinition<?> typeDefinition,
+            final MountInstance mountPoint) {
         return new ObjectCodec(typeDefinition, mountPoint);
     }
 
@@ -62,7 +62,7 @@ public class RestCodec {
 
         private final TypeDefinition<?> type;
 
-        private ObjectCodec(TypeDefinition<?> typeDefinition, MountInstance mountPoint) {
+        private ObjectCodec(final TypeDefinition<?> typeDefinition, final MountInstance mountPoint) {
             type = RestUtil.resolveBaseTypeFrom(typeDefinition);
             if (type instanceof IdentityrefTypeDefinition) {
                 identityrefCodec = new IdentityrefCodecImpl(mountPoint);
@@ -78,7 +78,7 @@ public class RestCodec {
 
         @SuppressWarnings("unchecked")
         @Override
-        public Object deserialize(Object input) {
+        public Object deserialize(final Object input) {
             try {
                 if (type instanceof IdentityrefTypeDefinition) {
                     if (input instanceof IdentityValuesDTO) {
@@ -90,7 +90,7 @@ public class RestCodec {
                     return null;
                 } else if (type instanceof LeafrefTypeDefinition) {
                     if (input instanceof IdentityValuesDTO) {
-                        return LEAFREF_DEFAULT_CODEC.deserialize(((IdentityValuesDTO)input).getOriginValue());
+                        return LEAFREF_DEFAULT_CODEC.deserialize(((IdentityValuesDTO) input).getOriginValue());
                     }
                     return LEAFREF_DEFAULT_CODEC.deserialize(input);
                 } else if (type instanceof InstanceIdentifierTypeDefinition) {
@@ -106,7 +106,7 @@ public class RestCodec {
                             .from(type);
                     if (typeAwarecodec != null) {
                         if (input instanceof IdentityValuesDTO) {
-                            return typeAwarecodec.deserialize(((IdentityValuesDTO)input).getOriginValue());
+                            return typeAwarecodec.deserialize(((IdentityValuesDTO) input).getOriginValue());
                         }
                         return typeAwarecodec.deserialize(String.valueOf(input));
                     } else {
@@ -115,8 +115,7 @@ public class RestCodec {
                         return null;
                     }
                 }
-            } catch (ClassCastException e) { // TODO remove this catch when
-                                             // everyone use codecs
+            } catch (ClassCastException e) { // TODO remove this catch when everyone use codecs
                 logger.error(
                         "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input),
                         e);
@@ -126,7 +125,7 @@ public class RestCodec {
 
         @SuppressWarnings("unchecked")
         @Override
-        public Object serialize(Object input) {
+        public Object serialize(final Object input) {
             try {
                 if (type instanceof IdentityrefTypeDefinition) {
                     return identityrefCodec.serialize(input);
@@ -145,8 +144,7 @@ public class RestCodec {
                         return null;
                     }
                 }
-            } catch (ClassCastException e) { // TODO remove this catch when
-                                             // everyone use codecs
+            } catch (ClassCastException e) { // TODO remove this catch when everyone use codecs
                 logger.error(
                         "ClassCastException was thrown when codec is invoked with parameter " + String.valueOf(input),
                         e);
@@ -162,17 +160,17 @@ public class RestCodec {
 
         private final MountInstance mountPoint;
 
-        public IdentityrefCodecImpl(MountInstance mountPoint) {
+        public IdentityrefCodecImpl(final MountInstance mountPoint) {
             this.mountPoint = mountPoint;
         }
 
         @Override
-        public IdentityValuesDTO serialize(QName data) {
-            return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), data.getPrefix(),null);
+        public IdentityValuesDTO serialize(final QName data) {
+            return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), data.getPrefix(), null);
         }
 
         @Override
-        public QName deserialize(IdentityValuesDTO data) {
+        public QName deserialize(final IdentityValuesDTO data) {
             IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
             Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), mountPoint);
             if (module == null) {
@@ -189,12 +187,12 @@ public class RestCodec {
     public static class LeafrefCodecImpl implements LeafrefCodec<String> {
 
         @Override
-        public String serialize(Object data) {
+        public String serialize(final Object data) {
             return String.valueOf(data);
         }
 
         @Override
-        public Object deserialize(String data) {
+        public Object deserialize(final String data) {
             return data;
         }
 
@@ -204,15 +202,14 @@ public class RestCodec {
         private final Logger logger = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class);
         private final MountInstance mountPoint;
 
-        public InstanceIdentifierCodecImpl(MountInstance mountPoint) {
+        public InstanceIdentifierCodecImpl(final MountInstance mountPoint) {
             this.mountPoint = mountPoint;
         }
 
         @Override
-        public IdentityValuesDTO serialize(InstanceIdentifier data) {
-            List<PathArgument> pathArguments = data.getPath();
+        public IdentityValuesDTO serialize(final InstanceIdentifier data) {
             IdentityValuesDTO identityValuesDTO = new IdentityValuesDTO();
-            for (PathArgument pathArgument : pathArguments) {
+            for (PathArgument pathArgument : data.getPathArguments()) {
                 IdentityValue identityValue = qNameToIdentityValue(pathArgument.getNodeType());
                 if (pathArgument instanceof NodeIdentifierWithPredicates && identityValue != null) {
                     List<Predicate> predicates = keyValuesToPredicateList(((NodeIdentifierWithPredicates) pathArgument)
@@ -230,13 +227,15 @@ public class RestCodec {
         }
 
         @Override
-        public InstanceIdentifier deserialize(IdentityValuesDTO data) {
+        public InstanceIdentifier deserialize(final IdentityValuesDTO data) {
             List<PathArgument> result = new ArrayList<PathArgument>();
             IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
             Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), mountPoint);
             if (module == null) {
-                logger.info("Module by namespace '{}' of first node in instance-identiefier was not found.", valueWithNamespace.getNamespace());
-                logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(valueWithNamespace.getValue()));
+                logger.info("Module by namespace '{}' of first node in instance-identiefier was not found.",
+                        valueWithNamespace.getNamespace());
+                logger.info("Instance-identifier will be translated as NULL for data - {}",
+                        String.valueOf(valueWithNamespace.getValue()));
                 return null;
             }
 
@@ -249,7 +248,8 @@ public class RestCodec {
                         parentContainer, identityValue.getValue(), validNamespace);
                 if (node == null) {
                     logger.info("'{}' node was not found in {}", identityValue, parentContainer.getChildNodes());
-                    logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue()));
+                    logger.info("Instance-identifier will be translated as NULL for data - {}",
+                            String.valueOf(identityValue.getValue()));
                     return null;
                 }
                 QName qName = node.getQName();
@@ -261,7 +261,8 @@ public class RestCodec {
                         Predicate leafListPredicate = identityValue.getPredicates().get(0);
                         if (!leafListPredicate.isLeafList()) {
                             logger.info("Predicate's data is not type of leaf-list. It should be in format \".='value'\"");
-                            logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue()));
+                            logger.info("Instance-identifier will be translated as NULL for data - {}",
+                                    String.valueOf(identityValue.getValue()));
                             return null;
                         }
                         pathArgument = new NodeWithValue(qName, leafListPredicate.getValue());
@@ -270,33 +271,37 @@ public class RestCodec {
                         Map<QName, Object> predicatesMap = new HashMap<>();
                         for (Predicate predicate : identityValue.getPredicates()) {
                             validNamespace = resolveValidNamespace(predicate.getName().getNamespace(), mountPoint);
-                            DataSchemaNode listKey = ControllerContext.getInstance().findInstanceDataChildByNameAndNamespace(
-                                    listNode, predicate.getName().getValue(), validNamespace);
+                            DataSchemaNode listKey = ControllerContext.getInstance()
+                                    .findInstanceDataChildByNameAndNamespace(listNode, predicate.getName().getValue(),
+                                            validNamespace);
                             predicatesMap.put(listKey.getQName(), predicate.getValue());
                         }
                         pathArgument = new NodeIdentifierWithPredicates(qName, predicatesMap);
                     } else {
                         logger.info("Node {} is not List or Leaf-list.", node);
-                        logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue()));
+                        logger.info("Instance-identifier will be translated as NULL for data - {}",
+                                String.valueOf(identityValue.getValue()));
                         return null;
                     }
                 }
                 result.add(pathArgument);
-                if (i < identities.size() - 1) { // last element in instance-identifier can be other than DataNodeContainer
+                if (i < identities.size() - 1) { // last element in instance-identifier can be other than
+                                                 // DataNodeContainer
                     if (node instanceof DataNodeContainer) {
                         parentContainer = (DataNodeContainer) node;
                     } else {
                         logger.info("Node {} isn't instance of DataNodeContainer", node);
-                        logger.info("Instance-identifier will be translated as NULL for data - {}", String.valueOf(identityValue.getValue()));
+                        logger.info("Instance-identifier will be translated as NULL for data - {}",
+                                String.valueOf(identityValue.getValue()));
                         return null;
                     }
                 }
             }
 
-            return result.isEmpty() ? null : new InstanceIdentifier(result);
+            return result.isEmpty() ? null : InstanceIdentifier.create(result);
         }
 
-        private List<Predicate> keyValuesToPredicateList(Map<QName, Object> keyValues) {
+        private List<Predicate> keyValuesToPredicateList(final Map<QName, Object> keyValues) {
             List<Predicate> result = new ArrayList<>();
             for (QName qName : keyValues.keySet()) {
                 Object value = keyValues.get(qName);
@@ -305,7 +310,7 @@ public class RestCodec {
             return result;
         }
 
-        private IdentityValue qNameToIdentityValue(QName qName) {
+        private IdentityValue qNameToIdentityValue(final QName qName) {
             if (qName != null) {
                 return new IdentityValue(qName.getNamespace().toString(), qName.getLocalName(), qName.getPrefix());
             }
@@ -313,7 +318,7 @@ public class RestCodec {
         }
     }
 
-    private static Module getModuleByNamespace(String namespace, MountInstance mountPoint) {
+    private static Module getModuleByNamespace(final String namespace, final MountInstance mountPoint) {
         URI validNamespace = resolveValidNamespace(namespace, mountPoint);
 
         Module module = null;
@@ -329,7 +334,7 @@ public class RestCodec {
         return module;
     }
 
-    private static URI resolveValidNamespace(String namespace, MountInstance mountPoint) {
+    private static URI resolveValidNamespace(final String namespace, final MountInstance mountPoint) {
         URI validNamespace;
         if (mountPoint != null) {
             validNamespace = ControllerContext.getInstance().findNamespaceByModuleName(mountPoint, namespace);
index 0548e95044e081592ef9bb7d49513b8be7ab48bb..e3e0c3a2bdc49cbf8fca3bb8104e673fa2ea0b2c 100644 (file)
@@ -8,20 +8,17 @@
 
 package org.opendaylight.controller.sal.restconf.impl;
 
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
 import java.util.List;
-
 import javax.ws.rs.WebApplicationException;
 import javax.ws.rs.core.Response.Status;
-
 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
 
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableList;
-
 /**
- * Unchecked exception to communicate error information, as defined in the ietf restcong draft,
- * to be sent to the client.
+ * Unchecked exception to communicate error information, as defined in the ietf restcong draft, to be sent to the
+ * client.
  *
  * @author Devin Avery
  * @author Thomas Pantelis
@@ -35,70 +32,76 @@ public class RestconfDocumentedException extends WebApplicationException {
     private final Status status;
 
     /**
-     * Constructs an instance with an error message. The error type defaults to APPLICATION and
-     * the error tag defaults to OPERATION_FAILED.
+     * Constructs an instance with an error message. The error type defaults to APPLICATION and the error tag defaults
+     * to OPERATION_FAILED.
      *
-     * @param message A string which provides a plain text string describing the error.
+     * @param message
+     *            A string which provides a plain text string describing the error.
      */
-    public RestconfDocumentedException( String message ) {
-        this( message, RestconfError.ErrorType.APPLICATION, RestconfError.ErrorTag.OPERATION_FAILED );
+    public RestconfDocumentedException(String message) {
+        this(message, RestconfError.ErrorType.APPLICATION, RestconfError.ErrorTag.OPERATION_FAILED);
     }
 
     /**
      * Constructs an instance with an error message, error type, and error tag.
      *
-     * @param message A string which provides a plain text string describing the error.
-     * @param errorType The enumerated type indicating the layer where the error occurred.
-     * @param errorTag The enumerated tag representing a more specific error cause.
+     * @param message
+     *            A string which provides a plain text string describing the error.
+     * @param errorType
+     *            The enumerated type indicating the layer where the error occurred.
+     * @param errorTag
+     *            The enumerated tag representing a more specific error cause.
      */
-    public RestconfDocumentedException( String message, ErrorType errorType, ErrorTag errorTag ) {
-        this( null, new RestconfError( errorType, errorTag, message ) );
+    public RestconfDocumentedException(String message, ErrorType errorType, ErrorTag errorTag) {
+        this(null, new RestconfError(errorType, errorTag, message));
     }
 
     /**
-     * Constructs an instance with an error message and exception cause. The stack trace of the
-     * exception is included in the error info.
+     * Constructs an instance with an error message and exception cause. The stack trace of the exception is included in
+     * the error info.
      *
-     * @param message A string which provides a plain text string describing the error.
-     * @param cause The underlying exception cause.
+     * @param message
+     *            A string which provides a plain text string describing the error.
+     * @param cause
+     *            The underlying exception cause.
      */
-    public RestconfDocumentedException( String message, Throwable cause ) {
-        this( cause, new RestconfError( RestconfError.ErrorType.APPLICATION,
-                                        RestconfError.ErrorTag.OPERATION_FAILED, message,
-                                        null, RestconfError.toErrorInfo( cause ) ) );
+    public RestconfDocumentedException(String message, Throwable cause) {
+        this(cause, new RestconfError(RestconfError.ErrorType.APPLICATION, RestconfError.ErrorTag.OPERATION_FAILED,
+                message, null, RestconfError.toErrorInfo(cause)));
     }
 
     /**
      * Constructs an instance with the given error.
      */
-    public RestconfDocumentedException( RestconfError error ) {
-        this( null, error );
+    public RestconfDocumentedException(RestconfError error) {
+        this(null, error);
     }
 
     /**
      * Constructs an instance with the given errors.
      */
-    public RestconfDocumentedException( List<RestconfError> errors ) {
-        this.errors = ImmutableList.copyOf( errors );
-        Preconditions.checkArgument( !this.errors.isEmpty(), "RestconfError list can't be empty" );
+    public RestconfDocumentedException(List<RestconfError> errors) {
+        this.errors = ImmutableList.copyOf(errors);
+        Preconditions.checkArgument(!this.errors.isEmpty(), "RestconfError list can't be empty");
         status = null;
     }
 
     /**
      * Constructs an instance with an HTTP status and no error information.
      *
-     * @param status the HTTP status.
+     * @param status
+     *            the HTTP status.
      */
-    public RestconfDocumentedException( Status status ) {
-        Preconditions.checkNotNull( status, "Status can't be null" );
+    public RestconfDocumentedException(Status status) {
+        Preconditions.checkNotNull(status, "Status can't be null");
         errors = ImmutableList.of();
         this.status = status;
     }
 
-    private RestconfDocumentedException( Throwable cause, RestconfError error ) {
-        super( cause );
-        Preconditions.checkNotNull( error, "RestconfError can't be null" );
-        errors = ImmutableList.of( error );
+    private RestconfDocumentedException(Throwable cause, RestconfError error) {
+        super(cause);
+        Preconditions.checkNotNull(error, "RestconfError can't be null");
+        errors = ImmutableList.of(error);
         status = null;
     }
 
@@ -110,7 +113,6 @@ public class RestconfDocumentedException extends WebApplicationException {
         return status;
     }
 
-
     @Override
     public String getMessage() {
         return "errors: " + errors + (status != null ? ", status: " + status : "");
index cc279cbd58e68cfc98634364a30002051f698441..ed20bd01a5047e4d746858ff4adde4fe7de0c701 100644 (file)
@@ -1,23 +1,23 @@
 /*
-* Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*/
+ * Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
 package org.opendaylight.controller.sal.restconf.impl;
 
+import com.google.common.base.Preconditions;
 import java.io.PrintWriter;
 import java.io.StringWriter;
-
 import org.opendaylight.yangtools.yang.common.RpcError;
 
-import com.google.common.base.Preconditions;
-
 /**
  * Encapsulates a restconf error as defined in the ietf restconf draft.
  *
- * <br><br><b>Note:</b> Enumerations defined within are provided by the ietf restconf draft.
+ * <br>
+ * <br>
+ * <b>Note:</b> Enumerations defined within are provided by the ietf restconf draft.
  *
  * @author Devin Avery
  * @see {@link https://tools.ietf.org/html/draft-bierman-netconf-restconf-02}
@@ -38,37 +38,35 @@ public class RestconfError {
             return name().toLowerCase();
         }
 
-        public static ErrorType valueOfCaseInsensitive( String value )
-        {
+        public static ErrorType valueOfCaseInsensitive(String value) {
             try {
-                return ErrorType.valueOf( ErrorType.class, value.toUpperCase() );
-            }
-            catch( IllegalArgumentException e ) {
+                return ErrorType.valueOf(ErrorType.class, value.toUpperCase());
+            } catch (IllegalArgumentException e) {
                 return APPLICATION;
             }
         }
     }
 
     public static enum ErrorTag {
-        IN_USE( "in-use", 409 /*Conflict*/ ),
-        INVALID_VALUE( "invalid-value", 400 /*Bad Request*/ ),
-        TOO_BIG( "too-big", 413 /*Request Entity Too Large*/ ),
-        MISSING_ATTRIBUTE( "missing-attribute", 400 /*Bad Request*/ ),
-        BAD_ATTRIBUTE( "bad-attribute", 400 /*Bad Request*/ ),
-        UNKNOWN_ATTRIBUTE( "unknown-attribute", 400 /*Bad Request*/ ),
-        BAD_ELEMENT( "bad-element", 400 /*Bad Request*/ ),
-        UNKNOWN_ELEMENT( "unknown-element", 400 /*Bad Request*/ ),
-        UNKNOWN_NAMESPACE( "unknown-namespace", 400 /*Bad Request*/ ),
-        ACCESS_DENIED( "access-denied", 403 /*Forbidden*/ ),
-        LOCK_DENIED( "lock-denied", 409 /*Conflict*/ ),
-        RESOURCE_DENIED( "resource-denied", 409 /*Conflict*/ ),
-        ROLLBACK_FAILED( "rollback-failed", 500 /*INTERNAL_SERVER_ERROR*/ ),
-        DATA_EXISTS( "data-exists", 409 /*Conflict*/ ),
-        DATA_MISSING( "data-missing", 409 /*Conflict*/ ),
-        OPERATION_NOT_SUPPORTED( "operation-not-supported", 501 /*Not Implemented*/ ),
-        OPERATION_FAILED( "operation-failed", 500 /*INTERNAL_SERVER_ERROR*/ ),
-        PARTIAL_OPERATION( "partial-operation", 500 /*INTERNAL_SERVER_ERROR*/ ),
-        MALFORMED_MESSAGE( "malformed-message", 400 /*Bad Request*/ );
+        IN_USE("in-use", 409 /* Conflict */),
+        INVALID_VALUE("invalid-value", 400 /* Bad Request */),
+        TOO_BIG("too-big", 413 /* Request Entity Too Large */),
+        MISSING_ATTRIBUTE("missing-attribute", 400 /* Bad Request */),
+        BAD_ATTRIBUTE("bad-attribute", 400 /* Bad Request */),
+        UNKNOWN_ATTRIBUTE("unknown-attribute", 400 /* Bad Request */),
+        BAD_ELEMENT("bad-element", 400 /* Bad Request */),
+        UNKNOWN_ELEMENT("unknown-element", 400 /* Bad Request */),
+        UNKNOWN_NAMESPACE("unknown-namespace", 400 /* Bad Request */),
+        ACCESS_DENIED("access-denied", 403 /* Forbidden */),
+        LOCK_DENIED("lock-denied", 409 /* Conflict */),
+        RESOURCE_DENIED("resource-denied", 409 /* Conflict */),
+        ROLLBACK_FAILED("rollback-failed", 500 /* INTERNAL_SERVER_ERROR */),
+        DATA_EXISTS("data-exists", 409 /* Conflict */),
+        DATA_MISSING("data-missing", 409 /* Conflict */),
+        OPERATION_NOT_SUPPORTED("operation-not-supported", 501 /* Not Implemented */),
+        OPERATION_FAILED("operation-failed", 500 /* INTERNAL_SERVER_ERROR */),
+        PARTIAL_OPERATION("partial-operation", 500 /* INTERNAL_SERVER_ERROR */),
+        MALFORMED_MESSAGE("malformed-message", 400 /* Bad Request */);
 
         private final String tagValue;
         private final int statusCode;
@@ -82,12 +80,10 @@ public class RestconfError {
             return this.tagValue.toLowerCase();
         }
 
-        public static ErrorTag valueOfCaseInsensitive( String value )
-        {
+        public static ErrorTag valueOfCaseInsensitive(String value) {
             try {
-                return ErrorTag.valueOf( ErrorTag.class, value.toUpperCase().replaceAll( "-","_" ) );
-            }
-            catch( IllegalArgumentException e ) {
+                return ErrorTag.valueOf(ErrorTag.class, value.toUpperCase().replaceAll("-", "_"));
+            } catch (IllegalArgumentException e) {
                 return OPERATION_FAILED;
             }
         }
@@ -102,53 +98,63 @@ public class RestconfError {
     private final String errorInfo;
     private final String errorAppTag;
     private final String errorMessage;
-    //TODO: Add in the error-path concept as defined in the ietf draft.
 
-    static String toErrorInfo( Throwable cause ) {
+    // TODO: Add in the error-path concept as defined in the ietf draft.
+
+    static String toErrorInfo(Throwable cause) {
         StringWriter writer = new StringWriter();
-        cause.printStackTrace( new PrintWriter( writer ) );
+        cause.printStackTrace(new PrintWriter(writer));
         return writer.toString();
     }
 
     /**
      * Constructs a RestConfError
      *
-     * @param errorType The enumerated type indicating the layer where the error occurred.
-     * @param errorTag The enumerated tag representing a more specific error cause.
-     * @param errorMessage A string which provides a plain text string describing the error.
+     * @param errorType
+     *            The enumerated type indicating the layer where the error occurred.
+     * @param errorTag
+     *            The enumerated tag representing a more specific error cause.
+     * @param errorMessage
+     *            A string which provides a plain text string describing the error.
      */
     public RestconfError(ErrorType errorType, ErrorTag errorTag, String errorMessage) {
-        this( errorType, errorTag, errorMessage, null );
+        this(errorType, errorTag, errorMessage, null);
     }
 
     /**
      * Constructs a RestConfError object.
      *
-     * @param errorType The enumerated type indicating the layer where the error occurred.
-     * @param errorTag The enumerated tag representing a more specific error cause.
-     * @param errorMessage A string which provides a plain text string describing the error.
-     * @param errorAppTag A string which represents an application-specific error tag that further
-     *                    specifies the error cause.
+     * @param errorType
+     *            The enumerated type indicating the layer where the error occurred.
+     * @param errorTag
+     *            The enumerated tag representing a more specific error cause.
+     * @param errorMessage
+     *            A string which provides a plain text string describing the error.
+     * @param errorAppTag
+     *            A string which represents an application-specific error tag that further specifies the error cause.
      */
-    public RestconfError(ErrorType errorType, ErrorTag errorTag, String errorMessage,
-                         String errorAppTag) {
-        this( errorType, errorTag, errorMessage, errorAppTag, null );
+    public RestconfError(ErrorType errorType, ErrorTag errorTag, String errorMessage, String errorAppTag) {
+        this(errorType, errorTag, errorMessage, errorAppTag, null);
     }
 
     /**
      * Constructs a RestConfError object.
      *
-     * @param errorType The enumerated type indicating the layer where the error occurred.
-     * @param errorTag The enumerated tag representing a more specific error cause.
-     * @param errorMessage A string which provides a plain text string describing the error.
-     * @param errorAppTag A string which represents an application-specific error tag that further
-     *                    specifies the error cause.
-     * @param errorInfo A string, <b>formatted as XML</b>, which contains additional error information.
+     * @param errorType
+     *            The enumerated type indicating the layer where the error occurred.
+     * @param errorTag
+     *            The enumerated tag representing a more specific error cause.
+     * @param errorMessage
+     *            A string which provides a plain text string describing the error.
+     * @param errorAppTag
+     *            A string which represents an application-specific error tag that further specifies the error cause.
+     * @param errorInfo
+     *            A string, <b>formatted as XML</b>, which contains additional error information.
      */
-    public RestconfError(ErrorType errorType, ErrorTag errorTag, String errorMessage,
-                         String errorAppTag, String errorInfo) {
-        Preconditions.checkNotNull( errorType, "Error type is required for RestConfError" );
-        Preconditions.checkNotNull( errorTag, "Error tag is required for RestConfError");
+    public RestconfError(ErrorType errorType, ErrorTag errorTag, String errorMessage, String errorAppTag,
+            String errorInfo) {
+        Preconditions.checkNotNull(errorType, "Error type is required for RestConfError");
+        Preconditions.checkNotNull(errorTag, "Error tag is required for RestConfError");
         this.errorType = errorType;
         this.errorTag = errorTag;
         this.errorMessage = errorMessage;
@@ -159,28 +165,25 @@ public class RestconfError {
     /**
      * Constructs a RestConfError object from an RpcError.
      */
-    public RestconfError( RpcError rpcError ) {
+    public RestconfError(RpcError rpcError) {
 
-        this.errorType = rpcError.getErrorType() == null ? ErrorType.APPLICATION :
-                               ErrorType.valueOfCaseInsensitive( rpcError.getErrorType().name() );
+        this.errorType = rpcError.getErrorType() == null ? ErrorType.APPLICATION : ErrorType
+                .valueOfCaseInsensitive(rpcError.getErrorType().name());
 
-        this.errorTag = rpcError.getTag() == null ? ErrorTag.OPERATION_FAILED :
-                                    ErrorTag.valueOfCaseInsensitive( rpcError.getTag().toString() );
+        this.errorTag = rpcError.getTag() == null ? ErrorTag.OPERATION_FAILED : ErrorTag
+                .valueOfCaseInsensitive(rpcError.getTag().toString());
 
         this.errorMessage = rpcError.getMessage();
         this.errorAppTag = rpcError.getApplicationTag();
 
         String errorInfo = null;
-        if( rpcError.getInfo() == null ) {
-            if( rpcError.getCause() != null ) {
-                errorInfo = toErrorInfo( rpcError.getCause() );
+        if (rpcError.getInfo() == null) {
+            if (rpcError.getCause() != null) {
+                errorInfo = toErrorInfo(rpcError.getCause());
+            } else if (rpcError.getSeverity() != null) {
+                errorInfo = "<severity>" + rpcError.getSeverity().toString().toLowerCase() + "</severity>";
             }
-            else if( rpcError.getSeverity() != null ) {
-                errorInfo = "<severity>" + rpcError.getSeverity().toString().toLowerCase() +
-                            "</severity>";
-            }
-        }
-        else {
+        } else {
             errorInfo = rpcError.getInfo();
         }
 
@@ -209,8 +212,7 @@ public class RestconfError {
 
     @Override
     public String toString() {
-        return "error-type: " + errorType.getErrorTypeTag()
-                + ", error-tag: " + errorTag.getTagValue() + ", "
+        return "error-type: " + errorType.getErrorTypeTag() + ", error-tag: " + errorTag.getTagValue() + ", "
                 + (errorAppTag != null ? "error-app-tag: " + errorAppTag + ", " : "")
                 + (errorMessage != null ? "error-message: " + errorMessage : "")
                 + (errorInfo != null ? "error-info: " + errorInfo + ", " : "") + "]";
index 9700d48bc298f30576796d76a72489d5ae0900da..bb7547d3302f1d172c1271416c08e0895ac46398 100644 (file)
@@ -25,6 +25,7 @@ import java.util.Collections;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.Future;
 import javax.ws.rs.core.Response;
@@ -51,11 +52,14 @@ import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.InstanceIdentifierBuilder;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
 import org.opendaylight.yangtools.yang.data.api.Node;
 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
 import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
+import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
@@ -74,13 +78,29 @@ import org.opendaylight.yangtools.yang.parser.builder.impl.ContainerSchemaNodeBu
 import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder;
 
 public class RestconfImpl implements RestconfService {
+    private enum UriParameters {
+        PRETTY_PRINT("prettyPrint"),
+        DEPTH("depth");
+
+        private String uriParameterName;
+
+        UriParameters(String uriParameterName) {
+            this.uriParameterName = uriParameterName;
+        }
+
+        @Override
+        public String toString() {
+            return uriParameterName;
+        }
+    }
+
     private final static RestconfImpl INSTANCE = new RestconfImpl();
 
     private static final int CHAR_NOT_FOUND = -1;
 
     private final static String MOUNT_POINT_MODULE_NAME = "ietf-netconf";
 
-    private final static SimpleDateFormat REVISION_FORMAT =  new SimpleDateFormat("yyyy-MM-dd");
+    private final static SimpleDateFormat REVISION_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
 
     private final static String SAL_REMOTE_NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote";
 
@@ -106,12 +126,12 @@ public class RestconfImpl implements RestconfService {
     }
 
     @Override
-    public StructuredData getModules() {
+    public StructuredData getModules(final UriInfo uriInfo) {
         final Module restconfModule = this.getRestconfModule();
 
         final List<Node<?>> modulesAsData = new ArrayList<Node<?>>();
-        final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
-                                        restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
+        final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
+                Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
 
         Set<Module> allModules = this.controllerContext.getAllModules();
         for (final Module module : allModules) {
@@ -119,135 +139,128 @@ public class RestconfImpl implements RestconfService {
             modulesAsData.add(moduleCompositeNode);
         }
 
-        final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
-                                   restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
+        final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
+                Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
         QName qName = modulesSchemaNode.getQName();
         final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData);
-        return new StructuredData(modulesNode, modulesSchemaNode, null);
+        return new StructuredData(modulesNode, modulesSchemaNode, null, parsePrettyPrintParameter(uriInfo));
     }
 
     @Override
-    public StructuredData getAvailableStreams() {
+    public StructuredData getAvailableStreams(final UriInfo uriInfo) {
         Set<String> availableStreams = Notificator.getStreamNames();
 
         final List<Node<?>> streamsAsData = new ArrayList<Node<?>>();
         Module restconfModule = this.getRestconfModule();
-        final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
-                                             restconfModule, Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
+        final DataSchemaNode streamSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
+                Draft02.RestConfModule.STREAM_LIST_SCHEMA_NODE);
         for (final String streamName : availableStreams) {
             streamsAsData.add(this.toStreamCompositeNode(streamName, streamSchemaNode));
         }
 
-        final DataSchemaNode streamsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
-                                     restconfModule, Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
+        final DataSchemaNode streamsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
+                Draft02.RestConfModule.STREAMS_CONTAINER_SCHEMA_NODE);
         QName qName = streamsSchemaNode.getQName();
         final CompositeNode streamsNode = NodeFactory.createImmutableCompositeNode(qName, null, streamsAsData);
-        return new StructuredData(streamsNode, streamsSchemaNode, null);
+        return new StructuredData(streamsNode, streamsSchemaNode, null, parsePrettyPrintParameter(uriInfo));
     }
 
     @Override
-    public StructuredData getModules(final String identifier) {
+    public StructuredData getModules(final String identifier, final UriInfo uriInfo) {
         Set<Module> modules = null;
         MountInstance mountPoint = null;
         if (identifier.contains(ControllerContext.MOUNT)) {
-            InstanceIdWithSchemaNode mountPointIdentifier =
-                                           this.controllerContext.toMountPointIdentifier(identifier);
+            InstanceIdWithSchemaNode mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
             mountPoint = mountPointIdentifier.getMountPoint();
             modules = this.controllerContext.getAllModules(mountPoint);
-        }
-        else {
+        } else {
             throw new RestconfDocumentedException(
-                    "URI has bad format. If modules behind mount point should be showed, URI has to end with " +
-                    ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                    "URI has bad format. If modules behind mount point should be showed, URI has to end with "
+                            + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
         final List<Node<?>> modulesAsData = new ArrayList<Node<?>>();
         Module restconfModule = this.getRestconfModule();
-        final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
-                                         restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
+        final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
+                Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
 
         for (final Module module : modules) {
             modulesAsData.add(this.toModuleCompositeNode(module, moduleSchemaNode));
         }
 
-        final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
-                                  restconfModule, Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
+        final DataSchemaNode modulesSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
+                Draft02.RestConfModule.MODULES_CONTAINER_SCHEMA_NODE);
         QName qName = modulesSchemaNode.getQName();
         final CompositeNode modulesNode = NodeFactory.createImmutableCompositeNode(qName, null, modulesAsData);
-        return new StructuredData(modulesNode, modulesSchemaNode, mountPoint);
+        return new StructuredData(modulesNode, modulesSchemaNode, mountPoint, parsePrettyPrintParameter(uriInfo));
     }
 
     @Override
-    public StructuredData getModule(final String identifier) {
+    public StructuredData getModule(final String identifier, final UriInfo uriInfo) {
         final QName moduleNameAndRevision = this.getModuleNameAndRevision(identifier);
         Module module = null;
         MountInstance mountPoint = null;
         if (identifier.contains(ControllerContext.MOUNT)) {
-            InstanceIdWithSchemaNode mountPointIdentifier =
-                                            this.controllerContext.toMountPointIdentifier(identifier);
+            InstanceIdWithSchemaNode mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
             mountPoint = mountPointIdentifier.getMountPoint();
             module = this.controllerContext.findModuleByNameAndRevision(mountPoint, moduleNameAndRevision);
-        }
-        else {
+        } else {
             module = this.controllerContext.findModuleByNameAndRevision(moduleNameAndRevision);
         }
 
         if (module == null) {
-            throw new RestconfDocumentedException(
-                    "Module with name '" + moduleNameAndRevision.getLocalName() + "' and revision '" +
-                    moduleNameAndRevision.getRevision() + "' was not found.",
-                    ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT );
+            throw new RestconfDocumentedException("Module with name '" + moduleNameAndRevision.getLocalName()
+                    + "' and revision '" + moduleNameAndRevision.getRevision() + "' was not found.",
+                    ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
         }
 
         Module restconfModule = this.getRestconfModule();
-        final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
-                                          restconfModule, Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
+        final DataSchemaNode moduleSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(restconfModule,
+                Draft02.RestConfModule.MODULE_LIST_SCHEMA_NODE);
         final CompositeNode moduleNode = this.toModuleCompositeNode(module, moduleSchemaNode);
-        return new StructuredData(moduleNode, moduleSchemaNode, mountPoint);
+        return new StructuredData(moduleNode, moduleSchemaNode, mountPoint, parsePrettyPrintParameter(uriInfo));
     }
 
     @Override
-    public StructuredData getOperations() {
+    public StructuredData getOperations(final UriInfo uriInfo) {
         Set<Module> allModules = this.controllerContext.getAllModules();
-        return this.operationsFromModulesToStructuredData(allModules, null);
+        return this.operationsFromModulesToStructuredData(allModules, null, parsePrettyPrintParameter(uriInfo));
     }
 
     @Override
-    public StructuredData getOperations(final String identifier) {
+    public StructuredData getOperations(final String identifier, final UriInfo uriInfo) {
         Set<Module> modules = null;
         MountInstance mountPoint = null;
         if (identifier.contains(ControllerContext.MOUNT)) {
-            InstanceIdWithSchemaNode mountPointIdentifier =
-                                         this.controllerContext.toMountPointIdentifier(identifier);
+            InstanceIdWithSchemaNode mountPointIdentifier = this.controllerContext.toMountPointIdentifier(identifier);
             mountPoint = mountPointIdentifier.getMountPoint();
             modules = this.controllerContext.getAllModules(mountPoint);
-        }
-        else {
+        } else {
             throw new RestconfDocumentedException(
-                    "URI has bad format. If operations behind mount point should be showed, URI has to end with " +
-                    ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                    "URI has bad format. If operations behind mount point should be showed, URI has to end with "
+                            + ControllerContext.MOUNT, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
-        return this.operationsFromModulesToStructuredData(modules, mountPoint);
+        return this.operationsFromModulesToStructuredData(modules, mountPoint, parsePrettyPrintParameter(uriInfo));
     }
 
     private StructuredData operationsFromModulesToStructuredData(final Set<Module> modules,
-                                                                 final MountInstance mountPoint) {
+            final MountInstance mountPoint, boolean prettyPrint) {
         final List<Node<?>> operationsAsData = new ArrayList<Node<?>>();
         Module restconfModule = this.getRestconfModule();
         final DataSchemaNode operationsSchemaNode = controllerContext.getRestconfModuleRestConfSchemaNode(
-                              restconfModule, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
+                restconfModule, Draft02.RestConfModule.OPERATIONS_CONTAINER_SCHEMA_NODE);
         QName qName = operationsSchemaNode.getQName();
         SchemaPath path = operationsSchemaNode.getPath();
-        ContainerSchemaNodeBuilder containerSchemaNodeBuilder =
-                             new ContainerSchemaNodeBuilder(Draft02.RestConfModule.NAME, 0, qName, path);
+        ContainerSchemaNodeBuilder containerSchemaNodeBuilder = new ContainerSchemaNodeBuilder(
+                Draft02.RestConfModule.NAME, 0, qName, path);
         final ContainerSchemaNodeBuilder fakeOperationsSchemaNode = containerSchemaNodeBuilder;
         for (final Module module : modules) {
             Set<RpcDefinition> rpcs = module.getRpcs();
             for (final RpcDefinition rpc : rpcs) {
                 QName rpcQName = rpc.getQName();
-                SimpleNode<Object> immutableSimpleNode =
-                                     NodeFactory.<Object>createImmutableSimpleNode(rpcQName, null, null);
+                SimpleNode<Object> immutableSimpleNode = NodeFactory.<Object> createImmutableSimpleNode(rpcQName, null,
+                        null);
                 operationsAsData.add(immutableSimpleNode);
 
                 String name = module.getName();
@@ -262,18 +275,16 @@ public class RestconfImpl implements RestconfService {
             }
         }
 
-        final CompositeNode operationsNode =
-                                  NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData);
+        final CompositeNode operationsNode = NodeFactory.createImmutableCompositeNode(qName, null, operationsAsData);
         ContainerSchemaNode schemaNode = fakeOperationsSchemaNode.build();
-        return new StructuredData(operationsNode, schemaNode, mountPoint);
+        return new StructuredData(operationsNode, schemaNode, mountPoint, prettyPrint);
     }
 
     private Module getRestconfModule() {
         Module restconfModule = controllerContext.getRestconfModule();
         if (restconfModule == null) {
-            throw new RestconfDocumentedException(
-                    "ietf-restconf module was not found.", ErrorType.APPLICATION,
-                    ErrorTag.OPERATION_NOT_SUPPORTED );
+            throw new RestconfDocumentedException("ietf-restconf module was not found.", ErrorType.APPLICATION,
+                    ErrorTag.OPERATION_NOT_SUPPORTED);
         }
 
         return restconfModule;
@@ -284,96 +295,91 @@ public class RestconfImpl implements RestconfService {
         String moduleNameAndRevision = "";
         if (mountIndex >= 0) {
             moduleNameAndRevision = identifier.substring(mountIndex + ControllerContext.MOUNT.length());
-        }
-        else {
+        } else {
             moduleNameAndRevision = identifier;
         }
 
         Splitter splitter = Splitter.on("/").omitEmptyStrings();
         Iterable<String> split = splitter.split(moduleNameAndRevision);
-        final List<String> pathArgs = Lists.<String>newArrayList(split);
+        final List<String> pathArgs = Lists.<String> newArrayList(split);
         if (pathArgs.size() < 2) {
             throw new RestconfDocumentedException(
-                    "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'",
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                    "URI has bad format. End of URI should be in format \'moduleName/yyyy-MM-dd\'", ErrorType.PROTOCOL,
+                    ErrorTag.INVALID_VALUE);
         }
 
         try {
-            final String moduleName = pathArgs.get( 0 );
+            final String moduleName = pathArgs.get(0);
             String revision = pathArgs.get(1);
             final Date moduleRevision = REVISION_FORMAT.parse(revision);
             return QName.create(null, moduleRevision, moduleName);
-        }
-        catch (ParseException e) {
-            throw new RestconfDocumentedException(
-                    "URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+        } catch (ParseException e) {
+            throw new RestconfDocumentedException("URI has bad format. It should be \'moduleName/yyyy-MM-dd\'",
+                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
     }
 
     private CompositeNode toStreamCompositeNode(final String streamName, final DataSchemaNode streamSchemaNode) {
         final List<Node<?>> streamNodeValues = new ArrayList<Node<?>>();
-        List<DataSchemaNode> instanceDataChildrenByName =
-                this.controllerContext.findInstanceDataChildrenByName(((DataNodeContainer) streamSchemaNode),
-                                                                       "name");
+        List<DataSchemaNode> instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
+                ((DataNodeContainer) streamSchemaNode), "name");
         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
-        streamNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(nameSchemaNode.getQName(), null,
-                                                                           streamName));
+        streamNodeValues
+                .add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null, streamName));
 
         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
-                                                 ((DataNodeContainer) streamSchemaNode), "description");
+                ((DataNodeContainer) streamSchemaNode), "description");
         final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
-        streamNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(descriptionSchemaNode.getQName(), null,
-                                                                           "DESCRIPTION_PLACEHOLDER"));
+        streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(descriptionSchemaNode.getQName(), null,
+                "DESCRIPTION_PLACEHOLDER"));
 
         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
-                                               ((DataNodeContainer) streamSchemaNode), "replay-support");
+                ((DataNodeContainer) streamSchemaNode), "replay-support");
         final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
-        streamNodeValues.add(NodeFactory.<Boolean>createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null,
-                                                                            Boolean.valueOf(true)));
+        streamNodeValues.add(NodeFactory.<Boolean> createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null,
+                Boolean.valueOf(true)));
 
         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
-                                           ((DataNodeContainer) streamSchemaNode), "replay-log-creation-time");
+                ((DataNodeContainer) streamSchemaNode), "replay-log-creation-time");
         final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
-        streamNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(),
-                                                                           null, ""));
+        streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(),
+                null, ""));
 
         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
-                                                        ((DataNodeContainer) streamSchemaNode), "events");
+                ((DataNodeContainer) streamSchemaNode), "events");
         final DataSchemaNode eventsSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
-        streamNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(eventsSchemaNode.getQName(),
-                                                                           null, ""));
+        streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(eventsSchemaNode.getQName(), null, ""));
 
         return NodeFactory.createImmutableCompositeNode(streamSchemaNode.getQName(), null, streamNodeValues);
     }
 
     private CompositeNode toModuleCompositeNode(final Module module, final DataSchemaNode moduleSchemaNode) {
         final List<Node<?>> moduleNodeValues = new ArrayList<Node<?>>();
-        List<DataSchemaNode> instanceDataChildrenByName =
-            this.controllerContext.findInstanceDataChildrenByName(((DataNodeContainer) moduleSchemaNode), "name");
+        List<DataSchemaNode> instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
+                ((DataNodeContainer) moduleSchemaNode), "name");
         final DataSchemaNode nameSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
-        moduleNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(nameSchemaNode.getQName(),
-                                                                           null, module.getName()));
+        moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(nameSchemaNode.getQName(), null,
+                module.getName()));
 
         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
-                                                          ((DataNodeContainer) moduleSchemaNode), "revision");
+                ((DataNodeContainer) moduleSchemaNode), "revision");
         final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
         Date _revision = module.getRevision();
-        moduleNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(revisionSchemaNode.getQName(), null,
-                                                                           REVISION_FORMAT.format(_revision)));
+        moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(revisionSchemaNode.getQName(), null,
+                REVISION_FORMAT.format(_revision)));
 
         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
-                                                        ((DataNodeContainer) moduleSchemaNode), "namespace");
+                ((DataNodeContainer) moduleSchemaNode), "namespace");
         final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
-        moduleNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(namespaceSchemaNode.getQName(), null,
-                                                                           module.getNamespace().toString()));
+        moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(namespaceSchemaNode.getQName(), null,
+                module.getNamespace().toString()));
 
         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
-                                                           ((DataNodeContainer) moduleSchemaNode), "feature");
+                ((DataNodeContainer) moduleSchemaNode), "feature");
         final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
         for (final FeatureDefinition feature : module.getFeatures()) {
-            moduleNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(featureSchemaNode.getQName(), null,
-                                                                               feature.getQName().getLocalName()));
+            moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(featureSchemaNode.getQName(), null,
+                    feature.getQName().getLocalName()));
         }
 
         return NodeFactory.createImmutableCompositeNode(moduleSchemaNode.getQName(), null, moduleNodeValues);
@@ -385,58 +391,50 @@ public class RestconfImpl implements RestconfService {
     }
 
     @Override
-    public StructuredData invokeRpc(final String identifier, final CompositeNode payload) {
+    public StructuredData invokeRpc(final String identifier, final CompositeNode payload, final UriInfo uriInfo) {
         final RpcExecutor rpc = this.resolveIdentifierInInvokeRpc(identifier);
         QName rpcName = rpc.getRpcDefinition().getQName();
         URI rpcNamespace = rpcName.getNamespace();
-        if (Objects.equal(rpcNamespace.toString(), SAL_REMOTE_NAMESPACE) &&
-            Objects.equal(rpcName.getLocalName(), SAL_REMOTE_RPC_SUBSRCIBE)) {
-            return invokeSalRemoteRpcSubscribeRPC(payload, rpc.getRpcDefinition());
+        if (Objects.equal(rpcNamespace.toString(), SAL_REMOTE_NAMESPACE)
+                && Objects.equal(rpcName.getLocalName(), SAL_REMOTE_RPC_SUBSRCIBE)) {
+            return invokeSalRemoteRpcSubscribeRPC(payload, rpc.getRpcDefinition(), parsePrettyPrintParameter(uriInfo));
         }
 
-        validateInput( rpc.getRpcDefinition().getInput(), payload );
+        validateInput(rpc.getRpcDefinition().getInput(), payload);
 
-        return callRpc(rpc, payload);
+        return callRpc(rpc, payload, parsePrettyPrintParameter(uriInfo));
     }
 
-    private void validateInput(DataSchemaNode inputSchema, CompositeNode payload) {
-        if( inputSchema != null && payload == null )
-        {
-            //expected a non null payload
-            throw new RestconfDocumentedException( "Input is required.",
-                                                   ErrorType.PROTOCOL,
-                                                   ErrorTag.MALFORMED_MESSAGE );
-        }
-        else if( inputSchema == null && payload != null )
-        {
-            //did not expect any input
-            throw new RestconfDocumentedException( "No input expected.",
-                                                   ErrorType.PROTOCOL,
-                                                   ErrorTag.MALFORMED_MESSAGE );
-        }
-        //else
-        //{
-            //TODO: Validate "mandatory" and "config" values here??? Or should those be
+    private void validateInput(final DataSchemaNode inputSchema, final CompositeNode payload) {
+        if (inputSchema != null && payload == null) {
+            // expected a non null payload
+            throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
+        } else if (inputSchema == null && payload != null) {
+            // did not expect any input
+            throw new RestconfDocumentedException("No input expected.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
+        }
+        // else
+        // {
+        // TODO: Validate "mandatory" and "config" values here??? Or should those be
         // validate in a more central location inside MD-SAL core.
-        //}
+        // }
     }
 
-    private StructuredData invokeSalRemoteRpcSubscribeRPC(final CompositeNode payload,
-                                                          final RpcDefinition rpc) {
+    private StructuredData invokeSalRemoteRpcSubscribeRPC(final CompositeNode payload, final RpcDefinition rpc,
+            final boolean prettyPrint) {
         final CompositeNode value = this.normalizeNode(payload, rpc.getInput(), null);
-        final SimpleNode<? extends Object> pathNode = value == null ? null :
-                               value.getFirstSimpleByName( QName.create(rpc.getQName(), "path") );
+        final SimpleNode<? extends Object> pathNode = value == null ? null : value.getFirstSimpleByName(QName.create(
+                rpc.getQName(), "path"));
         final Object pathValue = pathNode == null ? null : pathNode.getValue();
 
         if (!(pathValue instanceof InstanceIdentifier)) {
-            throw new RestconfDocumentedException(
-                    "Instance identifier was not normalized correctly.",
-                    ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED );
+            throw new RestconfDocumentedException("Instance identifier was not normalized correctly.",
+                    ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED);
         }
 
         final InstanceIdentifier pathIdentifier = ((InstanceIdentifier) pathValue);
         String streamName = null;
-        if (!Iterables.isEmpty(pathIdentifier.getPath())) {
+        if (!Iterables.isEmpty(pathIdentifier.getPathArguments())) {
             String fullRestconfIdentifier = this.controllerContext.toFullRestconfIdentifier(pathIdentifier);
             streamName = Notificator.createStreamNameFromUri(fullRestconfIdentifier);
         }
@@ -444,31 +442,30 @@ public class RestconfImpl implements RestconfService {
         if (Strings.isNullOrEmpty(streamName)) {
             throw new RestconfDocumentedException(
                     "Path is empty or contains data node which is not Container or List build-in type.",
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
-        final SimpleNode<String> streamNameNode = NodeFactory.<String>createImmutableSimpleNode(
-                             QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName);
+        final SimpleNode<String> streamNameNode = NodeFactory.<String> createImmutableSimpleNode(
+                QName.create(rpc.getOutput().getQName(), "stream-name"), null, streamName);
         final List<Node<?>> output = new ArrayList<Node<?>>();
         output.add(streamNameNode);
 
-        final MutableCompositeNode responseData = NodeFactory.createMutableCompositeNode(
-                                              rpc.getOutput().getQName(), null, output, null, null);
+        final MutableCompositeNode responseData = NodeFactory.createMutableCompositeNode(rpc.getOutput().getQName(),
+                null, output, null, null);
 
         if (!Notificator.existListenerFor(pathIdentifier)) {
             Notificator.createListener(pathIdentifier, streamName);
         }
 
-        return new StructuredData(responseData, rpc.getOutput(), null);
+        return new StructuredData(responseData, rpc.getOutput(), null, prettyPrint);
     }
 
     @Override
-    public StructuredData invokeRpc(final String identifier, final String noPayload) {
+    public StructuredData invokeRpc(final String identifier, final String noPayload, final UriInfo uriInfo) {
         if (StringUtils.isNotBlank(noPayload)) {
-            throw new RestconfDocumentedException(
-                    "Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+            throw new RestconfDocumentedException("Content must be empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
-        return invokeRpc( identifier, (CompositeNode)null );
+        return invokeRpc(identifier, (CompositeNode) null, uriInfo);
     }
 
     private RpcExecutor resolveIdentifierInInvokeRpc(final String identifier) {
@@ -476,8 +473,7 @@ public class RestconfImpl implements RestconfService {
         MountInstance mountPoint = null;
         if (identifier.contains(ControllerContext.MOUNT)) {
             // mounted RPC call - look up mount instance.
-            InstanceIdWithSchemaNode mountPointId = controllerContext
-                    .toMountPointIdentifier(identifier);
+            InstanceIdWithSchemaNode mountPointId = controllerContext.toMountPointIdentifier(identifier);
             mountPoint = mountPointId.getMountPoint();
 
             int startOfRemoteRpcName = identifier.lastIndexOf(ControllerContext.MOUNT)
@@ -486,12 +482,9 @@ public class RestconfImpl implements RestconfService {
             identifierEncoded = remoteRpcName;
 
         } else if (identifier.indexOf("/") != CHAR_NOT_FOUND) {
-            final String slashErrorMsg = String
-                    .format("Identifier %n%s%ncan\'t contain slash "
-                            + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.",
-                            identifier);
-            throw new RestconfDocumentedException(
-                    slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+            final String slashErrorMsg = String.format("Identifier %n%s%ncan\'t contain slash "
+                    + "character (/).%nIf slash is part of identifier name then use %%2F placeholder.", identifier);
+            throw new RestconfDocumentedException(slashErrorMsg, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         } else {
             identifierEncoded = identifier;
         }
@@ -500,8 +493,7 @@ public class RestconfImpl implements RestconfService {
         RpcDefinition rpc = controllerContext.getRpcDefinition(identifierDecoded);
 
         if (rpc == null) {
-            throw new RestconfDocumentedException(
-                    "RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT );
+            throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
         }
 
         if (mountPoint == null) {
@@ -512,10 +504,9 @@ public class RestconfImpl implements RestconfService {
 
     }
 
-    private StructuredData callRpc(final RpcExecutor rpcExecutor, final CompositeNode payload) {
+    private StructuredData callRpc(final RpcExecutor rpcExecutor, final CompositeNode payload, boolean prettyPrint) {
         if (rpcExecutor == null) {
-            throw new RestconfDocumentedException(
-                    "RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT );
+            throw new RestconfDocumentedException("RPC does not exist.", ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT);
         }
 
         CompositeNode rpcRequest = null;
@@ -538,108 +529,109 @@ public class RestconfImpl implements RestconfService {
             return null;
         }
 
-        if( rpc.getOutput() == null )
-        {
-            return null; //no output, nothing to send back.
+        if (rpc.getOutput() == null) {
+            return null; // no output, nothing to send back.
         }
 
-        return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null);
+        return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null, prettyPrint);
     }
 
-    private void checkRpcSuccessAndThrowException(RpcResult<CompositeNode> rpcResult) {
+    private void checkRpcSuccessAndThrowException(final RpcResult<CompositeNode> rpcResult) {
         if (rpcResult.isSuccessful() == false) {
 
             Collection<RpcError> rpcErrors = rpcResult.getErrors();
-            if( rpcErrors == null || rpcErrors.isEmpty() ) {
+            if (rpcErrors == null || rpcErrors.isEmpty()) {
                 throw new RestconfDocumentedException(
-                    "The operation was not successful and there were no RPC errors returned",
-                    ErrorType.RPC, ErrorTag.OPERATION_FAILED );
+                        "The operation was not successful and there were no RPC errors returned", ErrorType.RPC,
+                        ErrorTag.OPERATION_FAILED);
             }
 
             List<RestconfError> errorList = Lists.newArrayList();
-            for( RpcError rpcError: rpcErrors ) {
-                errorList.add( new RestconfError( rpcError ) );
+            for (RpcError rpcError : rpcErrors) {
+                errorList.add(new RestconfError(rpcError));
             }
 
-            throw new RestconfDocumentedException( errorList );
+            throw new RestconfDocumentedException(errorList);
         }
     }
 
     @Override
-    public StructuredData readConfigurationData(final String identifier, UriInfo info) {
+    public StructuredData readConfigurationData(final String identifier, final UriInfo uriInfo) {
         final InstanceIdWithSchemaNode iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
         CompositeNode data = null;
         MountInstance mountPoint = iiWithData.getMountPoint();
         if (mountPoint != null) {
             data = broker.readConfigurationDataBehindMountPoint(mountPoint, iiWithData.getInstanceIdentifier());
-        }
-        else {
+        } else {
             data = broker.readConfigurationData(iiWithData.getInstanceIdentifier());
         }
 
-        data = pruneDataAtDepth( data, parseDepthParameter( info ) );
-        return new StructuredData(data, iiWithData.getSchemaNode(), iiWithData.getMountPoint());
+        data = pruneDataAtDepth(data, parseDepthParameter(uriInfo));
+        boolean prettyPrintMode = parsePrettyPrintParameter(uriInfo);
+        return new StructuredData(data, iiWithData.getSchemaNode(), iiWithData.getMountPoint(), prettyPrintMode);
     }
 
     @SuppressWarnings("unchecked")
-    private <T extends Node<?>> T pruneDataAtDepth( T node, Integer depth ) {
-        if( depth == null ) {
+    private <T extends Node<?>> T pruneDataAtDepth(final T node, final Integer depth) {
+        if (depth == null) {
             return node;
         }
 
-        if( node instanceof CompositeNode ) {
+        if (node instanceof CompositeNode) {
             ImmutableList.Builder<Node<?>> newChildNodes = ImmutableList.<Node<?>> builder();
-            if( depth > 1 ) {
-                for( Node<?> childNode: ((CompositeNode)node).getValue() ) {
-                    newChildNodes.add( pruneDataAtDepth( childNode, depth - 1 ) );
+            if (depth > 1) {
+                for (Node<?> childNode : ((CompositeNode) node).getValue()) {
+                    newChildNodes.add(pruneDataAtDepth(childNode, depth - 1));
                 }
             }
 
-            return (T) ImmutableCompositeNode.create( node.getNodeType(), newChildNodes.build() );
-        }
-        else { // SimpleNode
+            return (T) ImmutableCompositeNode.create(node.getNodeType(), newChildNodes.build());
+        } else { // SimpleNode
             return node;
         }
     }
 
-    private Integer parseDepthParameter( UriInfo info ) {
-        String param = info.getQueryParameters( false ).getFirst( "depth" );
-        if( Strings.isNullOrEmpty( param ) || "unbounded".equals( param ) ) {
+    private Integer parseDepthParameter(final UriInfo info) {
+        String param = info.getQueryParameters(false).getFirst(UriParameters.DEPTH.toString());
+        if (Strings.isNullOrEmpty(param) || "unbounded".equals(param)) {
             return null;
         }
 
         try {
-            Integer depth = Integer.valueOf( param );
-            if( depth < 1 ) {
-                throw new RestconfDocumentedException( new RestconfError(
-                        ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE, "Invalid depth parameter: " + depth,
-                        null, "The depth parameter must be an integer > 1 or \"unbounded\"" ) );
+            Integer depth = Integer.valueOf(param);
+            if (depth < 1) {
+                throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
+                        "Invalid depth parameter: " + depth, null,
+                        "The depth parameter must be an integer > 1 or \"unbounded\""));
             }
 
             return depth;
-        }
-        catch( NumberFormatException e ) {
-            throw new RestconfDocumentedException( new RestconfError(
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
-                    "Invalid depth parameter: " + e.getMessage(),
-                    null, "The depth parameter must be an integer > 1 or \"unbounded\"" ) );
+        } catch (NumberFormatException e) {
+            throw new RestconfDocumentedException(new RestconfError(ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
+                    "Invalid depth parameter: " + e.getMessage(), null,
+                    "The depth parameter must be an integer > 1 or \"unbounded\""));
         }
     }
 
     @Override
-    public StructuredData readOperationalData(final String identifier, UriInfo info) {
+    public StructuredData readOperationalData(final String identifier, final UriInfo info) {
         final InstanceIdWithSchemaNode iiWithData = this.controllerContext.toInstanceIdentifier(identifier);
         CompositeNode data = null;
         MountInstance mountPoint = iiWithData.getMountPoint();
         if (mountPoint != null) {
             data = broker.readOperationalDataBehindMountPoint(mountPoint, iiWithData.getInstanceIdentifier());
-        }
-        else {
+        } else {
             data = broker.readOperationalData(iiWithData.getInstanceIdentifier());
         }
 
-        data = pruneDataAtDepth( data, parseDepthParameter( info ) );
-        return new StructuredData(data, iiWithData.getSchemaNode(), mountPoint);
+        data = pruneDataAtDepth(data, parseDepthParameter(info));
+        boolean prettyPrintMode = parsePrettyPrintParameter(info);
+        return new StructuredData(data, iiWithData.getSchemaNode(), mountPoint, prettyPrintMode);
+    }
+
+    private boolean parsePrettyPrintParameter(UriInfo info) {
+        String param = info.getQueryParameters(false).getFirst(UriParameters.PRETTY_PRINT.toString());
+        return Boolean.parseBoolean(param);
     }
 
     @Override
@@ -650,73 +642,114 @@ public class RestconfImpl implements RestconfService {
 
         MountInstance mountPoint = iiWithData.getMountPoint();
         final CompositeNode value = this.normalizeNode(payload, iiWithData.getSchemaNode(), mountPoint);
+        validateListKeysEqualityInPayloadAndUri(iiWithData, payload);
         RpcResult<TransactionStatus> status = null;
 
         try {
             if (mountPoint != null) {
-                status = broker.commitConfigurationDataPutBehindMountPoint(
-                                                mountPoint, iiWithData.getInstanceIdentifier(), value).get();
+                status = broker.commitConfigurationDataPutBehindMountPoint(mountPoint,
+                        iiWithData.getInstanceIdentifier(), value).get();
             } else {
                 status = broker.commitConfigurationDataPut(iiWithData.getInstanceIdentifier(), value).get();
             }
-        }
-        catch( Exception e ) {
-            throw new RestconfDocumentedException( "Error updating data", e );
+        } catch (Exception e) {
+            throw new RestconfDocumentedException("Error updating data", e);
         }
 
-        if( status.getResult() == TransactionStatus.COMMITED )
+        if (status.getResult() == TransactionStatus.COMMITED) {
             return Response.status(Status.OK).build();
+        }
 
         return Response.status(Status.INTERNAL_SERVER_ERROR).build();
     }
 
+    /**
+     * Validates whether keys in {@code payload} are equal to values of keys in {@code iiWithData} for list schema node
+     *
+     * @throws RestconfDocumentedException
+     *             if key values or key count in payload and URI isn't equal
+     *
+     */
+    private void validateListKeysEqualityInPayloadAndUri(final InstanceIdWithSchemaNode iiWithData,
+            final CompositeNode payload) {
+        if (iiWithData.getSchemaNode() instanceof ListSchemaNode) {
+            final List<QName> keyDefinitions = ((ListSchemaNode) iiWithData.getSchemaNode()).getKeyDefinition();
+            final PathArgument lastPathArgument = iiWithData.getInstanceIdentifier().getLastPathArgument();
+            if (lastPathArgument instanceof NodeIdentifierWithPredicates) {
+                final Map<QName, Object> uriKeyValues = ((NodeIdentifierWithPredicates) lastPathArgument)
+                        .getKeyValues();
+                isEqualUriAndPayloadKeyValues(uriKeyValues, payload, keyDefinitions);
+            }
+        }
+    }
+
+    private void isEqualUriAndPayloadKeyValues(final Map<QName, Object> uriKeyValues, final CompositeNode payload,
+            final List<QName> keyDefinitions) {
+        for (QName keyDefinition : keyDefinitions) {
+            final Object uriKeyValue = uriKeyValues.get(keyDefinition);
+            // should be caught during parsing URI to InstanceIdentifier
+            if (uriKeyValue == null) {
+                throw new RestconfDocumentedException("Missing key " + keyDefinition + " in URI.", ErrorType.PROTOCOL,
+                        ErrorTag.DATA_MISSING);
+            }
+            final List<SimpleNode<?>> payloadKeyValues = payload.getSimpleNodesByName(keyDefinition.getLocalName());
+            if (payloadKeyValues.isEmpty()) {
+                throw new RestconfDocumentedException("Missing key " + keyDefinition.getLocalName()
+                        + " in the message body.", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
+            }
+
+            Object payloadKeyValue = payloadKeyValues.iterator().next().getValue();
+            if (!uriKeyValue.equals(payloadKeyValue)) {
+                throw new RestconfDocumentedException("The value '" + uriKeyValue + "' for key '"
+                        + keyDefinition.getLocalName() + "' specified in the URI doesn't match the value '"
+                        + payloadKeyValue + "' specified in the message body. ", ErrorType.PROTOCOL,
+                        ErrorTag.INVALID_VALUE);
+            }
+        }
+    }
+
     @Override
     public Response createConfigurationData(final String identifier, final CompositeNode payload) {
-        if( payload == null ) {
-            throw new RestconfDocumentedException( "Input is required.",
-                    ErrorType.PROTOCOL,
-                    ErrorTag.MALFORMED_MESSAGE );
+        if (payload == null) {
+            throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
         }
 
         URI payloadNS = this.namespace(payload);
         if (payloadNS == null) {
             throw new RestconfDocumentedException(
-                 "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
-                 ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE );
+                    "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
+                    ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
         }
 
         InstanceIdWithSchemaNode iiWithData = null;
         CompositeNode value = null;
         if (this.representsMountPointRootData(payload)) {
-             // payload represents mount point data and URI represents path to the mount point
+            // payload represents mount point data and URI represents path to the mount point
 
             if (this.endsWithMountPoint(identifier)) {
-                throw new RestconfDocumentedException(
-                        "URI has bad format. URI should be without \"" + ControllerContext.MOUNT +
-                        "\" for POST operation.",
-                        ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                throw new RestconfDocumentedException("URI has bad format. URI should be without \""
+                        + ControllerContext.MOUNT + "\" for POST operation.", ErrorType.PROTOCOL,
+                        ErrorTag.INVALID_VALUE);
             }
 
             final String completeIdentifier = this.addMountPointIdentifier(identifier);
             iiWithData = this.controllerContext.toInstanceIdentifier(completeIdentifier);
 
             value = this.normalizeNode(payload, iiWithData.getSchemaNode(), iiWithData.getMountPoint());
-        }
-        else {
-            final InstanceIdWithSchemaNode incompleteInstIdWithData =
-                                               this.controllerContext.toInstanceIdentifier(identifier);
+        } else {
+            final InstanceIdWithSchemaNode incompleteInstIdWithData = this.controllerContext
+                    .toInstanceIdentifier(identifier);
             final DataNodeContainer parentSchema = (DataNodeContainer) incompleteInstIdWithData.getSchemaNode();
             MountInstance mountPoint = incompleteInstIdWithData.getMountPoint();
             final Module module = this.findModule(mountPoint, payload);
             if (module == null) {
-                throw new RestconfDocumentedException(
-                        "Module was not found for \"" + payloadNS + "\"",
-                        ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT );
+                throw new RestconfDocumentedException("Module was not found for \"" + payloadNS + "\"",
+                        ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
             }
 
             String payloadName = this.getName(payload);
             final DataSchemaNode schemaNode = this.controllerContext.findInstanceDataChildByNameAndNamespace(
-                                                              parentSchema, payloadName, module.getNamespace());
+                    parentSchema, payloadName, module.getNamespace());
             value = this.normalizeNode(payload, schemaNode, mountPoint);
 
             iiWithData = this.addLastIdentifierFromData(incompleteInstIdWithData, value, schemaNode);
@@ -726,56 +759,52 @@ public class RestconfImpl implements RestconfService {
         MountInstance mountPoint = iiWithData.getMountPoint();
         try {
             if (mountPoint != null) {
-                Future<RpcResult<TransactionStatus>> future =
-                                          broker.commitConfigurationDataPostBehindMountPoint(
-                                                       mountPoint, iiWithData.getInstanceIdentifier(), value);
+                Future<RpcResult<TransactionStatus>> future = broker.commitConfigurationDataPostBehindMountPoint(
+                        mountPoint, iiWithData.getInstanceIdentifier(), value);
                 status = future == null ? null : future.get();
-            }
-            else {
-                Future<RpcResult<TransactionStatus>> future =
-                               broker.commitConfigurationDataPost(iiWithData.getInstanceIdentifier(), value);
+            } else {
+                Future<RpcResult<TransactionStatus>> future = broker.commitConfigurationDataPost(
+                        iiWithData.getInstanceIdentifier(), value);
                 status = future == null ? null : future.get();
             }
-        }
-        catch( Exception e ) {
-            throw new RestconfDocumentedException( "Error creating data", e );
+        } catch (Exception e) {
+            throw new RestconfDocumentedException("Error creating data", e);
         }
 
         if (status == null) {
             return Response.status(Status.ACCEPTED).build();
         }
 
-        if( status.getResult() == TransactionStatus.COMMITED )
+        if (status.getResult() == TransactionStatus.COMMITED) {
             return Response.status(Status.NO_CONTENT).build();
+        }
 
         return Response.status(Status.INTERNAL_SERVER_ERROR).build();
     }
 
     @Override
     public Response createConfigurationData(final CompositeNode payload) {
-        if( payload == null ) {
-            throw new RestconfDocumentedException( "Input is required.",
-                    ErrorType.PROTOCOL,
-                    ErrorTag.MALFORMED_MESSAGE );
+        if (payload == null) {
+            throw new RestconfDocumentedException("Input is required.", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
         }
 
         URI payloadNS = this.namespace(payload);
         if (payloadNS == null) {
             throw new RestconfDocumentedException(
-                "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
-                ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE );
+                    "Data has bad format. Root element node must have namespace (XML format) or module name(JSON format)",
+                    ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
         }
 
         final Module module = this.findModule(null, payload);
         if (module == null) {
             throw new RestconfDocumentedException(
                     "Data has bad format. Root element node has incorrect namespace (XML format) or module name(JSON format)",
-                    ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE );
+                    ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
         }
 
         String payloadName = this.getName(payload);
-        final DataSchemaNode schemaNode = this.controllerContext.findInstanceDataChildByNameAndNamespace(
-                                                                   module, payloadName, module.getNamespace());
+        final DataSchemaNode schemaNode = this.controllerContext.findInstanceDataChildByNameAndNamespace(module,
+                payloadName, module.getNamespace());
         final CompositeNode value = this.normalizeNode(payload, schemaNode, null);
         final InstanceIdWithSchemaNode iiWithData = this.addLastIdentifierFromData(null, value, schemaNode);
         RpcResult<TransactionStatus> status = null;
@@ -783,27 +812,25 @@ public class RestconfImpl implements RestconfService {
 
         try {
             if (mountPoint != null) {
-                Future<RpcResult<TransactionStatus>> future =
-                                             broker.commitConfigurationDataPostBehindMountPoint(
-                                                          mountPoint, iiWithData.getInstanceIdentifier(), value);
+                Future<RpcResult<TransactionStatus>> future = broker.commitConfigurationDataPostBehindMountPoint(
+                        mountPoint, iiWithData.getInstanceIdentifier(), value);
                 status = future == null ? null : future.get();
-            }
-            else {
-                Future<RpcResult<TransactionStatus>> future =
-                                 broker.commitConfigurationDataPost(iiWithData.getInstanceIdentifier(), value);
+            } else {
+                Future<RpcResult<TransactionStatus>> future = broker.commitConfigurationDataPost(
+                        iiWithData.getInstanceIdentifier(), value);
                 status = future == null ? null : future.get();
             }
-        }
-        catch( Exception e ) {
-            throw new RestconfDocumentedException( "Error creating data", e );
+        } catch (Exception e) {
+            throw new RestconfDocumentedException("Error creating data", e);
         }
 
         if (status == null) {
             return Response.status(Status.ACCEPTED).build();
         }
 
-        if( status.getResult() == TransactionStatus.COMMITED )
+        if (status.getResult() == TransactionStatus.COMMITED) {
             return Response.status(Status.NO_CONTENT).build();
+        }
 
         return Response.status(Status.INTERNAL_SERVER_ERROR).build();
     }
@@ -816,19 +843,18 @@ public class RestconfImpl implements RestconfService {
 
         try {
             if (mountPoint != null) {
-                status = broker.commitConfigurationDataDeleteBehindMountPoint(
-                                        mountPoint, iiWithData.getInstanceIdentifier()).get();
-            }
-            else {
+                status = broker.commitConfigurationDataDeleteBehindMountPoint(mountPoint,
+                        iiWithData.getInstanceIdentifier()).get();
+            } else {
                 status = broker.commitConfigurationDataDelete(iiWithData.getInstanceIdentifier()).get();
             }
-        }
-        catch( Exception e ) {
-            throw new RestconfDocumentedException( "Error creating data", e );
+        } catch (Exception e) {
+            throw new RestconfDocumentedException("Error creating data", e);
         }
 
-        if( status.getResult() == TransactionStatus.COMMITED )
+        if (status.getResult() == TransactionStatus.COMMITED) {
             return Response.status(Status.OK).build();
+        }
 
         return Response.status(Status.INTERNAL_SERVER_ERROR).build();
     }
@@ -837,20 +863,18 @@ public class RestconfImpl implements RestconfService {
     public Response subscribeToStream(final String identifier, final UriInfo uriInfo) {
         final String streamName = Notificator.createStreamNameFromUri(identifier);
         if (Strings.isNullOrEmpty(streamName)) {
-            throw new RestconfDocumentedException(
-                    "Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+            throw new RestconfDocumentedException("Stream name is empty.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
         final ListenerAdapter listener = Notificator.getListenerFor(streamName);
         if (listener == null) {
-            throw new RestconfDocumentedException(
-                    "Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT );
+            throw new RestconfDocumentedException("Stream was not found.", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT);
         }
 
         broker.registerToListenDataChanges(listener);
 
         final UriBuilder uriBuilder = uriInfo.getAbsolutePathBuilder();
-        UriBuilder port = uriBuilder.port(WebSocketServer.PORT);
+        UriBuilder port = uriBuilder.port(WebSocketServer.getInstance().getPort());
         final URI uriToWebsocketServer = port.replacePath(streamName).build();
 
         return Response.status(Status.OK).location(uriToWebsocketServer).build();
@@ -858,26 +882,23 @@ public class RestconfImpl implements RestconfService {
 
     private Module findModule(final MountInstance mountPoint, final CompositeNode data) {
         if (data instanceof CompositeNodeWrapper) {
-            return findModule(mountPoint, (CompositeNodeWrapper)data);
-        }
-        else if (data != null) {
+            return findModule(mountPoint, (CompositeNodeWrapper) data);
+        } else if (data != null) {
             URI namespace = data.getNodeType().getNamespace();
             if (mountPoint != null) {
                 return this.controllerContext.findModuleByNamespace(mountPoint, namespace);
-            }
-            else {
+            } else {
                 return this.controllerContext.findModuleByNamespace(namespace);
             }
-        }
-        else {
-            throw new IllegalArgumentException("Unhandled parameter types: " +
-                    Arrays.<Object>asList(mountPoint, data).toString());
+        } else {
+            throw new IllegalArgumentException("Unhandled parameter types: "
+                    + Arrays.<Object> asList(mountPoint, data).toString());
         }
     }
 
     private Module findModule(final MountInstance mountPoint, final CompositeNodeWrapper data) {
         URI namespace = data.getNamespace();
-        Preconditions.<URI>checkNotNull(namespace);
+        Preconditions.<URI> checkNotNull(namespace);
 
         Module module = null;
         if (mountPoint != null) {
@@ -885,8 +906,7 @@ public class RestconfImpl implements RestconfService {
             if (module == null) {
                 module = this.controllerContext.findModuleByName(mountPoint, namespace.toString());
             }
-        }
-        else {
+        } else {
             module = this.controllerContext.findModuleByNamespace(namespace);
             if (module == null) {
                 module = this.controllerContext.findModuleByName(namespace.toString());
@@ -896,9 +916,8 @@ public class RestconfImpl implements RestconfService {
         return module;
     }
 
-    private InstanceIdWithSchemaNode addLastIdentifierFromData(
-                                              final InstanceIdWithSchemaNode identifierWithSchemaNode,
-                                              final CompositeNode data, final DataSchemaNode schemaOfData) {
+    private InstanceIdWithSchemaNode addLastIdentifierFromData(final InstanceIdWithSchemaNode identifierWithSchemaNode,
+            final CompositeNode data, final DataSchemaNode schemaOfData) {
         InstanceIdentifier instanceIdentifier = null;
         if (identifierWithSchemaNode != null) {
             instanceIdentifier = identifierWithSchemaNode.getInstanceIdentifier();
@@ -908,31 +927,28 @@ public class RestconfImpl implements RestconfService {
         InstanceIdentifierBuilder iiBuilder = null;
         if (iiOriginal == null) {
             iiBuilder = InstanceIdentifier.builder();
-        }
-        else {
+        } else {
             iiBuilder = InstanceIdentifier.builder(iiOriginal);
         }
 
         if ((schemaOfData instanceof ListSchemaNode)) {
-            HashMap<QName,Object> keys = this.resolveKeysFromData(((ListSchemaNode) schemaOfData), data);
+            HashMap<QName, Object> keys = this.resolveKeysFromData(((ListSchemaNode) schemaOfData), data);
             iiBuilder.nodeWithKey(schemaOfData.getQName(), keys);
-        }
-        else {
+        } else {
             iiBuilder.node(schemaOfData.getQName());
         }
 
         InstanceIdentifier instance = iiBuilder.toInstance();
         MountInstance mountPoint = null;
         if (identifierWithSchemaNode != null) {
-            mountPoint=identifierWithSchemaNode.getMountPoint();
+            mountPoint = identifierWithSchemaNode.getMountPoint();
         }
 
         return new InstanceIdWithSchemaNode(instance, schemaOfData, mountPoint);
     }
 
-    private HashMap<QName,Object> resolveKeysFromData(final ListSchemaNode listNode,
-                                                      final CompositeNode dataNode) {
-        final HashMap<QName,Object> keyValues = new HashMap<QName, Object>();
+    private HashMap<QName, Object> resolveKeysFromData(final ListSchemaNode listNode, final CompositeNode dataNode) {
+        final HashMap<QName, Object> keyValues = new HashMap<QName, Object>();
         List<QName> _keyDefinition = listNode.getKeyDefinition();
         for (final QName key : _keyDefinition) {
             SimpleNode<? extends Object> head = null;
@@ -948,10 +964,9 @@ public class RestconfImpl implements RestconfService {
             }
 
             if (dataNodeKeyValueObject == null) {
-                throw new RestconfDocumentedException(
-                        "Data contains list \"" + dataNode.getNodeType().getLocalName() +
-                        "\" which does not contain key: \"" + key.getLocalName() + "\"",
-                        ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                throw new RestconfDocumentedException("Data contains list \"" + dataNode.getNodeType().getLocalName()
+                        + "\" which does not contain key: \"" + key.getLocalName() + "\"", ErrorType.PROTOCOL,
+                        ErrorTag.INVALID_VALUE);
             }
 
             keyValues.put(key, dataNodeKeyValueObject);
@@ -961,15 +976,16 @@ public class RestconfImpl implements RestconfService {
     }
 
     private boolean endsWithMountPoint(final String identifier) {
-        return identifier.endsWith(ControllerContext.MOUNT) ||
-               identifier.endsWith(ControllerContext.MOUNT + "/");
+        return identifier.endsWith(ControllerContext.MOUNT) || identifier.endsWith(ControllerContext.MOUNT + "/");
     }
 
     private boolean representsMountPointRootData(final CompositeNode data) {
         URI namespace = this.namespace(data);
-        return (SchemaContext.NAME.getNamespace().equals( namespace ) /* ||
-                MOUNT_POINT_MODULE_NAME.equals( namespace.toString() )*/ ) &&
-                SchemaContext.NAME.getLocalName().equals( this.localName(data) );
+        return (SchemaContext.NAME.getNamespace().equals(namespace) /*
+                                                                     * || MOUNT_POINT_MODULE_NAME .equals( namespace .
+                                                                     * toString( ) )
+                                                                     */)
+                && SchemaContext.NAME.getLocalName().equals(this.localName(data));
     }
 
     private String addMountPointIdentifier(final String identifier) {
@@ -982,20 +998,18 @@ public class RestconfImpl implements RestconfService {
     }
 
     private CompositeNode normalizeNode(final CompositeNode node, final DataSchemaNode schema,
-                                        final MountInstance mountPoint) {
+            final MountInstance mountPoint) {
         if (schema == null) {
             QName nodeType = node == null ? null : node.getNodeType();
             String localName = nodeType == null ? null : nodeType.getLocalName();
 
-            throw new RestconfDocumentedException(
-                    "Data schema node was not found for " + localName,
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+            throw new RestconfDocumentedException("Data schema node was not found for " + localName,
+                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
         if (!(schema instanceof DataNodeContainer)) {
-            throw new RestconfDocumentedException(
-                    "Root element has to be container or list yang datatype.",
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+            throw new RestconfDocumentedException("Root element has to be container or list yang datatype.",
+                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
         if ((node instanceof CompositeNodeWrapper)) {
@@ -1003,10 +1017,8 @@ public class RestconfImpl implements RestconfService {
             if (isChangeAllowed) {
                 try {
                     this.normalizeNode(((CompositeNodeWrapper) node), schema, null, mountPoint);
-                }
-                catch (IllegalArgumentException e) {
-                    throw new RestconfDocumentedException(
-                                    e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                } catch (IllegalArgumentException e) {
+                    throw new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
                 }
             }
 
@@ -1016,156 +1028,194 @@ public class RestconfImpl implements RestconfService {
         return node;
     }
 
-    private void normalizeNode(final NodeWrapper<? extends Object> nodeBuilder,
-                               final DataSchemaNode schema, final QName previousAugment,
-                               final MountInstance mountPoint) {
+    private void normalizeNode(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
+            final QName previousAugment, final MountInstance mountPoint) {
         if (schema == null) {
-            throw new RestconfDocumentedException(
-                    "Data has bad format.\n\"" + nodeBuilder.getLocalName() +
-                    "\" does not exist in yang schema.",
-                    ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+            throw new RestconfDocumentedException("Data has bad format.\n\"" + nodeBuilder.getLocalName()
+                    + "\" does not exist in yang schema.", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
         }
 
         QName currentAugment = null;
         if (nodeBuilder.getQname() != null) {
             currentAugment = previousAugment;
-        }
-        else {
+        } else {
             currentAugment = this.normalizeNodeName(nodeBuilder, schema, previousAugment, mountPoint);
             if (nodeBuilder.getQname() == null) {
                 throw new RestconfDocumentedException(
-                        "Data has bad format.\nIf data is in XML format then namespace for \"" +
-                        nodeBuilder.getLocalName() +
-                        "\" should be \"" + schema.getQName().getNamespace() + "\".\n" +
-                        "If data is in JSON format then module name for \"" + nodeBuilder.getLocalName() +
-                         "\" should be corresponding to namespace \"" +
-                        schema.getQName().getNamespace() + "\".",
-                        ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                        "Data has bad format.\nIf data is in XML format then namespace for \""
+                                + nodeBuilder.getLocalName() + "\" should be \"" + schema.getQName().getNamespace()
+                                + "\".\n" + "If data is in JSON format then module name for \""
+                                + nodeBuilder.getLocalName() + "\" should be corresponding to namespace \""
+                                + schema.getQName().getNamespace() + "\".", ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
+            }
+        }
+
+        if (nodeBuilder instanceof CompositeNodeWrapper) {
+            if (schema instanceof DataNodeContainer) {
+                normalizeCompositeNode((CompositeNodeWrapper) nodeBuilder, (DataNodeContainer) schema, mountPoint,
+                        currentAugment);
+            } else if (schema instanceof AnyXmlSchemaNode) {
+                normalizeAnyXmlNode((CompositeNodeWrapper) nodeBuilder, (AnyXmlSchemaNode) schema);
             }
+        } else if (nodeBuilder instanceof SimpleNodeWrapper) {
+            normalizeSimpleNode((SimpleNodeWrapper) nodeBuilder, schema, mountPoint);
+        } else if ((nodeBuilder instanceof EmptyNodeWrapper)) {
+            normalizeEmptyNode((EmptyNodeWrapper) nodeBuilder, schema);
         }
+    }
 
-        if ((nodeBuilder instanceof CompositeNodeWrapper)) {
-            final List<NodeWrapper<?>> children = ((CompositeNodeWrapper) nodeBuilder).getValues();
-            for (final NodeWrapper<? extends Object> child : children) {
-                final List<DataSchemaNode> potentialSchemaNodes =
-                        this.controllerContext.findInstanceDataChildrenByName(
-                                             ((DataNodeContainer) schema), child.getLocalName());
+    private void normalizeAnyXmlNode(final CompositeNodeWrapper compositeNode, final AnyXmlSchemaNode schema) {
+        List<NodeWrapper<?>> children = compositeNode.getValues();
+        for (NodeWrapper<? extends Object> child : children) {
+            child.setNamespace(schema.getQName().getNamespace());
+            if (child instanceof CompositeNodeWrapper) {
+                normalizeAnyXmlNode((CompositeNodeWrapper) child, schema);
+            }
+        }
+    }
 
-                if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) {
-                    StringBuilder builder = new StringBuilder();
-                    for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
-                        builder.append("   ").append(potentialSchemaNode.getQName().getNamespace().toString())
-                               .append("\n");
-                    }
+    private void normalizeEmptyNode(final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema) {
+        if ((schema instanceof LeafSchemaNode)) {
+            emptyNodeBuilder.setComposite(false);
+        } else {
+            if ((schema instanceof ContainerSchemaNode)) {
+                // FIXME: Add presence check
+                emptyNodeBuilder.setComposite(true);
+            }
+        }
+    }
 
-                    throw new RestconfDocumentedException(
-                                 "Node \"" + child.getLocalName() +
-                                 "\" is added as augment from more than one module. " +
-                                 "Therefore node must have namespace (XML format) or module name (JSON format)." +
-                                 "\nThe node is added as augment from modules with namespaces:\n" + builder,
-                                 ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
-                }
+    private void normalizeSimpleNode(final SimpleNodeWrapper simpleNode, final DataSchemaNode schema,
+            final MountInstance mountPoint) {
+        final Object value = simpleNode.getValue();
+        Object inputValue = value;
+        TypeDefinition<? extends Object> typeDefinition = this.typeDefinition(schema);
+        if ((typeDefinition instanceof IdentityrefTypeDefinition)) {
+            if ((value instanceof String)) {
+                inputValue = new IdentityValuesDTO(simpleNode.getNamespace().toString(), (String) value, null,
+                        (String) value);
+            } // else value is already instance of IdentityValuesDTO
+        }
 
-                boolean rightNodeSchemaFound = false;
+        Object outputValue = inputValue;
+
+        if (typeDefinition != null) {
+            Codec<Object, Object> codec = RestCodec.from(typeDefinition, mountPoint);
+            outputValue = codec == null ? null : codec.deserialize(inputValue);
+        }
+
+        simpleNode.setValue(outputValue);
+    }
+
+    private void normalizeCompositeNode(final CompositeNodeWrapper compositeNodeBuilder,
+            final DataNodeContainer schema, final MountInstance mountPoint, final QName currentAugment) {
+        final List<NodeWrapper<?>> children = compositeNodeBuilder.getValues();
+        checkNodeMultiplicityAccordingToSchema(schema, children);
+        for (final NodeWrapper<? extends Object> child : children) {
+            final List<DataSchemaNode> potentialSchemaNodes = this.controllerContext.findInstanceDataChildrenByName(
+                    schema, child.getLocalName());
+
+            if (potentialSchemaNodes.size() > 1 && child.getNamespace() == null) {
+                StringBuilder builder = new StringBuilder();
                 for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
-                    if (!rightNodeSchemaFound) {
-                        final QName potentialCurrentAugment =
-                                this.normalizeNodeName(child, potentialSchemaNode, currentAugment, mountPoint);
-                        if (child.getQname() != null ) {
-                            this.normalizeNode(child, potentialSchemaNode, potentialCurrentAugment, mountPoint);
-                            rightNodeSchemaFound = true;
-                        }
-                    }
+                    builder.append("   ").append(potentialSchemaNode.getQName().getNamespace().toString()).append("\n");
                 }
 
+                throw new RestconfDocumentedException("Node \"" + child.getLocalName()
+                        + "\" is added as augment from more than one module. "
+                        + "Therefore node must have namespace (XML format) or module name (JSON format)."
+                        + "\nThe node is added as augment from modules with namespaces:\n" + builder,
+                        ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
+            }
+
+            boolean rightNodeSchemaFound = false;
+            for (final DataSchemaNode potentialSchemaNode : potentialSchemaNodes) {
                 if (!rightNodeSchemaFound) {
-                    throw new RestconfDocumentedException(
-                               "Schema node \"" + child.getLocalName() + "\" was not found in module.",
-                               ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT );
+                    final QName potentialCurrentAugment = this.normalizeNodeName(child, potentialSchemaNode,
+                            currentAugment, mountPoint);
+                    if (child.getQname() != null) {
+                        this.normalizeNode(child, potentialSchemaNode, potentialCurrentAugment, mountPoint);
+                        rightNodeSchemaFound = true;
+                    }
                 }
             }
 
-            if ((schema instanceof ListSchemaNode)) {
-                final List<QName> listKeys = ((ListSchemaNode) schema).getKeyDefinition();
-                for (final QName listKey : listKeys) {
-                    boolean foundKey = false;
-                    for (final NodeWrapper<? extends Object> child : children) {
-                        if (Objects.equal(child.unwrap().getNodeType().getLocalName(), listKey.getLocalName())) {
-                            foundKey = true;
-                        }
-                    }
+            if (!rightNodeSchemaFound) {
+                throw new RestconfDocumentedException("Schema node \"" + child.getLocalName()
+                        + "\" was not found in module.", ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
+            }
+        }
 
-                    if (!foundKey) {
-                        throw new RestconfDocumentedException(
-                                       "Missing key in URI \"" + listKey.getLocalName() +
-                                       "\" of list \"" + schema.getQName().getLocalName() + "\"",
-                                       ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+        if ((schema instanceof ListSchemaNode)) {
+            ListSchemaNode listSchemaNode = (ListSchemaNode) schema;
+            final List<QName> listKeys = listSchemaNode.getKeyDefinition();
+            for (final QName listKey : listKeys) {
+                boolean foundKey = false;
+                for (final NodeWrapper<? extends Object> child : children) {
+                    if (Objects.equal(child.unwrap().getNodeType().getLocalName(), listKey.getLocalName())) {
+                        foundKey = true;
                     }
                 }
+
+                if (!foundKey) {
+                    throw new RestconfDocumentedException("Missing key in URI \"" + listKey.getLocalName()
+                            + "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", ErrorType.PROTOCOL,
+                            ErrorTag.DATA_MISSING);
+                }
             }
         }
-        else {
-            if ((nodeBuilder instanceof SimpleNodeWrapper)) {
-                final SimpleNodeWrapper simpleNode = ((SimpleNodeWrapper) nodeBuilder);
-                final Object value = simpleNode.getValue();
-                Object inputValue = value;
-                TypeDefinition<? extends Object> typeDefinition = this.typeDefinition(schema);
-                if ((typeDefinition instanceof IdentityrefTypeDefinition)) {
-                    if ((value instanceof String)) {
-                        inputValue = new IdentityValuesDTO( nodeBuilder.getNamespace().toString(),
-                                                            (String) value, null, (String) value );
-                    } // else value is already instance of IdentityValuesDTO
-                }
-
-                Codec<Object,Object> codec = RestCodec.from(typeDefinition, mountPoint);
-                Object outputValue = codec == null ? null : codec.deserialize(inputValue);
+    }
 
-                simpleNode.setValue(outputValue);
-            }
-            else {
-                if ((nodeBuilder instanceof EmptyNodeWrapper)) {
-                    final EmptyNodeWrapper emptyNodeBuilder = ((EmptyNodeWrapper) nodeBuilder);
-                    if ((schema instanceof LeafSchemaNode)) {
-                        emptyNodeBuilder.setComposite(false);
-                    }
-                    else {
-                        if ((schema instanceof ContainerSchemaNode)) {
-                            // FIXME: Add presence check
-                            emptyNodeBuilder.setComposite(true);
-                        }
-                    }
+    private void checkNodeMultiplicityAccordingToSchema(final DataNodeContainer dataNodeContainer,
+            final List<NodeWrapper<?>> nodes) {
+        Map<String, Integer> equalNodeNamesToCounts = new HashMap<String, Integer>();
+        for (NodeWrapper<?> child : nodes) {
+            Integer count = equalNodeNamesToCounts.get(child.getLocalName());
+            equalNodeNamesToCounts.put(child.getLocalName(), count == null ? 1 : ++count);
+        }
+
+        for (DataSchemaNode childSchemaNode : dataNodeContainer.getChildNodes()) {
+            if (childSchemaNode instanceof ContainerSchemaNode || childSchemaNode instanceof LeafSchemaNode) {
+                String localName = childSchemaNode.getQName().getLocalName();
+                Integer count = equalNodeNamesToCounts.get(localName);
+                if (count != null && count > 1) {
+                    throw new RestconfDocumentedException("Multiple input data elements were specified for '"
+                            + childSchemaNode.getQName().getLocalName()
+                            + "'. The data for this element type can only be specified once.", ErrorType.APPLICATION,
+                            ErrorTag.BAD_ELEMENT);
                 }
             }
         }
     }
 
-    private QName normalizeNodeName(final NodeWrapper<? extends Object> nodeBuilder,
-                                    final DataSchemaNode schema, final QName previousAugment,
-                                    final MountInstance mountPoint) {
+    private QName normalizeNodeName(final NodeWrapper<? extends Object> nodeBuilder, final DataSchemaNode schema,
+            final QName previousAugment, final MountInstance mountPoint) {
         QName validQName = schema.getQName();
         QName currentAugment = previousAugment;
         if (schema.isAugmenting()) {
             currentAugment = schema.getQName();
-        }
-        else if (previousAugment != null &&
-                 !Objects.equal( schema.getQName().getNamespace(), previousAugment.getNamespace())) {
+        } else if (previousAugment != null
+                && !Objects.equal(schema.getQName().getNamespace(), previousAugment.getNamespace())) {
             validQName = QName.create(currentAugment, schema.getQName().getLocalName());
         }
 
         String moduleName = null;
         if (mountPoint == null) {
             moduleName = controllerContext.findModuleNameByNamespace(validQName.getNamespace());
-        }
-        else {
+        } else {
             moduleName = controllerContext.findModuleNameByNamespace(mountPoint, validQName.getNamespace());
         }
 
-        if (nodeBuilder.getNamespace() == null ||
-            Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace()) ||
-            Objects.equal(nodeBuilder.getNamespace().toString(), moduleName) /*||
-            Note: this check is wrong - can never be true as it compares a URI with a String
-                  not sure what the intention is so commented out...
-            Objects.equal(nodeBuilder.getNamespace(), MOUNT_POINT_MODULE_NAME)*/ ) {
+        if (nodeBuilder.getNamespace() == null || Objects.equal(nodeBuilder.getNamespace(), validQName.getNamespace())
+                || Objects.equal(nodeBuilder.getNamespace().toString(), moduleName) /*
+                                                                                     * || Note : this check is wrong -
+                                                                                     * can never be true as it compares
+                                                                                     * a URI with a String not sure what
+                                                                                     * the intention is so commented out
+                                                                                     * ... Objects . equal ( nodeBuilder
+                                                                                     * . getNamespace ( ) ,
+                                                                                     * MOUNT_POINT_MODULE_NAME )
+                                                                                     */) {
 
             nodeBuilder.setQname(validQName);
         }
@@ -1175,40 +1225,31 @@ public class RestconfImpl implements RestconfService {
 
     private URI namespace(final CompositeNode data) {
         if (data instanceof CompositeNodeWrapper) {
-            return ((CompositeNodeWrapper)data).getNamespace();
-        }
-        else if (data != null) {
+            return ((CompositeNodeWrapper) data).getNamespace();
+        } else if (data != null) {
             return data.getNodeType().getNamespace();
-        }
-        else {
-            throw new IllegalArgumentException("Unhandled parameter types: " +
-                    Arrays.<Object>asList(data).toString());
+        } else {
+            throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
         }
     }
 
     private String localName(final CompositeNode data) {
         if (data instanceof CompositeNodeWrapper) {
-            return ((CompositeNodeWrapper)data).getLocalName();
-        }
-        else if (data != null) {
+            return ((CompositeNodeWrapper) data).getLocalName();
+        } else if (data != null) {
             return data.getNodeType().getLocalName();
-        }
-        else {
-            throw new IllegalArgumentException("Unhandled parameter types: " +
-                    Arrays.<Object>asList(data).toString());
+        } else {
+            throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
         }
     }
 
     private String getName(final CompositeNode data) {
         if (data instanceof CompositeNodeWrapper) {
-            return ((CompositeNodeWrapper)data).getLocalName();
-        }
-        else if (data != null) {
+            return ((CompositeNodeWrapper) data).getLocalName();
+        } else if (data != null) {
             return data.getNodeType().getLocalName();
-        }
-        else {
-            throw new IllegalArgumentException("Unhandled parameter types: " +
-                    Arrays.<Object>asList(data).toString());
+        } else {
+            throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(data).toString());
         }
     }
 
@@ -1232,14 +1273,13 @@ public class RestconfImpl implements RestconfService {
 
     private TypeDefinition<? extends Object> typeDefinition(final DataSchemaNode node) {
         if (node instanceof LeafListSchemaNode) {
-            return typeDefinition((LeafListSchemaNode)node);
-        }
-        else if (node instanceof LeafSchemaNode) {
-            return _typeDefinition((LeafSchemaNode)node);
-        }
-        else {
-            throw new IllegalArgumentException("Unhandled parameter types: " +
-                    Arrays.<Object>asList(node).toString());
+            return typeDefinition((LeafListSchemaNode) node);
+        } else if (node instanceof LeafSchemaNode) {
+            return _typeDefinition((LeafSchemaNode) node);
+        } else if (node instanceof AnyXmlSchemaNode) {
+            return null;
+        } else {
+            throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
         }
     }
 }
index 3131668ed9ed23ae8fb8f0edb75076c8635a235d..854e9635cf3cde883d97bbcc28f29c99bbda5c9c 100644 (file)
@@ -7,8 +7,8 @@
  */
 package org.opendaylight.controller.sal.restconf.impl;
 
+import com.google.common.base.Preconditions;
 import java.net.URI;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
@@ -16,8 +16,6 @@ import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
 import org.opendaylight.yangtools.yang.data.api.SimpleNode;
 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
 
-import com.google.common.base.Preconditions;
-
 public final class SimpleNodeWrapper implements NodeWrapper<SimpleNode<?>>, SimpleNode<Object> {
 
     private SimpleNode<Object> simpleNode;
@@ -27,18 +25,18 @@ public final class SimpleNodeWrapper implements NodeWrapper<SimpleNode<?>>, Simp
     private URI namespace;
     private QName name;
 
-    public SimpleNodeWrapper(String localName, Object value) {
+    public SimpleNodeWrapper(final String localName, final Object value) {
         this.localName = Preconditions.checkNotNull(localName);
         this.value = value;
     }
 
-    public SimpleNodeWrapper(URI namespace, String localName, Object value) {
+    public SimpleNodeWrapper(final URI namespace, final String localName, final Object value) {
         this(localName, value);
         this.namespace = namespace;
     }
 
     @Override
-    public void setQname(QName name) {
+    public void setQname(final QName name) {
         Preconditions.checkState(simpleNode == null, "Cannot change the object, due to data inconsistencies.");
         this.name = name;
     }
@@ -65,7 +63,7 @@ public final class SimpleNodeWrapper implements NodeWrapper<SimpleNode<?>>, Simp
     }
 
     @Override
-    public void setNamespace(URI namespace) {
+    public void setNamespace(final URI namespace) {
         Preconditions.checkState(simpleNode == null, "Cannot change the object, due to data inconsistencies.");
         this.namespace = namespace;
     }
@@ -89,7 +87,7 @@ public final class SimpleNodeWrapper implements NodeWrapper<SimpleNode<?>>, Simp
             localName = null;
             name = null;
         }
-        return (SimpleNode<Object>) simpleNode;
+        return simpleNode;
     }
 
     @Override
@@ -98,6 +96,7 @@ public final class SimpleNodeWrapper implements NodeWrapper<SimpleNode<?>>, Simp
     }
 
     @Override
+    @Deprecated
     public CompositeNode getParent() {
         return unwrap().getParent();
     }
@@ -108,6 +107,7 @@ public final class SimpleNodeWrapper implements NodeWrapper<SimpleNode<?>>, Simp
     }
 
     @Override
+    @Deprecated
     public ModifyAction getModificationAction() {
         return unwrap().getModificationAction();
     }
@@ -123,10 +123,8 @@ public final class SimpleNodeWrapper implements NodeWrapper<SimpleNode<?>>, Simp
     }
 
     @Override
-    public Object setValue(Object value) {
+    public Object setValue(final Object value) {
         return unwrap().setValue(value);
     }
 
-
-
 }
index 231fe7e02eedfdee29d2996a7d0ebc4839f73646..c745a8009deac75a70a7249626b07f56457d9243 100644 (file)
@@ -16,11 +16,18 @@ public class StructuredData {
     private final CompositeNode data;
     private final DataSchemaNode schema;
     private final MountInstance mountPoint;
+    private final boolean prettyPrintMode;
 
     public StructuredData(final CompositeNode data, final DataSchemaNode schema, final MountInstance mountPoint) {
+        this(data, schema, mountPoint, false);
+    }
+
+    public StructuredData(final CompositeNode data, final DataSchemaNode schema, final MountInstance mountPoint,
+            final boolean preattyPrintMode) {
         this.data = data;
         this.schema = schema;
         this.mountPoint = mountPoint;
+        this.prettyPrintMode = preattyPrintMode;
     }
 
     public CompositeNode getData() {
@@ -34,4 +41,8 @@ public class StructuredData {
     public MountInstance getMountPoint() {
         return mountPoint;
     }
+
+    public boolean isPrettyPrintMode() {
+        return prettyPrintMode;
+    }
 }
index 6008b1d3c7d8f1f3d5d3e131a569f5eb42b960d3..120c67d3d5f5c3f44bb387d861fc371a829a1700 100644 (file)
@@ -5,4 +5,4 @@
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
-package org.opendaylight.controller.sal.restconf.impl;
+package org.opendaylight.controller.sal.restconf.impl;
\ No newline at end of file
index 417cca653365bf96e925925226ee313513a79417..4c5e3ab5301e0dc1fa4f27507030bc479f49a012 100644 (file)
@@ -1,16 +1,15 @@
 /*
-* Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*/
+ * Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
 package org.opendaylight.controller.sal.restconf.rpc.impl;
 
 import java.util.concurrent.CancellationException;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.Future;
-
 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
@@ -21,7 +20,7 @@ import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
 public abstract class AbstractRpcExecutor implements RpcExecutor {
     private final RpcDefinition rpcDef;
 
-    public AbstractRpcExecutor( RpcDefinition rpcDef ){
+    public AbstractRpcExecutor(RpcDefinition rpcDef) {
         this.rpcDef = rpcDef;
     }
 
@@ -31,60 +30,47 @@ public abstract class AbstractRpcExecutor implements RpcExecutor {
     }
 
     @Override
-    public RpcResult<CompositeNode> invokeRpc( CompositeNode rpcRequest )
-                                                   throws RestconfDocumentedException {
+    public RpcResult<CompositeNode> invokeRpc(CompositeNode rpcRequest) throws RestconfDocumentedException {
         try {
-            return getRpcResult( invokeRpcUnchecked( rpcRequest ) );
-        }
-        catch( IllegalArgumentException e ) {
-            throw new RestconfDocumentedException(
-                                e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
-        }
-        catch( UnsupportedOperationException e ) {
-            throw new RestconfDocumentedException(
-                                e.getMessage(), ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED );
-        }
-        catch( Exception e ) {
-            throw new RestconfDocumentedException(
-                    "The operation encountered an unexpected error while executing.", e );
+            return getRpcResult(invokeRpcUnchecked(rpcRequest));
+        } catch (IllegalArgumentException e) {
+            throw new RestconfDocumentedException(e.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
+        } catch (UnsupportedOperationException e) {
+            throw new RestconfDocumentedException(e.getMessage(), ErrorType.RPC, ErrorTag.OPERATION_NOT_SUPPORTED);
+        } catch (Exception e) {
+            throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.", e);
         }
     }
 
-    protected abstract Future<RpcResult<CompositeNode>> invokeRpcUnchecked( CompositeNode rpcRequest );
+    protected abstract Future<RpcResult<CompositeNode>> invokeRpcUnchecked(CompositeNode rpcRequest);
 
-    protected RpcResult<CompositeNode> getRpcResult(
-                                            Future<RpcResult<CompositeNode>> fromFuture ) {
+    protected RpcResult<CompositeNode> getRpcResult(Future<RpcResult<CompositeNode>> fromFuture) {
         try {
             return fromFuture.get();
-        }
-        catch( InterruptedException e ) {
+        } catch (InterruptedException e) {
             throw new RestconfDocumentedException(
-                        "The operation was interrupted while executing and did not complete.",
-                        ErrorType.RPC, ErrorTag.PARTIAL_OPERATION );
-        }
-        catch( ExecutionException e ) {
+                    "The operation was interrupted while executing and did not complete.", ErrorType.RPC,
+                    ErrorTag.PARTIAL_OPERATION);
+        } catch (ExecutionException e) {
             Throwable cause = e.getCause();
-            if( cause instanceof CancellationException ) {
-                throw new RestconfDocumentedException(
-                        "The operation was cancelled while executing.",
-                        ErrorType.RPC, ErrorTag.PARTIAL_OPERATION );
-            }
-            else if( cause != null ){
-                while( cause.getCause() != null ) {
+            if (cause instanceof CancellationException) {
+                throw new RestconfDocumentedException("The operation was cancelled while executing.", ErrorType.RPC,
+                        ErrorTag.PARTIAL_OPERATION);
+            } else if (cause != null) {
+                while (cause.getCause() != null) {
                     cause = cause.getCause();
                 }
 
-                if( cause instanceof IllegalArgumentException ) {
-                    throw new RestconfDocumentedException(
-                            cause.getMessage(), ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                if (cause instanceof IllegalArgumentException) {
+                    throw new RestconfDocumentedException(cause.getMessage(), ErrorType.PROTOCOL,
+                            ErrorTag.INVALID_VALUE);
                 }
 
-                throw new RestconfDocumentedException(
-                       "The operation encountered an unexpected error while executing.", cause );
-            }
-            else {
-                throw new RestconfDocumentedException(
-                        "The operation encountered an unexpected error while executing.", e );
+                throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
+                        cause);
+            } else {
+                throw new RestconfDocumentedException("The operation encountered an unexpected error while executing.",
+                        e);
             }
         }
     }
index e23e95faab21e2cc129a745ba4959dbaa7da5ef3..146e69f0112214792c9b7067025615e922bb5408 100644 (file)
@@ -1,14 +1,13 @@
 /*
-* Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*/
+ * Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
 package org.opendaylight.controller.sal.restconf.rpc.impl;
 
 import java.util.concurrent.Future;
-
 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
@@ -17,14 +16,13 @@ import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
 public class BrokerRpcExecutor extends AbstractRpcExecutor {
     private final BrokerFacade broker;
 
-    public BrokerRpcExecutor( RpcDefinition rpcDef, BrokerFacade broker )
-    {
-        super( rpcDef );
+    public BrokerRpcExecutor(RpcDefinition rpcDef, BrokerFacade broker) {
+        super(rpcDef);
         this.broker = broker;
     }
 
     @Override
-    protected Future<RpcResult<CompositeNode>> invokeRpcUnchecked( CompositeNode rpcRequest ) {
-        return broker.invokeRpc( getRpcDefinition().getQName(), rpcRequest );
+    protected Future<RpcResult<CompositeNode>> invokeRpcUnchecked(CompositeNode rpcRequest) {
+        return broker.invokeRpc(getRpcDefinition().getQName(), rpcRequest);
     }
 }
\ No newline at end of file
index 26cb3b81028637c1b513e5d89aad837923684a79..36502656c22834829deaaa73f01defce0be1885d 100644 (file)
@@ -1,23 +1,22 @@
 /*
-* Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*/
+ * Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
 package org.opendaylight.controller.sal.restconf.rpc.impl;
 
+import com.google.common.base.Preconditions;
 import java.util.concurrent.Future;
-
 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
 
-import com.google.common.base.Preconditions;
-
 /**
  * Provides an implementation which invokes rpc methods via a mounted yang data model.
+ *
  * @author Devin Avery
  *
  */
@@ -25,13 +24,13 @@ public class MountPointRpcExecutor extends AbstractRpcExecutor {
     private final MountInstance mountPoint;
 
     public MountPointRpcExecutor(RpcDefinition rpcDef, MountInstance mountPoint) {
-        super( rpcDef );
+        super(rpcDef);
         this.mountPoint = mountPoint;
-        Preconditions.checkNotNull( mountPoint, "MountInstance can not be null." );
+        Preconditions.checkNotNull(mountPoint, "MountInstance can not be null.");
     }
 
     @Override
-    protected Future<RpcResult<CompositeNode>> invokeRpcUnchecked( CompositeNode rpcRequest ) {
-        return mountPoint.rpc( getRpcDefinition().getQName(), rpcRequest );
+    protected Future<RpcResult<CompositeNode>> invokeRpcUnchecked(CompositeNode rpcRequest) {
+        return mountPoint.rpc(getRpcDefinition().getQName(), rpcRequest);
     }
 }
\ No newline at end of file
index f628a63393d40e3016a96afb9b09c1fa196933e0..3430226c3a32174ffef9e3a6daac0230af91c98e 100644 (file)
@@ -1,10 +1,10 @@
 /*
-* Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*/
+ * Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
 package org.opendaylight.controller.sal.restconf.rpc.impl;
 
 import org.opendaylight.yangtools.yang.common.RpcResult;
@@ -12,7 +12,7 @@ import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
 
 public interface RpcExecutor {
-    RpcResult<CompositeNode> invokeRpc( CompositeNode rpcRequest );
+    RpcResult<CompositeNode> invokeRpc(CompositeNode rpcRequest);
 
     RpcDefinition getRpcDefinition();
 }
\ No newline at end of file
index 6282f37602be8236a737fe3e8ef42852816756bc..e526ec13be75fad83ff6c33b95dfe9ba0d809298 100644 (file)
@@ -7,10 +7,14 @@
  */
 package org.opendaylight.controller.sal.streams.listeners;
 
+import com.google.common.base.Charsets;
+import com.google.common.base.Preconditions;
+import com.google.common.eventbus.AsyncEventBus;
+import com.google.common.eventbus.EventBus;
+import com.google.common.eventbus.Subscribe;
 import io.netty.channel.Channel;
 import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
 import io.netty.util.internal.ConcurrentSet;
-
 import java.io.ByteArrayOutputStream;
 import java.io.OutputStreamWriter;
 import java.io.UnsupportedEncodingException;
@@ -23,7 +27,7 @@ import java.util.Map.Entry;
 import java.util.Random;
 import java.util.Set;
 import java.util.concurrent.Executors;
-
+import java.util.regex.Pattern;
 import javax.activation.UnsupportedDataTypeException;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
@@ -34,7 +38,6 @@ import javax.xml.transform.TransformerException;
 import javax.xml.transform.TransformerFactory;
 import javax.xml.transform.dom.DOMSource;
 import javax.xml.transform.stream.StreamResult;
-
 import org.opendaylight.controller.md.sal.common.api.data.DataChangeEvent;
 import org.opendaylight.controller.sal.core.api.data.DataChangeListener;
 import org.opendaylight.controller.sal.rest.impl.XmlMapper;
@@ -53,22 +56,18 @@ import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
-import com.google.common.base.Preconditions;
-import com.google.common.eventbus.AsyncEventBus;
-import com.google.common.eventbus.EventBus;
-import com.google.common.eventbus.Subscribe;
-
 /**
- * {@link ListenerAdapter} is responsible to track events, which occurred by
- * changing data in data source.
+ * {@link ListenerAdapter} is responsible to track events, which occurred by changing data in data source.
  */
 public class ListenerAdapter implements DataChangeListener {
 
-    private static final Logger logger = LoggerFactory
-            .getLogger(ListenerAdapter.class);
+    private static final Logger LOG = LoggerFactory.getLogger(ListenerAdapter.class);
+    private static final DocumentBuilderFactory DBF = DocumentBuilderFactory.newInstance();
+    private static final TransformerFactory FACTORY = TransformerFactory.newInstance();
+    private static final Pattern RFC3339_PATTERN = Pattern.compile("(\\d\\d)(\\d\\d)$");
+
     private final XmlMapper xmlMapper = new XmlMapper();
-    private final SimpleDateFormat rfc3339 = new SimpleDateFormat(
-            "yyyy-MM-dd'T'hh:mm:ssZ");
+    private final SimpleDateFormat rfc3339 = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ssZ");
 
     private final InstanceIdentifier path;
     private ListenerRegistration<DataChangeListener> registration;
@@ -78,18 +77,16 @@ public class ListenerAdapter implements DataChangeListener {
     private final EventBusChangeRecorder eventBusChangeRecorder;
 
     /**
-     * Creates new {@link ListenerAdapter} listener specified by path and stream
-     * name.
+     * Creates new {@link ListenerAdapter} listener specified by path and stream name.
      *
      * @param path
      *            Path to data in data store.
      * @param streamName
      *            The name of the stream.
      */
-    ListenerAdapter(InstanceIdentifier path, String streamName) {
+    ListenerAdapter(final InstanceIdentifier path, final String streamName) {
         Preconditions.checkNotNull(path);
-        Preconditions
-                .checkArgument(streamName != null && !streamName.isEmpty());
+        Preconditions.checkArgument(streamName != null && !streamName.isEmpty());
         this.path = path;
         this.streamName = streamName;
         eventBus = new AsyncEventBus(Executors.newSingleThreadExecutor());
@@ -98,14 +95,10 @@ public class ListenerAdapter implements DataChangeListener {
     }
 
     @Override
-    public void onDataChanged(
-            DataChangeEvent<InstanceIdentifier, CompositeNode> change) {
-        if (!change.getCreatedConfigurationData().isEmpty()
-                || !change.getCreatedOperationalData().isEmpty()
-                || !change.getUpdatedConfigurationData().isEmpty()
-                || !change.getUpdatedOperationalData().isEmpty()
-                || !change.getRemovedConfigurationData().isEmpty()
-                || !change.getRemovedOperationalData().isEmpty()) {
+    public void onDataChanged(final DataChangeEvent<InstanceIdentifier, CompositeNode> change) {
+        if (!change.getCreatedConfigurationData().isEmpty() || !change.getCreatedOperationalData().isEmpty()
+                || !change.getUpdatedConfigurationData().isEmpty() || !change.getUpdatedOperationalData().isEmpty()
+                || !change.getRemovedConfigurationData().isEmpty() || !change.getRemovedOperationalData().isEmpty()) {
             String xml = prepareXmlFrom(change);
             Event event = new Event(EventType.NOTIFY);
             event.setData(xml);
@@ -118,7 +111,7 @@ public class ListenerAdapter implements DataChangeListener {
      */
     private final class EventBusChangeRecorder {
         @Subscribe
-        public void recordCustomerChange(Event event) {
+        public void recordCustomerChange(final Event event) {
             if (event.getType() == EventType.REGISTER) {
                 Channel subscriber = event.getSubscriber();
                 if (!subscribers.contains(subscriber)) {
@@ -126,19 +119,14 @@ public class ListenerAdapter implements DataChangeListener {
                 }
             } else if (event.getType() == EventType.DEREGISTER) {
                 subscribers.remove(event.getSubscriber());
-                Notificator
-                        .removeListenerIfNoSubscriberExists(ListenerAdapter.this);
+                Notificator.removeListenerIfNoSubscriberExists(ListenerAdapter.this);
             } else if (event.getType() == EventType.NOTIFY) {
                 for (Channel subscriber : subscribers) {
                     if (subscriber.isActive()) {
-                        logger.debug("Data are sent to subscriber {}:",
-                                subscriber.remoteAddress());
-                        subscriber.writeAndFlush(new TextWebSocketFrame(event
-                                .getData()));
+                        LOG.debug("Data are sent to subscriber {}:", subscriber.remoteAddress());
+                        subscriber.writeAndFlush(new TextWebSocketFrame(event.getData()));
                     } else {
-                        logger.debug(
-                                "Subscriber {} is removed - channel is not active yet.",
-                                subscriber.remoteAddress());
+                        LOG.debug("Subscriber {} is removed - channel is not active yet.", subscriber.remoteAddress());
                         subscribers.remove(subscriber);
                     }
                 }
@@ -147,8 +135,7 @@ public class ListenerAdapter implements DataChangeListener {
     }
 
     /**
-     * Represents event of specific {@link EventType} type, holds data and
-     * {@link Channel} subscriber.
+     * Represents event of specific {@link EventType} type, holds data and {@link Channel} subscriber.
      */
     private final class Event {
         private final EventType type;
@@ -161,7 +148,7 @@ public class ListenerAdapter implements DataChangeListener {
          * @param type
          *            EventType
          */
-        public Event(EventType type) {
+        public Event(final EventType type) {
             this.type = type;
         }
 
@@ -180,7 +167,7 @@ public class ListenerAdapter implements DataChangeListener {
          * @param subscriber
          *            Channel
          */
-        public void setSubscriber(Channel subscriber) {
+        public void setSubscriber(final Channel subscriber) {
             this.subscriber = subscriber;
         }
 
@@ -199,7 +186,7 @@ public class ListenerAdapter implements DataChangeListener {
          * @param String
          *            data.
          */
-        public void setData(String data) {
+        public void setData(final String data) {
             this.data = data;
         }
 
@@ -217,7 +204,9 @@ public class ListenerAdapter implements DataChangeListener {
      * Type of the event.
      */
     private enum EventType {
-        REGISTER, DEREGISTER, NOTIFY;
+        REGISTER,
+        DEREGISTER,
+        NOTIFY;
     }
 
     /**
@@ -227,11 +216,9 @@ public class ListenerAdapter implements DataChangeListener {
      *            DataChangeEvent
      * @return Data in printable form.
      */
-    private String prepareXmlFrom(
-            DataChangeEvent<InstanceIdentifier, CompositeNode> change) {
+    private String prepareXmlFrom(final DataChangeEvent<InstanceIdentifier, CompositeNode> change) {
         Document doc = createDocument();
-        Element notificationElement = doc.createElementNS(
-                "urn:ietf:params:xml:ns:netconf:notification:1.0",
+        Element notificationElement = doc.createElementNS("urn:ietf:params:xml:ns:netconf:notification:1.0",
                 "notification");
         doc.appendChild(notificationElement);
 
@@ -240,30 +227,24 @@ public class ListenerAdapter implements DataChangeListener {
         notificationElement.appendChild(eventTimeElement);
 
         Element dataChangedNotificationEventElement = doc.createElementNS(
-                "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote",
-                "data-changed-notification");
-        addValuesToDataChangedNotificationEventElement(doc,
-                dataChangedNotificationEventElement, change);
+                "urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote", "data-changed-notification");
+        addValuesToDataChangedNotificationEventElement(doc, dataChangedNotificationEventElement, change);
         notificationElement.appendChild(dataChangedNotificationEventElement);
 
         try {
             ByteArrayOutputStream out = new ByteArrayOutputStream();
-            TransformerFactory tf = TransformerFactory.newInstance();
-            Transformer transformer = tf.newTransformer();
-            transformer
-                    .setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
+            Transformer transformer = FACTORY.newTransformer();
+            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
             transformer.setOutputProperty(OutputKeys.METHOD, "xml");
             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
             transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
-            transformer.setOutputProperty(
-                    "{http://xml.apache.org/xslt}indent-amount", "4");
-            transformer.transform(new DOMSource(doc), new StreamResult(
-                    new OutputStreamWriter(out, "UTF-8")));
+            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
+            transformer.transform(new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, Charsets.UTF_8)));
             byte[] charData = out.toByteArray();
             return new String(charData, "UTF-8");
         } catch (TransformerException | UnsupportedEncodingException e) {
             String msg = "Error during transformation of Document into String";
-            logger.error(msg, e);
+            LOG.error(msg, e);
             return msg;
         }
     }
@@ -275,8 +256,8 @@ public class ListenerAdapter implements DataChangeListener {
      *            Date
      * @return Data specified by RFC3339.
      */
-    private String toRFC3339(Date d) {
-        return rfc3339.format(d).replaceAll("(\\d\\d)(\\d\\d)$", "$1:$2");
+    private String toRFC3339(final Date d) {
+        return RFC3339_PATTERN.matcher(rfc3339.format(d)).replaceAll("$1:$2");
     }
 
     /**
@@ -285,15 +266,13 @@ public class ListenerAdapter implements DataChangeListener {
      * @return {@link Document} document.
      */
     private Document createDocument() {
-        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
-        Document doc = null;
+        final DocumentBuilder bob;
         try {
-            DocumentBuilder bob = dbf.newDocumentBuilder();
-            doc = bob.newDocument();
+            bob = DBF.newDocumentBuilder();
         } catch (ParserConfigurationException e) {
             return null;
         }
-        return doc;
+        return bob.newDocument();
     }
 
     /**
@@ -306,32 +285,25 @@ public class ListenerAdapter implements DataChangeListener {
      * @param change
      *            {@link DataChangeEvent}
      */
-    private void addValuesToDataChangedNotificationEventElement(Document doc,
-            Element dataChangedNotificationEventElement,
-            DataChangeEvent<InstanceIdentifier, CompositeNode> change) {
-        addValuesFromDataToElement(doc, change.getCreatedConfigurationData(),
-                dataChangedNotificationEventElement, Store.CONFIG,
-                Operation.CREATED);
-        addValuesFromDataToElement(doc, change.getCreatedOperationalData(),
-                dataChangedNotificationEventElement, Store.OPERATION,
-                Operation.CREATED);
+    private void addValuesToDataChangedNotificationEventElement(final Document doc,
+            final Element dataChangedNotificationEventElement,
+            final DataChangeEvent<InstanceIdentifier, CompositeNode> change) {
+        addValuesFromDataToElement(doc, change.getCreatedConfigurationData(), dataChangedNotificationEventElement,
+                Store.CONFIG, Operation.CREATED);
+        addValuesFromDataToElement(doc, change.getCreatedOperationalData(), dataChangedNotificationEventElement,
+                Store.OPERATION, Operation.CREATED);
         if (change.getCreatedConfigurationData().isEmpty()) {
-            addValuesFromDataToElement(doc,
-                    change.getUpdatedConfigurationData(),
-                    dataChangedNotificationEventElement, Store.CONFIG,
-                    Operation.UPDATED);
+            addValuesFromDataToElement(doc, change.getUpdatedConfigurationData(), dataChangedNotificationEventElement,
+                    Store.CONFIG, Operation.UPDATED);
         }
         if (change.getCreatedOperationalData().isEmpty()) {
-            addValuesFromDataToElement(doc, change.getUpdatedOperationalData(),
-                    dataChangedNotificationEventElement, Store.OPERATION,
-                    Operation.UPDATED);
+            addValuesFromDataToElement(doc, change.getUpdatedOperationalData(), dataChangedNotificationEventElement,
+                    Store.OPERATION, Operation.UPDATED);
         }
-        addValuesFromDataToElement(doc, change.getRemovedConfigurationData(),
-                dataChangedNotificationEventElement, Store.CONFIG,
-                Operation.DELETED);
-        addValuesFromDataToElement(doc, change.getRemovedOperationalData(),
-                dataChangedNotificationEventElement, Store.OPERATION,
-                Operation.DELETED);
+        addValuesFromDataToElement(doc, change.getRemovedConfigurationData(), dataChangedNotificationEventElement,
+                Store.CONFIG, Operation.DELETED);
+        addValuesFromDataToElement(doc, change.getRemovedOperationalData(), dataChangedNotificationEventElement,
+                Store.OPERATION, Operation.DELETED);
     }
 
     /**
@@ -348,15 +320,13 @@ public class ListenerAdapter implements DataChangeListener {
      * @param operation
      *            {@link Operation}
      */
-    private void addValuesFromDataToElement(Document doc,
-            Set<InstanceIdentifier> data, Element element, Store store,
-            Operation operation) {
+    private void addValuesFromDataToElement(final Document doc, final Set<InstanceIdentifier> data,
+            final Element element, final Store store, final Operation operation) {
         if (data == null || data.isEmpty()) {
             return;
         }
         for (InstanceIdentifier path : data) {
-            Node node = createDataChangeEventElement(doc, path, null, store,
-                    operation);
+            Node node = createDataChangeEventElement(doc, path, null, store, operation);
             element.appendChild(node);
         }
     }
@@ -375,15 +345,13 @@ public class ListenerAdapter implements DataChangeListener {
      * @param operation
      *            {@link Operation}
      */
-    private void addValuesFromDataToElement(Document doc,
-            Map<InstanceIdentifier, CompositeNode> data, Element element,
-            Store store, Operation operation) {
+    private void addValuesFromDataToElement(final Document doc, final Map<InstanceIdentifier, CompositeNode> data,
+            final Element element, final Store store, final Operation operation) {
         if (data == null || data.isEmpty()) {
             return;
         }
         for (Entry<InstanceIdentifier, CompositeNode> entry : data.entrySet()) {
-            Node node = createDataChangeEventElement(doc, entry.getKey(),
-                    entry.getValue(), store, operation);
+            Node node = createDataChangeEventElement(doc, entry.getKey(), entry.getValue(), store, operation);
             element.appendChild(node);
         }
     }
@@ -403,9 +371,8 @@ public class ListenerAdapter implements DataChangeListener {
      *            {@link Operation}
      * @return {@link Node} node represented by changed event element.
      */
-    private Node createDataChangeEventElement(Document doc,
-            InstanceIdentifier path, CompositeNode data, Store store,
-            Operation operation) {
+    private Node createDataChangeEventElement(final Document doc, final InstanceIdentifier path,
+            final CompositeNode data, final Store store, final Operation operation) {
         Element dataChangeEventElement = doc.createElement("data-change-event");
 
         Element pathElement = doc.createElement("path");
@@ -440,11 +407,10 @@ public class ListenerAdapter implements DataChangeListener {
      *            {@link CompositeNode}
      * @return Data in XML format.
      */
-    private Node translateToXml(InstanceIdentifier path, CompositeNode data) {
-        DataNodeContainer schemaNode = ControllerContext.getInstance()
-                .getDataNodeContainerFor(path);
+    private Node translateToXml(final InstanceIdentifier path, final CompositeNode data) {
+        DataNodeContainer schemaNode = ControllerContext.getInstance().getDataNodeContainerFor(path);
         if (schemaNode == null) {
-            logger.info(
+            LOG.info(
                     "Path '{}' contains node with unsupported type (supported type is Container or List) or some node was not found.",
                     path);
             return null;
@@ -453,9 +419,7 @@ public class ListenerAdapter implements DataChangeListener {
             Document xml = xmlMapper.write(data, schemaNode);
             return xml.getFirstChild();
         } catch (UnsupportedDataTypeException e) {
-            logger.error(
-                    "Error occured during translation of notification to XML.",
-                    e);
+            LOG.error("Error occured during translation of notification to XML.", e);
             return null;
         }
     }
@@ -468,25 +432,22 @@ public class ListenerAdapter implements DataChangeListener {
      * @param element
      *            {@link Element}
      */
-    private void addPathAsValueToElement(InstanceIdentifier path,
-            Element element) {
+    private void addPathAsValueToElement(final InstanceIdentifier path, final Element element) {
         // Map< key = namespace, value = prefix>
         Map<String, String> prefixes = new HashMap<>();
         InstanceIdentifier instanceIdentifier = path;
         StringBuilder textContent = new StringBuilder();
-        for (PathArgument pathArgument : instanceIdentifier.getPath()) {
+
+        // FIXME: BUG-1281: this is duplicated code from yangtools (BUG-1275)
+        for (PathArgument pathArgument : instanceIdentifier.getPathArguments()) {
             textContent.append("/");
-            writeIdentifierWithNamespacePrefix(element, textContent,
-                    pathArgument.getNodeType(), prefixes);
+            writeIdentifierWithNamespacePrefix(element, textContent, pathArgument.getNodeType(), prefixes);
             if (pathArgument instanceof NodeIdentifierWithPredicates) {
-                Map<QName, Object> predicates = ((NodeIdentifierWithPredicates) pathArgument)
-                        .getKeyValues();
+                Map<QName, Object> predicates = ((NodeIdentifierWithPredicates) pathArgument).getKeyValues();
                 for (QName keyValue : predicates.keySet()) {
-                    String predicateValue = String.valueOf(predicates
-                            .get(keyValue));
+                    String predicateValue = String.valueOf(predicates.get(keyValue));
                     textContent.append("[");
-                    writeIdentifierWithNamespacePrefix(element, textContent,
-                            keyValue, prefixes);
+                    writeIdentifierWithNamespacePrefix(element, textContent, keyValue, prefixes);
                     textContent.append("='");
                     textContent.append(predicateValue);
                     textContent.append("'");
@@ -514,14 +475,13 @@ public class ListenerAdapter implements DataChangeListener {
      * @param prefixes
      *            Map of namespaces and prefixes.
      */
-    private static void writeIdentifierWithNamespacePrefix(Element element,
-            StringBuilder textContent, QName qName, Map<String, String> prefixes) {
+    private static void writeIdentifierWithNamespacePrefix(final Element element, final StringBuilder textContent,
+            final QName qName, final Map<String, String> prefixes) {
         String namespace = qName.getNamespace().toString();
         String prefix = prefixes.get(namespace);
         if (prefix == null) {
             prefix = qName.getPrefix();
-            if (prefix == null || prefix.isEmpty()
-                    || prefixes.containsValue(prefix)) {
+            if (prefix == null || prefix.isEmpty() || prefixes.containsValue(prefix)) {
                 prefix = generateNewPrefix(prefixes.values());
             }
         }
@@ -541,7 +501,7 @@ public class ListenerAdapter implements DataChangeListener {
      *            Collection of prefixes.
      * @return New prefix which consists of four random characters <a-z>.
      */
-    private static String generateNewPrefix(Collection<String> prefixes) {
+    private static String generateNewPrefix(final Collection<String> prefixes) {
         StringBuilder result = null;
         Random random = new Random();
         do {
@@ -570,8 +530,7 @@ public class ListenerAdapter implements DataChangeListener {
      * @param registration
      *            ListenerRegistration<DataChangeListener>
      */
-    public void setRegistration(
-            ListenerRegistration<DataChangeListener> registration) {
+    public void setRegistration(final ListenerRegistration<DataChangeListener> registration) {
         this.registration = registration;
     }
 
@@ -585,8 +544,7 @@ public class ListenerAdapter implements DataChangeListener {
     }
 
     /**
-     * Removes all subscribers and unregisters event bus change recorder form
-     * event bus.
+     * Removes all subscribers and unregisters event bus change recorder form event bus.
      */
     public void close() throws Exception {
         subscribers = new ConcurrentSet<>();
@@ -605,16 +563,15 @@ public class ListenerAdapter implements DataChangeListener {
     }
 
     /**
-     * Creates event of type {@link EventType#REGISTER}, set {@link Channel}
-     * subscriber to the event and post event into event bus.
+     * Creates event of type {@link EventType#REGISTER}, set {@link Channel} subscriber to the event and post event into
+     * event bus.
      *
      * @param subscriber
      *            Channel
      */
-    public void addSubscriber(Channel subscriber) {
+    public void addSubscriber(final Channel subscriber) {
         if (!subscriber.isActive()) {
-            logger.debug("Channel is not active between websocket server and subscriber {}"
-                    + subscriber.remoteAddress());
+            LOG.debug("Channel is not active between websocket server and subscriber {}" + subscriber.remoteAddress());
         }
         Event event = new Event(EventType.REGISTER);
         event.setSubscriber(subscriber);
@@ -622,13 +579,13 @@ public class ListenerAdapter implements DataChangeListener {
     }
 
     /**
-     * Creates event of type {@link EventType#DEREGISTER}, sets {@link Channel}
-     * subscriber to the event and posts event into event bus.
+     * Creates event of type {@link EventType#DEREGISTER}, sets {@link Channel} subscriber to the event and posts event
+     * into event bus.
      *
      * @param subscriber
      */
-    public void removeSubscriber(Channel subscriber) {
-        logger.debug("Subscriber {} is removed.", subscriber.remoteAddress());
+    public void removeSubscriber(final Channel subscriber) {
+        LOG.debug("Subscriber {} is removed.", subscriber.remoteAddress());
         Event event = new Event(EventType.DEREGISTER);
         event.setSubscriber(subscriber);
         eventBus.post(event);
@@ -637,8 +594,7 @@ public class ListenerAdapter implements DataChangeListener {
     /**
      * Checks if exists at least one {@link Channel} subscriber.
      *
-     * @return True if exist at least one {@link Channel} subscriber, false
-     *         otherwise.
+     * @return True if exist at least one {@link Channel} subscriber, false otherwise.
      */
     public boolean hasSubscribers() {
         return !subscribers.isEmpty();
@@ -648,25 +604,27 @@ public class ListenerAdapter implements DataChangeListener {
      * Consists of two types {@link Store#CONFIG} and {@link Store#OPERATION}.
      */
     private static enum Store {
-        CONFIG("config"), OPERATION("operation");
+        CONFIG("config"),
+        OPERATION("operation");
 
         private final String value;
 
-        private Store(String value) {
+        private Store(final String value) {
             this.value = value;
         }
     }
 
     /**
-     * Consists of three types {@link Operation#CREATED},
-     * {@link Operation#UPDATED} and {@link Operation#DELETED}.
+     * Consists of three types {@link Operation#CREATED}, {@link Operation#UPDATED} and {@link Operation#DELETED}.
      */
     private static enum Operation {
-        CREATED("created"), UPDATED("updated"), DELETED("deleted");
+        CREATED("created"),
+        UPDATED("updated"),
+        DELETED("deleted");
 
         private final String value;
 
-        private Operation(String value) {
+        private Operation(final String value) {
             this.value = value;
         }
     }
index a576eed26978fb0380cd8a28613712409bf6ce53..166c473b9c77d118b14c822bc177a1320b77e0fe 100644 (file)
@@ -12,7 +12,6 @@ import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantLock;
-
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
 
 /**
@@ -34,7 +33,6 @@ public class Notificator {
         return listenersByStreamName.keySet();
     }
 
-
     /**
      * Gets {@link ListenerAdapter} specified by stream name.
      *
@@ -47,8 +45,7 @@ public class Notificator {
     }
 
     /**
-     * Gets {@link ListenerAdapter} listener specified by
-     * {@link InstanceIdentifier} path.
+     * Gets {@link ListenerAdapter} listener specified by {@link InstanceIdentifier} path.
      *
      * @param path
      *            Path to data in data repository.
@@ -59,8 +56,7 @@ public class Notificator {
     }
 
     /**
-     * Checks if the listener specified by {@link InstanceIdentifier} path
-     * exist.
+     * Checks if the listener specified by {@link InstanceIdentifier} path exist.
      *
      * @param path
      *            Path to data in data repository.
@@ -71,18 +67,15 @@ public class Notificator {
     }
 
     /**
-     * Creates new {@link ListenerAdapter} listener from
-     * {@link InstanceIdentifier} path and stream name.
+     * Creates new {@link ListenerAdapter} listener from {@link InstanceIdentifier} path and stream name.
      *
      * @param path
      *            Path to data in data repository.
      * @param streamName
      *            The name of the stream.
-     * @return New {@link ListenerAdapter} listener from
-     *         {@link InstanceIdentifier} path and stream name.
+     * @return New {@link ListenerAdapter} listener from {@link InstanceIdentifier} path and stream name.
      */
-    public static ListenerAdapter createListener(InstanceIdentifier path,
-            String streamName) {
+    public static ListenerAdapter createListener(InstanceIdentifier path, String streamName) {
         ListenerAdapter listener = new ListenerAdapter(path, streamName);
         try {
             lock.lock();
@@ -95,8 +88,7 @@ public class Notificator {
     }
 
     /**
-     * Looks for listener determined by {@link InstanceIdentifier} path and
-     * removes it.
+     * Looks for listener determined by {@link InstanceIdentifier} path and removes it.
      *
      * @param path
      *            InstanceIdentifier
@@ -107,8 +99,7 @@ public class Notificator {
     }
 
     /**
-     * Creates String representation of stream name from URI. Removes slash from
-     * URI in start and end position.
+     * Creates String representation of stream name from URI. Removes slash from URI in start and end position.
      *
      * @param uri
      *            URI for creation stream name.
@@ -148,14 +139,12 @@ public class Notificator {
     }
 
     /**
-     * Checks if listener has at least one subscriber. In case it doesn't have any, delete
-     * listener.
+     * Checks if listener has at least one subscriber. In case it doesn't have any, delete listener.
      *
      * @param listener
      *            ListenerAdapter
      */
-    public static void removeListenerIfNoSubscriberExists(
-            ListenerAdapter listener) {
+    public static void removeListenerIfNoSubscriberExists(ListenerAdapter listener) {
         if (!listener.hasSubscribers()) {
             deleteListener(listener);
         }
index fcfa8858ee940065baee9f4c8c4df2fb3a73089c..67ed44f84ea86020b54553f3f0b4f108e4ada66f 100644 (file)
@@ -1,27 +1,76 @@
 package org.opendaylight.controller.sal.streams.websockets;
 
+import com.google.common.base.Preconditions;
 import io.netty.bootstrap.ServerBootstrap;
 import io.netty.channel.Channel;
 import io.netty.channel.EventLoopGroup;
 import io.netty.channel.nio.NioEventLoopGroup;
 import io.netty.channel.socket.nio.NioServerSocketChannel;
-
 import org.opendaylight.controller.sal.streams.listeners.Notificator;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * {@link WebSocketServer} is responsible to start and stop web socket server at
- * {@link #PORT}.
+ * {@link WebSocketServer} is responsible to start and stop web socket server
  */
 public class WebSocketServer implements Runnable {
 
-    private static final Logger logger = LoggerFactory
-            .getLogger(WebSocketServer.class);
-
-    public static final int PORT = 8181;
+    private static final Logger logger = LoggerFactory.getLogger(WebSocketServer.class);
+    public static final String WEBSOCKET_SERVER_CONFIG_PROPERTY = "restconf.websocket.port";
+    public static final int DEFAULT_PORT = 8181;
     private EventLoopGroup bossGroup;
     private EventLoopGroup workerGroup;
+    private static WebSocketServer singleton = null;
+    private int port = DEFAULT_PORT;
+
+    private WebSocketServer(int port) {
+        this.port = port;
+    }
+
+    /**
+     * Create instance of {@link WebSocketServer}
+     *
+     * @param port
+     *            TCP port used for this server
+     * @return instance of {@link WebSocketServer}
+     */
+    public static WebSocketServer createInstance(int port) {
+        if (singleton != null) {
+            throw new IllegalStateException("createInstance() has already been called");
+        }
+        if (port < 1024) {
+            throw new IllegalArgumentException("Privileged port (below 1024) is not allowed");
+        }
+        singleton = new WebSocketServer(port);
+        return singleton;
+    }
+
+    /**
+     * Return websocket TCP port
+     */
+    public int getPort() {
+        return port;
+    }
+
+    /**
+     * Get instance of {@link WebSocketServer} created by {@link #createInstance(int)}
+     *
+     * @return instance of {@link WebSocketServer}
+     */
+    public static WebSocketServer getInstance() {
+        Preconditions.checkNotNull(singleton, "createInstance() must be called prior to getInstance()");
+        return singleton;
+    }
+
+    /**
+     * Destroy this already created instance
+     */
+    public static void destroyInstance() {
+        if (singleton == null) {
+            throw new IllegalStateException("createInstance() must be called prior to destroyInstance()");
+        }
+        getInstance().stop();
+    }
 
     @Override
     public void run() {
@@ -29,12 +78,11 @@ public class WebSocketServer implements Runnable {
         workerGroup = new NioEventLoopGroup();
         try {
             ServerBootstrap b = new ServerBootstrap();
-            b.group(bossGroup, workerGroup)
-                    .channel(NioServerSocketChannel.class)
+            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                     .childHandler(new WebSocketServerInitializer());
 
-            Channel ch = b.bind(PORT).sync().channel();
-            logger.info("Web socket server started at port {}.", PORT);
+            Channel ch = b.bind(port).sync().channel();
+            logger.info("Web socket server started at port {}.", port);
 
             ch.closeFuture().sync();
         } catch (InterruptedException e) {
index b5d6a6ea9be647d22c1dc8a75609506433e850f6..ce12d34e083f2ca440c754ab736aed1834276e0f 100644 (file)
@@ -8,6 +8,7 @@ import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
 import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
 import static io.netty.handler.codec.http.HttpResponseStatus.INTERNAL_SERVER_ERROR;
 import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;
+
 import io.netty.buffer.ByteBuf;
 import io.netty.buffer.Unpooled;
 import io.netty.channel.ChannelFuture;
@@ -25,29 +26,24 @@ import io.netty.handler.codec.http.websocketx.WebSocketFrame;
 import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
 import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
 import io.netty.util.CharsetUtil;
-
 import java.io.IOException;
-
 import org.opendaylight.controller.sal.streams.listeners.ListenerAdapter;
 import org.opendaylight.controller.sal.streams.listeners.Notificator;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 /**
- * {@link WebSocketServerHandler} is implementation of
- * {@link SimpleChannelInboundHandler} which allow handle
+ * {@link WebSocketServerHandler} is implementation of {@link SimpleChannelInboundHandler} which allow handle
  * {@link FullHttpRequest} and {@link WebSocketFrame} messages.
  */
 public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {
 
-    private static final Logger logger = LoggerFactory
-            .getLogger(WebSocketServerHandler.class);
+    private static final Logger logger = LoggerFactory.getLogger(WebSocketServerHandler.class);
 
     private WebSocketServerHandshaker handshaker;
 
     @Override
-    protected void channelRead0(ChannelHandlerContext ctx, Object msg)
-            throws Exception {
+    protected void channelRead0(final ChannelHandlerContext ctx, final Object msg) throws Exception {
         if (msg instanceof FullHttpRequest) {
             handleHttpRequest(ctx, (FullHttpRequest) msg);
         } else if (msg instanceof WebSocketFrame) {
@@ -56,27 +52,23 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>
     }
 
     /**
-     * Checks if HTTP request method is GET and if is possible to decode HTTP
-     * result of request.
+     * Checks if HTTP request method is GET and if is possible to decode HTTP result of request.
      *
      * @param ctx
      *            ChannelHandlerContext
      * @param req
      *            FullHttpRequest
      */
-    private void handleHttpRequest(ChannelHandlerContext ctx,
-            FullHttpRequest req) throws Exception {
+    private void handleHttpRequest(final ChannelHandlerContext ctx, final FullHttpRequest req) throws Exception {
         // Handle a bad request.
         if (!req.getDecoderResult().isSuccess()) {
-            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
-                    BAD_REQUEST));
+            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, BAD_REQUEST));
             return;
         }
 
         // Allow only GET methods.
         if (req.getMethod() != GET) {
-            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
-                    FORBIDDEN));
+            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, FORBIDDEN));
             return;
         }
 
@@ -86,19 +78,16 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>
             listener.addSubscriber(ctx.channel());
             logger.debug("Subscriber successfully registered.");
         } else {
-            logger.error("Listener for stream with name '{}' was not found.",
-                    streamName);
-            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1,
-                    INTERNAL_SERVER_ERROR));
+            logger.error("Listener for stream with name '{}' was not found.", streamName);
+            sendHttpResponse(ctx, req, new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR));
         }
 
         // Handshake
-        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
-                getWebSocketLocation(req), null, false);
+        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(getWebSocketLocation(req),
+                null, false);
         handshaker = wsFactory.newHandshaker(req);
         if (handshaker == null) {
-            WebSocketServerHandshakerFactory
-                    .sendUnsupportedWebSocketVersionResponse(ctx.channel());
+            WebSocketServerHandshakerFactory.sendUnsupportedVersionResponse(ctx.channel());
         } else {
             handshaker.handshake(ctx.channel(), req);
         }
@@ -115,12 +104,11 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>
      * @param res
      *            FullHttpResponse
      */
-    private static void sendHttpResponse(ChannelHandlerContext ctx,
-            HttpRequest req, FullHttpResponse res) {
+    private static void sendHttpResponse(final ChannelHandlerContext ctx, final HttpRequest req,
+            final FullHttpResponse res) {
         // Generate an error page if response getStatus code is not OK (200).
         if (res.getStatus().code() != 200) {
-            ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(),
-                    CharsetUtil.UTF_8);
+            ByteBuf buf = Unpooled.copiedBuffer(res.getStatus().toString(), CharsetUtil.UTF_8);
             res.content().writeBytes(buf);
             buf.release();
             setContentLength(res, res.content().readableBytes());
@@ -141,14 +129,10 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>
      * @param frame
      *            {@link WebSocketFrame}
      */
-    private void handleWebSocketFrame(ChannelHandlerContext ctx,
-            WebSocketFrame frame) throws IOException {
+    private void handleWebSocketFrame(final ChannelHandlerContext ctx, final WebSocketFrame frame) throws IOException {
         if (frame instanceof CloseWebSocketFrame) {
-            handshaker.close(ctx.channel(),
-                    (CloseWebSocketFrame) frame.retain());
-            String streamName = Notificator
-                    .createStreamNameFromUri(((CloseWebSocketFrame) frame)
-                            .reasonText());
+            handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain());
+            String streamName = Notificator.createStreamNameFromUri(((CloseWebSocketFrame) frame).reasonText());
             ListenerAdapter listener = Notificator.getListenerFor(streamName);
             if (listener != null) {
                 listener.removeSubscriber(ctx.channel());
@@ -157,15 +141,13 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>
             Notificator.removeListenerIfNoSubscriberExists(listener);
             return;
         } else if (frame instanceof PingWebSocketFrame) {
-            ctx.channel().write(
-                    new PongWebSocketFrame(frame.content().retain()));
+            ctx.channel().write(new PongWebSocketFrame(frame.content().retain()));
             return;
         }
     }
 
     @Override
-    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
-            throws Exception {
+    public void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) throws Exception {
         if (cause instanceof java.nio.channels.ClosedChannelException == false) {
             // cause.printStackTrace();
         }
@@ -179,7 +161,7 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>
      *            HTTP request from which the location will be returned
      * @return String representation of web socket location.
      */
-    private static String getWebSocketLocation(HttpRequest req) {
+    private static String getWebSocketLocation(final HttpRequest req) {
         return "http://" + req.headers().get(HOST) + req.getUri();
     }
 
index d188a029e7582a7672a67af0a956f978df79cc1b..754f156dde52d7b57eee9bc85b510685681bfc4c 100644 (file)
@@ -7,8 +7,8 @@ import io.netty.handler.codec.http.HttpObjectAggregator;
 import io.netty.handler.codec.http.HttpServerCodec;
 
 /**
- * {@link WebSocketServerInitializer} is used to setup the
- * {@link ChannelPipeline} of a {@link io.netty.channel.Channel}.
+ * {@link WebSocketServerInitializer} is used to setup the {@link ChannelPipeline} of a {@link io.netty.channel.Channel}
+ * .
  */
 public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> {
 
index d978a2f0de25af2f26c106dea7c79a759fea4ce0..0f059f5024cdc7c70dc7042f488e9fa22c32da55 100644 (file)
@@ -13,13 +13,13 @@ import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
 import java.io.IOException;
 import java.io.StringReader;
 import java.util.Map;
 import java.util.Set;
-
 import javax.ws.rs.WebApplicationException;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
@@ -37,9 +37,6 @@ import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
 import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
 
-import com.google.gson.stream.JsonReader;
-import com.google.gson.stream.JsonToken;
-
 public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
 
     @BeforeClass
@@ -48,8 +45,7 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     /**
-     * Test of json output when as input are specified composite node with empty
-     * data + YANG file
+     * Test of json output when as input are specified composite node with empty data + YANG file
      */
 
     @Test
@@ -67,8 +63,7 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     /**
-     * Test of json output when as input are specified xml file (no empty
-     * elements)and YANG file
+     * Test of json output when as input are specified xml file (no empty elements)and YANG file
      */
     @Test
     public void xmlAndYangTypesWithJsonReaderTest() {
@@ -355,11 +350,8 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
         assertEquals(1, lst11_1.getLfs().size());
         assertEquals(1, lst11_1.getConts().size());
         assertEquals(1, lst11_1.getLsts().size());
-        assertEquals(
-                lst11_1.getLsts().get("lst111"),
-                new Lst("lst111").addLstItem(new LstItem().addLf("lf1111", 35))
-                .addLstItem(new LstItem().addLf("lf1111", 34)).addLstItem(new LstItem())
-                .addLstItem(new LstItem()));
+        assertEquals(lst11_1.getLsts().get("lst111"), new Lst("lst111").addLstItem(new LstItem().addLf("lf1111", 35))
+                .addLstItem(new LstItem().addLf("lf1111", 34)).addLstItem(new LstItem()).addLstItem(new LstItem()));
         assertEquals(lst11_1.getConts().get("cont111"), new Cont("cont111"));
         // : lst11_1
 
@@ -378,8 +370,7 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
         assertEquals(1, lst11_2_cont111.getLsts().size());
         assertTrue(lst11_2_cont111.getConts().isEmpty());
 
-        assertEquals(new LfLst("lflst1111").addLf(1024).addLf(4096),
-                lst11_2_cont111.getLfLsts().get("lflst1111"));
+        assertEquals(new LfLst("lflst1111").addLf(1024).addLf(4096), lst11_2_cont111.getLfLsts().get("lflst1111"));
         assertEquals(
                 new Lst("lst1111").addLstItem(new LstItem().addLf("lf1111B", 4)).addLstItem(
                         new LstItem().addLf("lf1111A", "lf1111A str12")), lst11_2_cont111.getLsts().get("lst1111"));
@@ -539,90 +530,108 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
                 TestUtils.buildQName("cont1", "simple:yang:types", "2013-11-5"), null, null, ModifyAction.CREATE, null);
 
         // lst11_1
-        MutableCompositeNode lst11_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst11","simple:yang:types","2013-11-5"), cont1,
-                null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst11_1 = NodeFactory
+                .createMutableCompositeNode(TestUtils.buildQName("lst11", "simple:yang:types", "2013-11-5"), cont1,
+                        null, ModifyAction.CREATE, null);
         cont1.getValue().add(lst11_1);
 
-        MutableSimpleNode<?> lf111_1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf111","simple:yang:types","2013-11-5"), lst11_1,
-                (short) 1, ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lf111_1 = NodeFactory.createMutableSimpleNode(
+                TestUtils.buildQName("lf111", "simple:yang:types", "2013-11-5"), lst11_1, (short) 1,
+                ModifyAction.CREATE, null);
         lst11_1.getValue().add(lf111_1);
 
         // lst111_1_1
-        MutableCompositeNode lst111_1_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111","simple:yang:types","2013-11-5"),
-                lst11_1, null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst111_1_1 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("lst111", "simple:yang:types", "2013-11-5"), lst11_1, null, ModifyAction.CREATE,
+                null);
         lst11_1.getValue().add(lst111_1_1);
-        MutableSimpleNode<?> lf1111_1_1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111","simple:yang:types","2013-11-5"),
-                lst111_1_1, 34, ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lf1111_1_1 = NodeFactory.createMutableSimpleNode(
+                TestUtils.buildQName("lf1111", "simple:yang:types", "2013-11-5"), lst111_1_1, 34, ModifyAction.CREATE,
+                null);
         lst111_1_1.getValue().add(lf1111_1_1);
         lst111_1_1.init();
         // :lst111_1_1
 
         // lst111_1_2
-        MutableCompositeNode lst111_1_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111","simple:yang:types","2013-11-5"),
-                lst11_1, null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst111_1_2 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("lst111", "simple:yang:types", "2013-11-5"), lst11_1, null, ModifyAction.CREATE,
+                null);
         lst11_1.getValue().add(lst111_1_2);
-        MutableSimpleNode<?> lf1111_1_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111","simple:yang:types","2013-11-5"),
-                lst111_1_2, 35, ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lf1111_1_2 = NodeFactory.createMutableSimpleNode(
+                TestUtils.buildQName("lf1111", "simple:yang:types", "2013-11-5"), lst111_1_2, 35, ModifyAction.CREATE,
+                null);
         lst111_1_2.getValue().add(lf1111_1_2);
         lst111_1_2.init();
         // :lst111_1_2
 
         // lst111_1_3
-        MutableCompositeNode lst111_1_3 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111","simple:yang:types","2013-11-5"),
-                lst11_1, null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst111_1_3 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("lst111", "simple:yang:types", "2013-11-5"), lst11_1, null, ModifyAction.CREATE,
+                null);
         lst11_1.getValue().add(lst111_1_3);
         lst111_1_2.init();
         // :lst111_1_3
 
         // lst111_1_4
-        MutableCompositeNode lst111_1_4 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst111","simple:yang:types","2013-11-5"),
-                lst11_1, null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst111_1_4 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("lst111", "simple:yang:types", "2013-11-5"), lst11_1, null, ModifyAction.CREATE,
+                null);
         lst11_1.getValue().add(lst111_1_4);
         lst111_1_2.init();
         // :lst111_1_4
 
-        MutableCompositeNode cont111_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont111","simple:yang:types","2013-11-5"),
-                lst11_1, null, ModifyAction.CREATE, null);
+        MutableCompositeNode cont111_1 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("cont111", "simple:yang:types", "2013-11-5"), lst11_1, null, ModifyAction.CREATE,
+                null);
         lst11_1.getValue().add(cont111_1);
 
         lst11_1.init();
         // :lst11_1
 
         // lst11_2
-        MutableCompositeNode lst11_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst11","simple:yang:types","2013-11-5"), cont1,
-                null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst11_2 = NodeFactory
+                .createMutableCompositeNode(TestUtils.buildQName("lst11", "simple:yang:types", "2013-11-5"), cont1,
+                        null, ModifyAction.CREATE, null);
         cont1.getValue().add(lst11_2);
 
-        MutableSimpleNode<?> lf111_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf111","simple:yang:types","2013-11-5"), lst11_2,
-                (short) 2, ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lf111_2 = NodeFactory.createMutableSimpleNode(
+                TestUtils.buildQName("lf111", "simple:yang:types", "2013-11-5"), lst11_2, (short) 2,
+                ModifyAction.CREATE, null);
         lst11_2.getValue().add(lf111_2);
 
         // cont111_2
-        MutableCompositeNode cont111_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont111","simple:yang:types","2013-11-5"),
-                lst11_2, null, ModifyAction.CREATE, null);
+        MutableCompositeNode cont111_2 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("cont111", "simple:yang:types", "2013-11-5"), lst11_2, null, ModifyAction.CREATE,
+                null);
         lst11_2.getValue().add(cont111_2);
 
-        MutableSimpleNode<?> lflst1111_2_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lflst1111","simple:yang:types","2013-11-5"),
-                cont111_2, 1024, ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lflst1111_2_2 = NodeFactory.createMutableSimpleNode(
+                TestUtils.buildQName("lflst1111", "simple:yang:types", "2013-11-5"), cont111_2, 1024,
+                ModifyAction.CREATE, null);
         cont111_2.getValue().add(lflst1111_2_2);
-        MutableSimpleNode<?> lflst1111_2_3 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lflst1111","simple:yang:types","2013-11-5"),
-                cont111_2, 4096, ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lflst1111_2_3 = NodeFactory.createMutableSimpleNode(
+                TestUtils.buildQName("lflst1111", "simple:yang:types", "2013-11-5"), cont111_2, 4096,
+                ModifyAction.CREATE, null);
         cont111_2.getValue().add(lflst1111_2_3);
 
         // lst1111_2
-        MutableCompositeNode lst1111_2_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111","simple:yang:types","2013-11-5"),
-                cont111_2, null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst1111_2_1 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("lst1111", "simple:yang:types", "2013-11-5"), cont111_2, null,
+                ModifyAction.CREATE, null);
         cont111_2.getValue().add(lst1111_2_1);
-        MutableSimpleNode<?> lf1111B_2_1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111B","simple:yang:types","2013-11-5"),
-                lst1111_2_1, (short) 4, ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lf1111B_2_1 = NodeFactory.createMutableSimpleNode(
+                TestUtils.buildQName("lf1111B", "simple:yang:types", "2013-11-5"), lst1111_2_1, (short) 4,
+                ModifyAction.CREATE, null);
         lst1111_2_1.getValue().add(lf1111B_2_1);
         lst1111_2_1.init();
 
-        MutableCompositeNode lst1111_2_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111","simple:yang:types","2013-11-5"),
-                cont111_2, null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst1111_2_2 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("lst1111", "simple:yang:types", "2013-11-5"), cont111_2, null,
+                ModifyAction.CREATE, null);
         cont111_2.getValue().add(lst1111_2_2);
-        MutableSimpleNode<?> lf1111A_2_2 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1111A","simple:yang:types","2013-11-5"),
-                lst1111_2_2, "lf1111A str12", ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lf1111A_2_2 = NodeFactory.createMutableSimpleNode(
+                TestUtils.buildQName("lf1111A", "simple:yang:types", "2013-11-5"), lst1111_2_2, "lf1111A str12",
+                ModifyAction.CREATE, null);
         lst1111_2_2.getValue().add(lf1111A_2_2);
         lst1111_2_2.init();
         // :lst1111_2
@@ -630,8 +639,9 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
         cont111_2.init();
         // :cont111_2
 
-        MutableCompositeNode lst112_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst112","simple:yang:types","2013-11-5"), lst11_2,
-                null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst112_2 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("lst112", "simple:yang:types", "2013-11-5"), lst11_2, null, ModifyAction.CREATE,
+                null);
         lst11_2.getValue().add(lst112_2);
         lst112_2.init();
         lst11_2.init();
@@ -639,26 +649,31 @@ public class CnSnJsonBasicYangTypesTest extends YangAndXmlAndDataSchemaLoader {
         // :lst11_2
 
         // lst11_3
-        MutableCompositeNode lst11_3 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst11","simple:yang:types","2013-11-5"), cont1,
-                null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst11_3 = NodeFactory
+                .createMutableCompositeNode(TestUtils.buildQName("lst11", "simple:yang:types", "2013-11-5"), cont1,
+                        null, ModifyAction.CREATE, null);
         cont1.getValue().add(lst11_3);
 
-        MutableSimpleNode<?> lf111_3 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf111","simple:yang:types","2013-11-5"), lst11_3,
-                (short) 3, ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lf111_3 = NodeFactory.createMutableSimpleNode(
+                TestUtils.buildQName("lf111", "simple:yang:types", "2013-11-5"), lst11_3, (short) 3,
+                ModifyAction.CREATE, null);
         lst11_3.getValue().add(lf111_3);
 
         // cont111_3
-        MutableCompositeNode cont111_3 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont111","simple:yang:types","2013-11-5"),
-                lst11_3, null, ModifyAction.CREATE, null);
+        MutableCompositeNode cont111_3 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("cont111", "simple:yang:types", "2013-11-5"), lst11_3, null, ModifyAction.CREATE,
+                null);
         lst11_3.getValue().add(cont111_3);
 
-        MutableCompositeNode lst1111_3_1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111","simple:yang:types","2013-11-5"),
-                cont111_3, null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst1111_3_1 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("lst1111", "simple:yang:types", "2013-11-5"), cont111_3, null,
+                ModifyAction.CREATE, null);
         cont111_3.getValue().add(lst1111_3_1);
         lst1111_3_1.init();
 
-        MutableCompositeNode lst1111_3_2 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("lst1111","simple:yang:types","2013-11-5"),
-                cont111_3, null, ModifyAction.CREATE, null);
+        MutableCompositeNode lst1111_3_2 = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("lst1111", "simple:yang:types", "2013-11-5"), cont111_3, null,
+                ModifyAction.CREATE, null);
         cont111_3.getValue().add(lst1111_3_2);
         lst1111_3_2.init();
 
index 21590ecb335fa81c309012bc34b92c1975da169c..0d0ce5cdd36908e458e50ac242ef356d4008287e 100644 (file)
@@ -10,9 +10,7 @@ package org.opendaylight.controller.sal.restconf.impl.cnsn.to.json.test;
 import static org.junit.Assert.assertTrue;
 
 import java.io.IOException;
-
 import javax.ws.rs.WebApplicationException;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
@@ -29,9 +27,8 @@ public class CnSnJsonChoiceCaseTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     /**
-     * Test when some data are in one case node and other in another. This isn't
-     * correct. Next Json validator should return error because nodes has to be
-     * from one case below concrete choice.
+     * Test when some data are in one case node and other in another. This isn't correct. Next Json validator should
+     * return error because nodes has to be from one case below concrete choice.
      *
      */
     @Test
@@ -40,10 +37,9 @@ public class CnSnJsonChoiceCaseTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     /**
-     * Test when some data are in one case node and other in another.
-     * Additionally data are loadef from various choices. This isn't correct.
-     * Next Json validator should return error because nodes has to be from one
-     * case below concrete choice.
+     * Test when some data are in one case node and other in another. Additionally data are loadef from various choices.
+     * This isn't correct. Next Json validator should return error because nodes has to be from one case below concrete
+     * choice.
      *
      */
     @Test
@@ -53,8 +49,8 @@ public class CnSnJsonChoiceCaseTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     /**
-     * Test when second level data are red first, then first and at the end
-     * third level. Level represents pass through couple choice-case
+     * Test when second level data are red first, then first and at the end third level. Level represents pass through
+     * couple choice-case
      */
 
     @Test
@@ -103,8 +99,8 @@ public class CnSnJsonChoiceCaseTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     /**
-     * Test whether is possible to find data schema for node which is specified
-     * as dirrect subnode of choice (case without CASE key word)
+     * Test whether is possible to find data schema for node which is specified as dirrect subnode of choice (case
+     * without CASE key word)
      */
     @Test
     public void nodeSchemasInCaseNotDefinedWithCaseKeyword() {
index 1ec7253b8d595dea9ef3e62a05decbd224178975..4b8b71440a7688334897bafc3c3117e8e2dfb937 100644 (file)
@@ -13,10 +13,12 @@ import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.fail;
 
+import com.google.common.collect.Maps;
+import com.google.gson.stream.JsonReader;
+import com.google.gson.stream.JsonToken;
 import java.io.IOException;
 import java.io.StringReader;
 import java.util.Map;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
@@ -27,10 +29,6 @@ import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
 import org.opendaylight.controller.sal.restconf.impl.test.YangAndXmlAndDataSchemaLoader;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 
-import com.google.common.collect.Maps;
-import com.google.gson.stream.JsonReader;
-import com.google.gson.stream.JsonToken;
-
 public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader {
 
     static abstract class LeafVerifier {
@@ -38,15 +36,15 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader
         Object expectedValue;
         JsonToken expectedToken;
 
-        LeafVerifier( Object expectedValue, JsonToken expectedToken ) {
+        LeafVerifier(Object expectedValue, JsonToken expectedToken) {
             this.expectedValue = expectedValue;
             this.expectedToken = expectedToken;
         }
 
-        abstract Object getActualValue( JsonReader reader ) throws IOException;
+        abstract Object getActualValue(JsonReader reader) throws IOException;
 
-        void verify( JsonReader reader, String keyName ) throws IOException {
-            assertEquals( "Json value for key " + keyName, expectedValue, getActualValue( reader ) );
+        void verify(JsonReader reader, String keyName) throws IOException {
+            assertEquals("Json value for key " + keyName, expectedValue, getActualValue(reader));
         }
 
         JsonToken expectedTokenType() {
@@ -56,31 +54,29 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader
 
     static class BooleanVerifier extends LeafVerifier {
 
-        public BooleanVerifier( boolean expected ) {
-            super( expected, JsonToken.BOOLEAN );
+        public BooleanVerifier(boolean expected) {
+            super(expected, JsonToken.BOOLEAN);
         }
 
         @Override
-        Object getActualValue( JsonReader reader ) throws IOException {
+        Object getActualValue(JsonReader reader) throws IOException {
             return reader.nextBoolean();
         }
     }
 
     static class NumberVerifier extends LeafVerifier {
 
-        public NumberVerifier( Number expected ) {
-            super( expected, JsonToken.NUMBER );
+        public NumberVerifier(Number expected) {
+            super(expected, JsonToken.NUMBER);
         }
 
         @Override
-        Object getActualValue( JsonReader reader ) throws IOException {
-            if( expectedValue instanceof Double ) {
+        Object getActualValue(JsonReader reader) throws IOException {
+            if (expectedValue instanceof Double) {
                 return reader.nextDouble();
-            }
-            else if( expectedValue instanceof Long ) {
+            } else if (expectedValue instanceof Long) {
                 return reader.nextLong();
-            }
-            else if( expectedValue instanceof Integer ) {
+            } else if (expectedValue instanceof Integer) {
                 return reader.nextInt();
             }
 
@@ -90,12 +86,12 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader
 
     static class StringVerifier extends LeafVerifier {
 
-        StringVerifier( String expected ) {
-            super( expected, JsonToken.STRING );
+        StringVerifier(String expected) {
+            super(expected, JsonToken.STRING);
         }
 
         @Override
-        Object getActualValue( JsonReader reader ) throws IOException {
+        Object getActualValue(JsonReader reader) throws IOException {
             return reader.nextString();
         }
     }
@@ -103,11 +99,11 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader
     static class EmptyVerifier extends LeafVerifier {
 
         EmptyVerifier() {
-            super( null, null );
+            super(null, null);
         }
 
         @Override
-        Object getActualValue( JsonReader reader ) throws IOException {
+        Object getActualValue(JsonReader reader) throws IOException {
             reader.beginArray();
             reader.nextNull();
             reader.endArray();
@@ -116,6 +112,75 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader
 
     }
 
+    static class ComplexAnyXmlVerifier extends LeafVerifier {
+
+        ComplexAnyXmlVerifier() {
+            super(null, JsonToken.BEGIN_OBJECT);
+        }
+
+        @Override
+        void verify(JsonReader reader, String keyName) throws IOException {
+
+            reader.beginObject();
+            String innerKey = reader.nextName();
+            assertEquals("Json reader child key for " + keyName, "data", innerKey);
+            assertEquals("Json token type for key " + innerKey, JsonToken.BEGIN_OBJECT, reader.peek());
+
+            reader.beginObject();
+            verifyLeaf(reader, innerKey, "leaf1", "leaf1-value");
+            verifyLeaf(reader, innerKey, "leaf2", "leaf2-value");
+
+            String nextName = reader.nextName();
+            assertEquals("Json reader child key for " + innerKey, "leaf-list", nextName);
+            reader.beginArray();
+            assertEquals("Json value for key " + nextName, "leaf-list-value1", reader.nextString());
+            assertEquals("Json value for key " + nextName, "leaf-list-value2", reader.nextString());
+            reader.endArray();
+
+            nextName = reader.nextName();
+            assertEquals("Json reader child key for " + innerKey, "list", nextName);
+            reader.beginArray();
+            verifyNestedLists(reader, 1);
+            verifyNestedLists(reader, 3);
+            reader.endArray();
+
+            reader.endObject();
+            reader.endObject();
+        }
+
+        void verifyNestedLists(JsonReader reader, int leafNum) throws IOException {
+            reader.beginObject();
+
+            String nextName = reader.nextName();
+            assertEquals("Json reader next name", "nested-list", nextName);
+
+            reader.beginArray();
+
+            reader.beginObject();
+            verifyLeaf(reader, "nested-list", "nested-leaf", "nested-value" + leafNum++);
+            reader.endObject();
+
+            reader.beginObject();
+            verifyLeaf(reader, "nested-list", "nested-leaf", "nested-value" + leafNum);
+            reader.endObject();
+
+            reader.endArray();
+            reader.endObject();
+        }
+
+        void verifyLeaf(JsonReader reader, String parent, String name, String value) throws IOException {
+            String nextName = reader.nextName();
+            assertEquals("Json reader child key for " + parent, name, nextName);
+            assertEquals("Json token type for key " + parent, JsonToken.STRING, reader.peek());
+            assertEquals("Json value for key " + nextName, value, reader.nextString());
+        }
+
+        @Override
+        Object getActualValue(JsonReader reader) throws IOException {
+            return null;
+        }
+    }
+
     @BeforeClass
     public static void initialize() {
         dataLoad("/cnsn-to-json/simple-data-types");
@@ -130,7 +195,7 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader
         TestUtils.normalizeCompositeNode(compositeNode, modules, "simple-data-types:cont");
 
         String jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(compositeNode, modules, dataSchemaNode,
-                    StructuredDataToJsonProvider.INSTANCE);
+                StructuredDataToJsonProvider.INSTANCE);
 
         assertNotNull(jsonOutput);
 
@@ -167,65 +232,68 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader
     private void jsonReadContElements(JsonReader jReader) throws IOException {
         jReader.beginObject();
 
-        Map<String,LeafVerifier> expectedMap = Maps.newHashMap();
-        expectedMap.put( "lfnint8Min", new NumberVerifier( Integer.valueOf( -128 ) ) );
-        expectedMap.put( "lfnint8Max", new NumberVerifier( Integer.valueOf( 127 ) ) );
-        expectedMap.put( "lfnint16Min", new NumberVerifier( Integer.valueOf( -32768 ) ) );
-        expectedMap.put( "lfnint16Max", new NumberVerifier( Integer.valueOf( 32767 ) ) );
-        expectedMap.put( "lfnint32Min", new NumberVerifier( Integer.valueOf( -2147483648 ) ) );
-        expectedMap.put( "lfnint32Max", new NumberVerifier( Long.valueOf( 2147483647 ) ) );
-        expectedMap.put( "lfnint64Min", new NumberVerifier( Long.valueOf( -9223372036854775808L ) ) );
-        expectedMap.put( "lfnint64Max", new NumberVerifier( Long.valueOf( 9223372036854775807L ) ) );
-        expectedMap.put( "lfnuint8Max", new NumberVerifier( Integer.valueOf( 255 ) ) );
-        expectedMap.put( "lfnuint16Max", new NumberVerifier( Integer.valueOf( 65535 ) ) );
-        expectedMap.put( "lfnuint32Max", new NumberVerifier( Long.valueOf( 4294967295L ) ) );
-        expectedMap.put( "lfstr", new StringVerifier( "lfstr" ) );
-        expectedMap.put( "lfstr1", new StringVerifier( "" ) );
-        expectedMap.put( "lfbool1", new BooleanVerifier( true ) );
-        expectedMap.put( "lfbool2", new BooleanVerifier( false ) );
-        expectedMap.put( "lfbool3", new BooleanVerifier( false ) );
-        expectedMap.put( "lfdecimal1", new NumberVerifier( new Double( 43.32 ) ) );
-        expectedMap.put( "lfdecimal2", new NumberVerifier( new Double( -0.43 ) ) );
-        expectedMap.put( "lfdecimal3", new NumberVerifier( new Double( 43 ) ) );
-        expectedMap.put( "lfdecimal4", new NumberVerifier( new Double( 43E3 ) ) );
-        expectedMap.put( "lfdecimal6", new NumberVerifier( new Double( 33.12345 ) ) );
-        expectedMap.put( "lfenum", new StringVerifier( "enum3" ) );
-        expectedMap.put( "lfbits", new StringVerifier( "bit3 bit2" ) );
-        expectedMap.put( "lfbinary", new StringVerifier( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" ) );
-        expectedMap.put( "lfunion1", new StringVerifier( "324" ) );
-        expectedMap.put( "lfunion2", new StringVerifier( "33.3" ) );
-        expectedMap.put( "lfunion3", new StringVerifier( "55" ) );
-        expectedMap.put( "lfunion4", new StringVerifier( "true" ) );
-        expectedMap.put( "lfunion5", new StringVerifier( "true" ) );
-        expectedMap.put( "lfunion6", new StringVerifier( "10" ) );
-        expectedMap.put( "lfunion7", new StringVerifier( "" ) );
-        expectedMap.put( "lfunion8", new StringVerifier( "" ) );
-        expectedMap.put( "lfunion9", new StringVerifier( "" ) );
-        expectedMap.put( "lfunion10", new StringVerifier( "bt1" ) );
-        expectedMap.put( "lfunion11", new StringVerifier( "33" ) );
-        expectedMap.put( "lfunion12", new StringVerifier( "false" ) );
-        expectedMap.put( "lfunion13", new StringVerifier( "b1" ) );
-        expectedMap.put( "lfunion14", new StringVerifier( "zero" ) );
-        expectedMap.put( "lfempty", new EmptyVerifier() );
-        expectedMap.put( "identityref1", new StringVerifier( "simple-data-types:iden" ) );
+        Map<String, LeafVerifier> expectedMap = Maps.newHashMap();
+        expectedMap.put("lfnint8Min", new NumberVerifier(Integer.valueOf(-128)));
+        expectedMap.put("lfnint8Max", new NumberVerifier(Integer.valueOf(127)));
+        expectedMap.put("lfnint16Min", new NumberVerifier(Integer.valueOf(-32768)));
+        expectedMap.put("lfnint16Max", new NumberVerifier(Integer.valueOf(32767)));
+        expectedMap.put("lfnint32Min", new NumberVerifier(Integer.valueOf(-2147483648)));
+        expectedMap.put("lfnint32Max", new NumberVerifier(Long.valueOf(2147483647)));
+        expectedMap.put("lfnint64Min", new NumberVerifier(Long.valueOf(-9223372036854775808L)));
+        expectedMap.put("lfnint64Max", new NumberVerifier(Long.valueOf(9223372036854775807L)));
+        expectedMap.put("lfnuint8Max", new NumberVerifier(Integer.valueOf(255)));
+        expectedMap.put("lfnuint16Max", new NumberVerifier(Integer.valueOf(65535)));
+        expectedMap.put("lfnuint32Max", new NumberVerifier(Long.valueOf(4294967295L)));
+        expectedMap.put("lfstr", new StringVerifier("lfstr"));
+        expectedMap.put("lfstr1", new StringVerifier(""));
+        expectedMap.put("lfbool1", new BooleanVerifier(true));
+        expectedMap.put("lfbool2", new BooleanVerifier(false));
+        expectedMap.put("lfbool3", new BooleanVerifier(false));
+        expectedMap.put("lfdecimal1", new NumberVerifier(new Double(43.32)));
+        expectedMap.put("lfdecimal2", new NumberVerifier(new Double(-0.43)));
+        expectedMap.put("lfdecimal3", new NumberVerifier(new Double(43)));
+        expectedMap.put("lfdecimal4", new NumberVerifier(new Double(43E3)));
+        expectedMap.put("lfdecimal6", new NumberVerifier(new Double(33.12345)));
+        expectedMap.put("lfenum", new StringVerifier("enum3"));
+        expectedMap.put("lfbits", new StringVerifier("bit3 bit2"));
+        expectedMap.put("lfbinary", new StringVerifier("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"));
+        expectedMap.put("lfunion1", new StringVerifier("324"));
+        expectedMap.put("lfunion2", new StringVerifier("33.3"));
+        expectedMap.put("lfunion3", new StringVerifier("55"));
+        expectedMap.put("lfunion4", new StringVerifier("true"));
+        expectedMap.put("lfunion5", new StringVerifier("true"));
+        expectedMap.put("lfunion6", new StringVerifier("10"));
+        expectedMap.put("lfunion7", new StringVerifier(""));
+        expectedMap.put("lfunion8", new StringVerifier(""));
+        expectedMap.put("lfunion9", new StringVerifier(""));
+        expectedMap.put("lfunion10", new StringVerifier("bt1"));
+        expectedMap.put("lfunion11", new StringVerifier("33"));
+        expectedMap.put("lfunion12", new StringVerifier("false"));
+        expectedMap.put("lfunion13", new StringVerifier("b1"));
+        expectedMap.put("lfunion14", new StringVerifier("zero"));
+        expectedMap.put("lfempty", new EmptyVerifier());
+        expectedMap.put("identityref1", new StringVerifier("simple-data-types:iden"));
+        expectedMap.put("complex-any", new ComplexAnyXmlVerifier());
+        expectedMap.put("simple-any", new StringVerifier("simple"));
+        expectedMap.put("empty-any", new StringVerifier(""));
 
         while (jReader.hasNext()) {
             String keyName = jReader.nextName();
             JsonToken peek = jReader.peek();
 
-            LeafVerifier verifier = expectedMap.remove( keyName );
-            assertNotNull( "Found unexpected leaf: " + keyName , verifier );
+            LeafVerifier verifier = expectedMap.remove(keyName);
+            assertNotNull("Found unexpected leaf: " + keyName, verifier);
 
             JsonToken expToken = verifier.expectedTokenType();
-            if( expToken != null ) {
-                assertEquals( "Json token type for key " + keyName, expToken, peek );
+            if (expToken != null) {
+                assertEquals("Json token type for key " + keyName, expToken, peek);
             }
 
-            verifier.verify( jReader, keyName );
+            verifier.verify(jReader, keyName);
         }
 
-        if( !expectedMap.isEmpty() ) {
-            fail( "Missing leaf nodes in Json output: " +expectedMap.keySet() );
+        if (!expectedMap.isEmpty()) {
+            fail("Missing leaf nodes in Json output: " + expectedMap.keySet());
         }
 
         jReader.endObject();
@@ -235,15 +303,13 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader
     public void testBadData() throws Exception {
 
         try {
-            CompositeNode compositeNode = TestUtils.readInputToCnSn(
-                                               "/cnsn-to-json/simple-data-types/xml/bad-data.xml",
-                                               XmlToCompositeNodeProvider.INSTANCE);
+            CompositeNode compositeNode = TestUtils.readInputToCnSn("/cnsn-to-json/simple-data-types/xml/bad-data.xml",
+                    XmlToCompositeNodeProvider.INSTANCE);
 
             TestUtils.normalizeCompositeNode(compositeNode, modules, "simple-data-types:cont");
-            fail( "Expected RestconfDocumentedException" );
-        }
-        catch( RestconfDocumentedException e ) {
-            assertEquals( "getErrorTag", ErrorTag.INVALID_VALUE, e.getErrors().get( 0 ).getErrorTag() );
+            fail("Expected RestconfDocumentedException");
+        } catch (RestconfDocumentedException e) {
+            assertEquals("getErrorTag", ErrorTag.INVALID_VALUE, e.getErrors().get(0).getErrorTag());
         }
     }
 }
index fdd3aa6684303babcabc9c849792e37c6cbf758e..506ca847a936c4abc006c099b02f970a6022fe36 100644 (file)
@@ -13,9 +13,7 @@ import static org.junit.Assert.assertTrue;
 import java.io.IOException;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
-
 import javax.ws.rs.WebApplicationException;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
@@ -74,14 +72,16 @@ public class CnSnToJsonIdentityrefTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     private CompositeNode prepareCompositeNode(final Object value) {
-        MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont","identityref:module","2013-12-2"), null, null,
-                ModifyAction.CREATE, null);
-        MutableCompositeNode cont1 = NodeFactory.createMutableCompositeNode(TestUtils.buildQName("cont1","identityref:module","2013-12-2"), cont, null,
-                ModifyAction.CREATE, null);
+        MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(
+                TestUtils.buildQName("cont", "identityref:module", "2013-12-2"), null, null, ModifyAction.CREATE, null);
+        MutableCompositeNode cont1 = NodeFactory
+                .createMutableCompositeNode(TestUtils.buildQName("cont1", "identityref:module", "2013-12-2"), cont,
+                        null, ModifyAction.CREATE, null);
         cont.getValue().add(cont1);
 
-        MutableSimpleNode<?> lf1 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf1","identityref:module","2013-12-2"), cont1, value,
-                ModifyAction.CREATE, null);
+        MutableSimpleNode<?> lf1 = NodeFactory
+                .createMutableSimpleNode(TestUtils.buildQName("lf1", "identityref:module", "2013-12-2"), cont1, value,
+                        ModifyAction.CREATE, null);
 
         cont1.getValue().add(lf1);
         cont1.init();
index 050a9925ff3f7f767af0c371ef651d2d3e0ba7a5..50c834b1ffee46f96787d73ac47c9f6e49d6ffd4 100644 (file)
@@ -12,10 +12,8 @@ import static org.junit.Assert.assertTrue;
 import java.io.IOException;
 import java.util.List;
 import java.util.Set;
-
 import javax.activation.UnsupportedDataTypeException;
 import javax.ws.rs.WebApplicationException;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
@@ -147,7 +145,8 @@ public class CnSnToJsonIncorrectTopLevelTest extends YangAndXmlAndDataSchemaLoad
     @Test
     public void incorrectTopLevelElementTest() {
 
-        CompositeNode compositeNode = TestUtils.readInputToCnSn("/cnsn-to-json/simple-data-types/xml/data.xml", XmlToCompositeNodeProvider.INSTANCE);
+        CompositeNode compositeNode = TestUtils.readInputToCnSn("/cnsn-to-json/simple-data-types/xml/data.xml",
+                XmlToCompositeNodeProvider.INSTANCE);
         DataSchemaNode incorrectDataSchema = null;
         incorrectDataSchema = new IncorrectDataSchema();
 
index 21a46a6cc32b60de0e3db3c9c74e71c96e5385ec..6e41dcb57769b6fd633edb2bea9ea0ede1c9014a 100644 (file)
@@ -13,9 +13,7 @@ import static org.junit.Assert.assertTrue;
 import java.io.IOException;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
-
 import javax.ws.rs.WebApplicationException;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
@@ -50,8 +48,8 @@ public class CnSnToJsonLeafrefType extends YangAndXmlAndDataSchemaLoader {
     }
 
     /**
-     * Tests case when reference to not existing element is present. In this
-     * case value from single node is printed as string.
+     * Tests case when reference to not existing element is present. In this case value from single node is printed as
+     * string.
      */
     @Test
     public void leafrefToNonExistingLeafTest() {
@@ -60,8 +58,7 @@ public class CnSnToJsonLeafrefType extends YangAndXmlAndDataSchemaLoader {
     }
 
     /**
-     * Tests case when non leaf element is referenced. In this case value from
-     * single node is printed as string.
+     * Tests case when non leaf element is referenced. In this case value from single node is printed as string.
      */
     @Test
     public void leafrefToNotLeafTest() {
index 24dba17c90cdff4e9a87d0a059160357dcbaad88..3ca29c8d65cd485002ef8b46ad7b675d4a4bc581 100644 (file)
@@ -9,6 +9,7 @@ package org.opendaylight.controller.sal.restconf.impl.cnsn.to.json.test;
 
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
+import static org.opendaylight.controller.sal.restconf.impl.test.TestUtils.containsStringData;
 
 import java.io.IOException;
 import java.util.Collections;
@@ -45,12 +46,12 @@ public class CnSnToJsonNotExistingLeafTypeTest extends YangAndXmlAndDataSchemaLo
     @Test
     public void incorrectTopLevelElementTest() throws WebApplicationException, IOException {
         String jsonOutput = null;
-        jsonOutput = TestUtils
-                .writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(),
-                        Collections.<Module>emptySet(), prepareDataSchemaNode(),
-                        StructuredDataToJsonProvider.INSTANCE);
+        jsonOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(),
+                Collections.<Module> emptySet(), prepareDataSchemaNode(), StructuredDataToJsonProvider.INSTANCE);
         assertNotNull(jsonOutput);
-        assertTrue(jsonOutput.contains("\"lf1\": \"\""));
+
+        // pattern for e.g. > "lf1" : "" < or >"lf1":""<
+        assertTrue(containsStringData(jsonOutput, "\"lf1\"", ":", "\"\""));
     }
 
     private CompositeNode prepareCompositeNode() {
index e116129bf7cc63736760688234b1f7665dcf9533..eb6a5b9e00f7c7af65d2398bd2e21e87f650fe9f 100644 (file)
@@ -9,11 +9,10 @@ package org.opendaylight.controller.sal.restconf.impl.cnsn.to.json.test;
 
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
+import static org.opendaylight.controller.sal.restconf.impl.test.TestUtils.containsStringData;
 
 import java.io.IOException;
-
 import javax.ws.rs.WebApplicationException;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
@@ -30,8 +29,7 @@ public class CnSnToJsonWithAugmentTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     /**
-     * Test of json output when as input are specified composite node with empty
-     * data + YANG file
+     * Test of json output when as input are specified composite node with empty data + YANG file
      */
     @Test
     public void augmentedElementsToJson() {
@@ -47,12 +45,12 @@ public class CnSnToJsonWithAugmentTest extends YangAndXmlAndDataSchemaLoader {
         }
         assertNotNull(jsonOutput);
 
-        assertTrue(jsonOutput.contains("\"augment-leaf:lf2\": \"lf2\""));
-        assertTrue(jsonOutput.contains("\"augment-container:cont1\": {"));
-        assertTrue(jsonOutput.contains("\"augment-container:lf11\": \"lf11\""));
-        assertTrue(jsonOutput.contains("\"augment-list:lst1\": ["));
-        assertTrue(jsonOutput.contains("\"augment-list:lf11\": \"lf1_1\""));
-        assertTrue(jsonOutput.contains("\"augment-list:lf11\": \"lf1_2\""));
-        assertTrue(jsonOutput.contains("\"augment-leaflist:lflst1\": ["));
+        assertTrue(containsStringData(jsonOutput, "\"augment-leaf:lf2\"", ":", "\"lf2\""));
+        assertTrue(containsStringData(jsonOutput, "\"augment-container:cont1\"", ":", "\\{"));
+        assertTrue(containsStringData(jsonOutput, "\"augment-container:lf11\"", ":", "\"lf11\""));
+        assertTrue(containsStringData(jsonOutput, "\"augment-list:lst1\"", ":", "\\["));
+        assertTrue(containsStringData(jsonOutput, "\"augment-list:lf11\"", ":", "\"lf1_1\""));
+        assertTrue(containsStringData(jsonOutput, "\"augment-list:lf11\"", ":", "\"lf1_2\""));
+        assertTrue(containsStringData(jsonOutput, "\"augment-leaflist:lflst1\"", ":", "\\["));
     }
 }
index 052bb1a2be762ffca684a54109f724bd4d188ce9..a84fc79b86fbc9bb1d028859b629aeb1ecbfe622 100644 (file)
@@ -13,9 +13,7 @@ import java.io.IOException;
 import java.net.URISyntaxException;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
-
 import javax.ws.rs.WebApplicationException;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
index 086e648097294354cb8a34baca155581397dad15..3ab880fe7e19a5eb156608e8c34435819ad6c568 100644 (file)
@@ -12,9 +12,7 @@ import static org.junit.Assert.assertNotNull;
 import java.io.IOException;
 import java.net.URI;
 import java.net.URISyntaxException;
-
 import javax.ws.rs.WebApplicationException;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
@@ -26,9 +24,8 @@ import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 
 /**
  *
- * CnSn = Composite node and Simple node data structure Class contains test of
- * serializing simple nodes data values according data types from YANG schema to
- * XML file
+ * CnSn = Composite node and Simple node data structure Class contains test of serializing simple nodes data values
+ * according data types from YANG schema to XML file
  *
  */
 public class CnSnInstanceIdentifierToXmlTest extends YangAndXmlAndDataSchemaLoader {
@@ -40,7 +37,7 @@ public class CnSnInstanceIdentifierToXmlTest extends YangAndXmlAndDataSchemaLoad
 
     @Test
     public void snAsYangInstanceIdentifier() throws WebApplicationException, IOException, URISyntaxException {
-        CompositeNode cnSnData = prepareCnStructForYangData( );
+        CompositeNode cnSnData = prepareCnStructForYangData();
         String xmlOutput = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSnData, modules, dataSchemaNode,
                 StructuredDataToXmlProvider.INSTANCE);
         assertNotNull(xmlOutput);
index 2ada6e13e9a64c2e62101f693027e3686645d025..800e2d3b486998e0993a136a0e7b0a1de6551c4c 100644 (file)
@@ -11,9 +11,7 @@ import static org.junit.Assert.assertTrue;
 
 import java.io.IOException;
 import java.util.Collections;
-
 import javax.ws.rs.WebApplicationException;
-
 import org.junit.Ignore;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
@@ -41,8 +39,8 @@ public class CnSnToXmlNotExistingLeafTypeTest {
 
         boolean nullPointerExceptionRaised = false;
         try {
-            TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(),
-                    Collections.<Module>emptySet(), prepareDataSchemaNode(), StructuredDataToXmlProvider.INSTANCE);
+            TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCompositeNode(), Collections.<Module> emptySet(),
+                    prepareDataSchemaNode(), StructuredDataToXmlProvider.INSTANCE);
         } catch (WebApplicationException | IOException e) {
             LOG.error("WebApplicationException or IOException was raised");
         } catch (NullPointerException e) {
index 9318af529b74c6ec4097331f6e374b7aa7038e9b..3d5fee3ab8aff5ef3adfde3dbbcdc91a9a13923e 100644 (file)
@@ -12,12 +12,12 @@ import static org.junit.Assert.assertTrue;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
+import com.google.common.base.Optional;
+import com.google.common.collect.Lists;
 import java.io.IOException;
 import java.util.List;
-
 import javax.ws.rs.WebApplicationException;
 import javax.xml.transform.TransformerFactoryConfigurationError;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
@@ -50,14 +50,10 @@ import org.opendaylight.yangtools.yang.model.util.Uint64;
 import org.opendaylight.yangtools.yang.model.util.Uint8;
 import org.opendaylight.yangtools.yang.model.util.UnionType;
 
-import com.google.common.base.Optional;
-import com.google.common.collect.Lists;
-
 /**
  *
- * CnSn = Composite node and Simple node data structure Class contains test of
- * serializing simple nodes data values according data types from YANG schema to
- * XML file
+ * CnSn = Composite node and Simple node data structure Class contains test of serializing simple nodes data values
+ * according data types from YANG schema to XML file
  *
  */
 public class CnSnToXmlTest extends YangAndXmlAndDataSchemaLoader {
@@ -87,76 +83,77 @@ public class CnSnToXmlTest extends YangAndXmlAndDataSchemaLoader {
         serializeToXml(prepareLeafrefData(), "<lfBoolean>true</lfBoolean>", "<lfLfref>true</lfLfref>");
     }
 
-
     @Test
     public void snAsYangStringToXmlTest() {
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(StringType.getInstance()).deserialize("lfStr value"),
-                        "lfStr"), "<lfStr>lfStr value</lfStr>");
+                prepareCnStructForYangData(
+                        TypeDefinitionAwareCodec.from(StringType.getInstance()).deserialize("lfStr value"), "lfStr"),
+                "<lfStr>lfStr value</lfStr>");
     }
 
     @Test
     public void snAsYangInt8ToXmlTest() {
         String elName = "lfInt8";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int8.getInstance()).deserialize("14"), elName), "<"
-                        + elName + ">14</" + elName + ">");
+                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int8.getInstance()).deserialize("14"), elName),
+                "<" + elName + ">14</" + elName + ">");
     }
 
     @Test
     public void snAsYangInt16ToXmlTest() {
         String elName = "lfInt16";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int16.getInstance()).deserialize("3000"), elName),
-                "<" + elName + ">3000</" + elName + ">");
+                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int16.getInstance()).deserialize("3000"),
+                        elName), "<" + elName + ">3000</" + elName + ">");
     }
 
     @Test
     public void snAsYangInt32ToXmlTest() {
         String elName = "lfInt32";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int32.getInstance()).deserialize("201234"), elName),
-                "<" + elName + ">201234</" + elName + ">");
+                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int32.getInstance()).deserialize("201234"),
+                        elName), "<" + elName + ">201234</" + elName + ">");
     }
 
     @Test
     public void snAsYangInt64ToXmlTest() {
         String elName = "lfInt64";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Int64.getInstance()).deserialize("5123456789"),
-                        elName), "<" + elName + ">5123456789</" + elName + ">");
+                prepareCnStructForYangData(
+                        TypeDefinitionAwareCodec.from(Int64.getInstance()).deserialize("5123456789"), elName), "<"
+                        + elName + ">5123456789</" + elName + ">");
     }
 
     @Test
     public void snAsYangUint8ToXmlTest() {
         String elName = "lfUint8";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint8.getInstance()).deserialize("200"), elName),
-                "<" + elName + ">200</" + elName + ">");
+                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint8.getInstance()).deserialize("200"),
+                        elName), "<" + elName + ">200</" + elName + ">");
     }
 
     @Test
     public void snAsYangUint16ToXmlTest() {
         String elName = "lfUint16";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint16.getInstance()).deserialize("4000"), elName),
-                "<" + elName + ">4000</" + elName + ">");
+                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint16.getInstance()).deserialize("4000"),
+                        elName), "<" + elName + ">4000</" + elName + ">");
     }
 
     @Test
     public void snAsYangUint32ToXmlTest() {
         String elName = "lfUint32";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint32.getInstance()).deserialize("4123456789"),
-                        elName), "<" + elName + ">4123456789</" + elName + ">");
+                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint32.getInstance())
+                        .deserialize("4123456789"), elName), "<" + elName + ">4123456789</" + elName + ">");
     }
 
     @Test
     public void snAsYangUint64ToXmlTest() {
         String elName = "lfUint64";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint64.getInstance()).deserialize("5123456789"),
-                        elName), "<" + elName + ">5123456789</" + elName + ">");
+                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(Uint64.getInstance())
+                        .deserialize("5123456789"), elName), "<" + elName + ">5123456789</" + elName + ">");
     }
 
     @Test
@@ -164,92 +161,87 @@ public class CnSnToXmlTest extends YangAndXmlAndDataSchemaLoader {
         String elName = "lfBinary";
         serializeToXml(
                 prepareCnStructForYangData(
-                        TypeDefinitionAwareCodec.from(BinaryType.getInstance())
-                        .deserialize("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567"),
-                        elName), "<" + elName + ">ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567</"
-                                + elName + ">");
+                        TypeDefinitionAwareCodec.from(BinaryType.getInstance()).deserialize(
+                                "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567"), elName), "<" + elName
+                        + ">ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567</" + elName + ">");
     }
 
     @Test
     public void snAsYangBitsToXmlTest() {
-        BitsTypeDefinition.Bit mockBit1 = mock( BitsTypeDefinition.Bit.class );
-        when( mockBit1.getName() ).thenReturn( "one" );
-        BitsTypeDefinition.Bit mockBit2 = mock( BitsTypeDefinition.Bit.class );
-        when( mockBit2.getName() ).thenReturn( "two" );
-        List<BitsTypeDefinition.Bit> bitList = Lists.newArrayList( mockBit1, mockBit2 );
+        BitsTypeDefinition.Bit mockBit1 = mock(BitsTypeDefinition.Bit.class);
+        when(mockBit1.getName()).thenReturn("one");
+        BitsTypeDefinition.Bit mockBit2 = mock(BitsTypeDefinition.Bit.class);
+        when(mockBit2.getName()).thenReturn("two");
+        List<BitsTypeDefinition.Bit> bitList = Lists.newArrayList(mockBit1, mockBit2);
 
         String elName = "lfBits";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(
-                        BitsType.create( mock( SchemaPath.class ), bitList ) )
-                        .deserialize("one two"), elName),
-                        "<" + elName + ">one two</" + elName + ">", "<" + elName + ">two one</" + elName + ">");
+                prepareCnStructForYangData(
+                        TypeDefinitionAwareCodec.from(BitsType.create(mock(SchemaPath.class), bitList)).deserialize(
+                                "one two"), elName), "<" + elName + ">one two</" + elName + ">", "<" + elName
+                        + ">two one</" + elName + ">");
     }
 
     @Test
     public void snAsYangEnumerationToXmlTest() {
-        EnumTypeDefinition.EnumPair mockEnum = mock( EnumTypeDefinition.EnumPair.class );
-        when( mockEnum.getName() ).thenReturn( "enum2" );
-        List<EnumPair> enumList = Lists.newArrayList( mockEnum );
+        EnumTypeDefinition.EnumPair mockEnum = mock(EnumTypeDefinition.EnumPair.class);
+        when(mockEnum.getName()).thenReturn("enum2");
+        List<EnumPair> enumList = Lists.newArrayList(mockEnum);
 
         String elName = "lfEnumeration";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(
-                        EnumerationType.create( mock( SchemaPath.class ), enumList,
-                                Optional.<EnumTypeDefinition.EnumPair>absent() ) )
-                                .deserialize("enum2"),
-                                elName), "<" + elName + ">enum2</" + elName + ">");
+                prepareCnStructForYangData(
+                        TypeDefinitionAwareCodec.from(
+                                EnumerationType.create(mock(SchemaPath.class), enumList,
+                                        Optional.<EnumTypeDefinition.EnumPair> absent())).deserialize("enum2"), elName),
+                "<" + elName + ">enum2</" + elName + ">");
     }
 
     @Test
     public void snAsYangEmptyToXmlTest() {
         String elName = "lfEmpty";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(EmptyType.getInstance()).deserialize(null), elName), "<"
-                        + elName + "/>");
+                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(EmptyType.getInstance()).deserialize(null),
+                        elName), "<" + elName + "/>");
     }
 
     @Test
     public void snAsYangBooleanToXmlTest() {
         String elName = "lfBoolean";
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(BooleanType.getInstance()).deserialize("str"), elName),
-                "<" + elName + ">false</" + elName + ">");
+                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(BooleanType.getInstance()).deserialize("str"),
+                        elName), "<" + elName + ">false</" + elName + ">");
         serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(BooleanType.getInstance()).deserialize("true"), elName),
-                "<" + elName + ">true</" + elName + ">");
+                prepareCnStructForYangData(
+                        TypeDefinitionAwareCodec.from(BooleanType.getInstance()).deserialize("true"), elName), "<"
+                        + elName + ">true</" + elName + ">");
     }
 
     @Test
     public void snAsYangUnionToXmlTest() {
 
-        BitsTypeDefinition.Bit mockBit1 = mock( BitsTypeDefinition.Bit.class );
-        when( mockBit1.getName() ).thenReturn( "first" );
-        BitsTypeDefinition.Bit mockBit2 = mock( BitsTypeDefinition.Bit.class );
-        when( mockBit1.getName() ).thenReturn( "second" );
-        List<BitsTypeDefinition.Bit> bitList = Lists.newArrayList( mockBit1, mockBit2 );
+        BitsTypeDefinition.Bit mockBit1 = mock(BitsTypeDefinition.Bit.class);
+        when(mockBit1.getName()).thenReturn("first");
+        BitsTypeDefinition.Bit mockBit2 = mock(BitsTypeDefinition.Bit.class);
+        when(mockBit2.getName()).thenReturn("second");
+        List<BitsTypeDefinition.Bit> bitList = Lists.newArrayList(mockBit1, mockBit2);
 
-        List<TypeDefinition<?>> types = Lists.<TypeDefinition<?>>newArrayList(
-                Int8.getInstance(),
-                BitsType.create( mock( SchemaPath.class ) , bitList ),
-                BooleanType.getInstance() );
-        UnionType unionType = UnionType.create( types );
+        List<TypeDefinition<?>> types = Lists.<TypeDefinition<?>> newArrayList(Int8.getInstance(),
+                BitsType.create(mock(SchemaPath.class), bitList), BooleanType.getInstance());
+        UnionType unionType = UnionType.create(types);
 
         String elName = "lfUnion";
         String int8 = "15";
-        serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(int8), elName), "<"
-                        + elName + ">15</" + elName + ">");
+        serializeToXml(prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(int8), elName),
+                "<" + elName + ">15</" + elName + ">");
 
         String bits = "first second";
-        serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(bits), elName), "<"
-                        + elName + ">first second</" + elName + ">");
+        serializeToXml(prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(bits), elName),
+                "<" + elName + ">first second</" + elName + ">");
 
         String bool = "str";
-        serializeToXml(
-                prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(bool), elName), "<"
-                        + elName + ">str</" + elName + ">");
+        serializeToXml(prepareCnStructForYangData(TypeDefinitionAwareCodec.from(unionType).deserialize(bool), elName),
+                "<" + elName + ">str</" + elName + ">");
     }
 
     private void serializeToXml(final CompositeNode compositeNode, final String... xmlRepresentation)
index ac7fe20818f31fc7fbb5bfd24b4399b2113cadee..8e5449029c78dccaba89861feb71e018d22c6ab2 100644 (file)
@@ -10,9 +10,7 @@ package org.opendaylight.controller.sal.restconf.impl.cnsn.to.xml.test;
 import static org.junit.Assert.assertTrue;
 
 import java.io.IOException;
-
 import javax.ws.rs.WebApplicationException;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
@@ -26,9 +24,8 @@ import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
 
 /**
  *
- * CnSn = Composite node and Simple node data structure Class contains test of
- * serializing simple nodes data values according data types from YANG schema to
- * XML file
+ * CnSn = Composite node and Simple node data structure Class contains test of serializing simple nodes data values
+ * according data types from YANG schema to XML file
  *
  */
 public class CnSnToXmlWithChoiceTest extends YangAndXmlAndDataSchemaLoader {
index f8d04c157f2e9d1678da36c6636bd872e05e4cc7..1e366dcaec88dd5171a191581a6877409afc696a 100644 (file)
@@ -14,9 +14,7 @@ import java.net.URI;
 import java.net.URISyntaxException;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
-
 import javax.ws.rs.WebApplicationException;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
@@ -31,7 +29,7 @@ public class CnSnToXmlWithDataFromSeveralModulesTest extends YangAndXmlAndDataSc
 
     @BeforeClass
     public static void initialize() {
-        dataLoad("/xml-to-cnsn/data-of-several-modules/yang",2,"module1","cont_m1");
+        dataLoad("/xml-to-cnsn/data-of-several-modules/yang", 2, "module1", "cont_m1");
     }
 
     @Test
@@ -40,19 +38,19 @@ public class CnSnToXmlWithDataFromSeveralModulesTest extends YangAndXmlAndDataSc
         String output = TestUtils.writeCompNodeWithSchemaContextToOutput(prepareCnSn(), modules, schemaContext,
                 StructuredDataToXmlProvider.INSTANCE);
 
-//         String output =
-//         String.format("<data>" +
-//                  "\n<cont_m1>" +
-//                         "\n\t<lf1_m1>" +
-//                             "\n\t\tlf1 m1 value" +
-//                             "\n\t</lf1_m1>" +
-//                         "\n</cont_m1>" +
-//                         "\n<cont_m2>" +
-//                             "\n\t<lf1_m2>" +
-//                                 "\n\t\tlf1 m2 value" +
-//                             "\n\t</lf1_m2>" +
-//                         "\n</cont_m2>" +
-//                     "\n</data>");
+        // String output =
+        // String.format("<data>" +
+        // "\n<cont_m1>" +
+        // "\n\t<lf1_m1>" +
+        // "\n\t\tlf1 m1 value" +
+        // "\n\t</lf1_m1>" +
+        // "\n</cont_m1>" +
+        // "\n<cont_m2>" +
+        // "\n\t<lf1_m2>" +
+        // "\n\t\tlf1 m2 value" +
+        // "\n\t</lf1_m2>" +
+        // "\n</cont_m2>" +
+        // "\n</data>");
 
         StringBuilder regex = new StringBuilder();
         regex.append("^");
@@ -61,7 +59,6 @@ public class CnSnToXmlWithDataFromSeveralModulesTest extends YangAndXmlAndDataSc
         regex.append(".*xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\"");
         regex.append(".*>");
 
-
         regex.append(".*<contB_m1.*\\/>");
         regex.append(".*xmlns=\"module:one\"");
         regex.append(".*>");
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/input/to/cnsn/test/RestPutListDataTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/input/to/cnsn/test/RestPutListDataTest.java
new file mode 100644 (file)
index 0000000..f4281c0
--- /dev/null
@@ -0,0 +1,189 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.sal.restconf.impl.input.to.cnsn.test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.FileNotFoundException;
+import java.net.URI;
+import java.util.List;
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
+import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
+import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
+import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
+import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
+import org.opendaylight.controller.sal.restconf.impl.RestconfError;
+import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
+import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
+import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
+import org.opendaylight.controller.sal.restconf.impl.SimpleNodeWrapper;
+import org.opendaylight.controller.sal.restconf.impl.test.DummyFuture;
+import org.opendaylight.controller.sal.restconf.impl.test.DummyFuture.Builder;
+import org.opendaylight.controller.sal.restconf.impl.test.DummyRpcResult;
+import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
+import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+public class RestPutListDataTest {
+
+    private static BrokerFacade brokerFacade;
+    private static RestconfImpl restconfImpl;
+    private static SchemaContext schemaContextTestModule;
+
+    private static final String TEST_MODULE_NS_STRING = "test:module";
+    private static final URI TEST_MODULE_NS;
+    private static final String TEST_MODULE_REVISION = "2014-01-09";
+
+    static {
+        TEST_MODULE_NS = URI.create("test:module");
+    }
+
+    @Before
+    public void initialize() throws FileNotFoundException {
+        ControllerContext controllerContext = ControllerContext.getInstance();
+        schemaContextTestModule = TestUtils.loadSchemaContext("/full-versions/test-module");
+        controllerContext.setSchemas(schemaContextTestModule);
+        brokerFacade = mock(BrokerFacade.class);
+        restconfImpl = RestconfImpl.getInstance();
+        restconfImpl.setBroker(brokerFacade);
+        restconfImpl.setControllerContext(controllerContext);
+        Builder<TransactionStatus> futureBuilder = new DummyFuture.Builder<TransactionStatus>();
+        futureBuilder.rpcResult(new DummyRpcResult.Builder<TransactionStatus>().result(TransactionStatus.COMMITED)
+                .build());
+        when(brokerFacade.commitConfigurationDataPut(any(InstanceIdentifier.class), any(CompositeNode.class)))
+                .thenReturn(futureBuilder.build());
+    }
+
+    /**
+     * Tests whether no exception is raised if number and values of keys in URI
+     * and payload are equal
+     */
+    @Test
+    public void testValidKeys() {
+        putListDataTest("key1value", "15", "key1value", (short) 15);
+    }
+
+    /**
+     * Tests whether an exception is raised if key values in URI and payload are
+     * different.
+     *
+     * The exception should be raised from validation method
+     * {@code RestconfImpl#validateListEqualityOfListInDataAndUri}
+     */
+    @Test
+    public void testUriAndPayloadKeysDifferent() {
+        try {
+            putListDataTest("key1value", "15", "key1value", (short) 16);
+            fail("RestconfDocumentedException expected");
+        } catch (RestconfDocumentedException e) {
+            verifyException(e, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
+        }
+
+        try {
+            putListDataTest("key1value", "15", "key1value1", (short) 16);
+            fail("RestconfDocumentedException expected");
+        } catch (RestconfDocumentedException e) {
+            verifyException(e, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE);
+        }
+    }
+
+    /**
+     * Tests whether an exception is raised if URI contains less key values then
+     * payload.
+     *
+     * The exception is raised during {@code InstanceIdentifier} instance is
+     * built from URI
+     */
+    @Test
+    public void testMissingKeysInUri() {
+        try {
+            putListDataTest("key1value", null, "key1value", (short) 15);
+            fail("RestconfDocumentedException expected");
+        } catch (RestconfDocumentedException e) {
+            verifyException(e, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
+        }
+    }
+
+    /**
+     * Tests whether an exception is raised if URI contains more key values then
+     * payload.
+     *
+     * The exception should be raised from validation method
+     * {@code RestconfImpl#validateListEqualityOfListInDataAndUri}
+     */
+    @Test
+    public void testMissingKeysInPayload() {
+        try {
+            putListDataTest("key1value", "15", "key1value", null);
+            fail("RestconfDocumentedException expected");
+        } catch (RestconfDocumentedException e) {
+            verifyException(e, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
+        }
+        try {
+            putListDataWithWrapperTest("key1value", "15", "key1value", null);
+            fail("RestconfDocumentedException expected");
+        } catch (RestconfDocumentedException e) {
+            // this exception is raised from RestconfImpl.normalizeCompositeNode()
+            verifyException(e, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING);
+        }
+
+    }
+
+    private void verifyException(final RestconfDocumentedException e, final ErrorType errorType, final ErrorTag errorTag) {
+        List<RestconfError> errors = e.getErrors();
+        assertEquals("getErrors() size", 1, errors.size());
+        assertEquals("RestconfError getErrorType()", errorType, errors.get(0).getErrorType());
+        assertEquals("RestconfError getErrorTag()", errorTag, errors.get(0).getErrorTag());
+    }
+
+    public void putListDataTest(final String uriKey1, final String uriKey2, final String payloadKey1,
+            final Short payloadKey2) {
+        QName lstWithCompositeKey = QName.create(TEST_MODULE_NS_STRING, TEST_MODULE_REVISION, "lst-with-composite-key");
+        QName key1 = QName.create(TEST_MODULE_NS_STRING, TEST_MODULE_REVISION, "key1");
+        QName key2 = QName.create(TEST_MODULE_NS_STRING, TEST_MODULE_REVISION, "key2");
+
+        CompositeNodeBuilder<ImmutableCompositeNode> payloadBuilder = ImmutableCompositeNode.builder();
+        payloadBuilder.setQName(lstWithCompositeKey).addLeaf(key1, payloadKey1);
+        if (payloadKey2 != null) {
+            payloadBuilder.addLeaf(key2, payloadKey2);
+        }
+
+        restconfImpl.updateConfigurationData(toUri(uriKey1, uriKey2), payloadBuilder.toInstance());
+    }
+
+    public void putListDataWithWrapperTest(final String uriKey1, final String uriKey2, final String payloadKey1,
+            final Short payloadKey2) {
+        CompositeNodeWrapper payloadBuilder = new CompositeNodeWrapper(TEST_MODULE_NS, "lst-with-composite-key");
+        payloadBuilder.addValue(new SimpleNodeWrapper(TEST_MODULE_NS, "key1", payloadKey1));
+        if (payloadKey2 != null) {
+            payloadBuilder.addValue(new SimpleNodeWrapper(TEST_MODULE_NS, "key2", payloadKey2));
+        }
+        restconfImpl.updateConfigurationData(toUri(uriKey1, uriKey2), payloadBuilder);
+    }
+
+    private String toUri(final String uriKey1, final String uriKey2) {
+        final StringBuilder uriBuilder = new StringBuilder("/test-module:lst-with-composite-key/");
+        uriBuilder.append(uriKey1);
+        if (uriKey2 != null) {
+            uriBuilder.append("/");
+            uriBuilder.append(uriKey2);
+        }
+        return uriBuilder.toString();
+    }
+
+}
index 0c9e95173fd3f1e309b6e512a90260eaf8bbb899..23b040a9a3846b6e273dedcb0fcb42e8c36ff5f4 100644 (file)
@@ -12,7 +12,6 @@ import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 
 import java.util.List;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
index 79dd026fd0dc5cf21b69d7dae886070b009a5999..913e9f2d707bd310feb103313d53d5c8a83928df 100644 (file)
@@ -28,8 +28,7 @@ public class JsonLeafrefToCnSnTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     /**
-     * JSON values which represents leafref are always loaded to simple node as
-     * string
+     * JSON values which represents leafref are always loaded to simple node as string
      */
     @Test
     public void jsonIdentityrefToCompositeNode() {
index 47e329cc3ef11a4cdfc8842c9a1285a445989517..7b71e42ab8ed669516c4e724231628c8d6bd4908 100644 (file)
@@ -17,7 +17,6 @@ import java.io.InputStream;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
-
 import org.junit.Ignore;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
@@ -82,8 +81,8 @@ public class JsonToCnSnTest {
     }
 
     /**
-     * List contains 4 items and in every item are other elements. It is
-     * supposed that there should be: lf11, lflst11, cont11, lst11
+     * List contains 4 items and in every item are other elements. It is supposed that there should be: lf11, lflst11,
+     * cont11, lst11
      */
     @Test
     public void multipleItemsInListTest() {
@@ -116,14 +115,19 @@ public class JsonToCnSnTest {
     public void incorrectTopLevelElementsTest() {
         RestconfDocumentedException cause1 = null;
         try {
-            TestUtils.readInputToCnSn("/json-to-cnsn/wrong-top-level1.json", true, JsonToCompositeNodeProvider.INSTANCE);
+            TestUtils
+                    .readInputToCnSn("/json-to-cnsn/wrong-top-level1.json", true, JsonToCompositeNodeProvider.INSTANCE);
         } catch (RestconfDocumentedException e) {
             cause1 = e;
         }
 
         assertNotNull(cause1);
-        assertTrue(cause1.getErrors().get( 0 ).getErrorMessage().contains(
-            "First element in Json Object has to be \"Object\" or \"Array with one Object element\". Other scenarios are not supported yet."));
+        assertTrue(cause1
+                .getErrors()
+                .get(0)
+                .getErrorMessage()
+                .contains(
+                        "First element in Json Object has to be \"Object\" or \"Array with one Object element\". Other scenarios are not supported yet."));
 
         RestconfDocumentedException cause2 = null;
         try {
@@ -133,26 +137,29 @@ public class JsonToCnSnTest {
             cause2 = e;
         }
         assertNotNull(cause2);
-        assertTrue(cause2.getErrors().get( 0 ).getErrorMessage().contains(
-                                                     "Json Object should contain one element"));
+        assertTrue(cause2.getErrors().get(0).getErrorMessage().contains("Json Object should contain one element"));
 
         RestconfDocumentedException cause3 = null;
         try {
             TestUtils
 
-                    .readInputToCnSn("/json-to-cnsn/wrong-top-level3.json", true, JsonToCompositeNodeProvider.INSTANCE);
+            .readInputToCnSn("/json-to-cnsn/wrong-top-level3.json", true, JsonToCompositeNodeProvider.INSTANCE);
         } catch (RestconfDocumentedException e) {
             cause3 = e;
         }
         assertNotNull(cause3);
-        assertTrue(cause3.getErrors().get( 0 ).getErrorMessage().contains(
-            "First element in Json Object has to be \"Object\" or \"Array with one Object element\". Other scenarios are not supported yet."));
+        assertTrue(cause3
+                .getErrors()
+                .get(0)
+                .getErrorMessage()
+                .contains(
+                        "First element in Json Object has to be \"Object\" or \"Array with one Object element\". Other scenarios are not supported yet."));
 
     }
 
     /**
-     * if leaf list with no data is in json then no corresponding data is
-     * created in composite node. if leaf with no data then exception is raised
+     * if leaf list with no data is in json then no corresponding data is created in composite node. if leaf with no
+     * data then exception is raised
      */
     @Test
     public void emptyDataReadTest() {
@@ -172,7 +179,7 @@ public class JsonToCnSnTest {
         try {
             TestUtils.readInputToCnSn("/json-to-cnsn/empty-data1.json", true, JsonToCompositeNodeProvider.INSTANCE);
         } catch (RestconfDocumentedException e) {
-            reason = e.getErrors().get( 0 ).getErrorMessage();
+            reason = e.getErrors().get(0).getErrorMessage();
         }
 
         assertTrue(reason.contains("Expected value at line"));
@@ -180,17 +187,16 @@ public class JsonToCnSnTest {
     }
 
     @Test
-    public void testJsonBlankInput() throws Exception{
-        InputStream inputStream = new ByteArrayInputStream( "".getBytes() );
-        CompositeNode compositeNode =
-                JsonToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null, inputStream);
-        assertNull( compositeNode );
+    public void testJsonBlankInput() throws Exception {
+        InputStream inputStream = new ByteArrayInputStream("".getBytes());
+        CompositeNode compositeNode = JsonToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null,
+                inputStream);
+        assertNull(compositeNode);
     }
 
     /**
-     * Tests whether namespace <b>stay unchanged</b> if concrete values are
-     * present in composite or simple node and if the method for update is
-     * called.
+     * Tests whether namespace <b>stay unchanged</b> if concrete values are present in composite or simple node and if
+     * the method for update is called.
      *
      */
     @Test
@@ -284,13 +290,14 @@ public class JsonToCnSnTest {
 
     }
 
-    private void simpleTest(final String jsonPath, final String yangPath, final String topLevelElementName, final String namespace,
-            final String moduleName) {
+    private void simpleTest(final String jsonPath, final String yangPath, final String topLevelElementName,
+            final String namespace, final String moduleName) {
         CompositeNode compNode = loadAndNormalizeData(jsonPath, yangPath, topLevelElementName, moduleName);
         verifyCompositeNode(compNode, namespace);
     }
 
-    private CompositeNode loadAndNormalizeData(final String jsonPath, final String yangPath, final String topLevelElementName, final String moduleName) {
+    private CompositeNode loadAndNormalizeData(final String jsonPath, final String yangPath,
+            final String topLevelElementName, final String moduleName) {
         CompositeNode compositeNode = TestUtils.readInputToCnSn(jsonPath, false, JsonToCompositeNodeProvider.INSTANCE);
         assertNotNull(compositeNode);
 
@@ -395,7 +402,7 @@ public class JsonToCnSnTest {
             TestUtils.readInputToCnSn("/json-to-cnsn/unsupported-json-format.json", true,
                     JsonToCompositeNodeProvider.INSTANCE);
         } catch (RestconfDocumentedException e) {
-            exceptionMessage = e.getErrors().get( 0 ).getErrorMessage();
+            exceptionMessage = e.getErrors().get(0).getErrorMessage();
         }
         assertTrue(exceptionMessage.contains("Root element of Json has to be Object"));
     }
index ddab7004408f4d60aa3e89f8660f8aa9749bce7b..656427352aea0da2242910ba5a274b1d500e63f2 100644 (file)
@@ -11,15 +11,17 @@ package org.opendaylight.controller.sal.restconf.impl.test;
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertSame;
+import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.inOrder;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.verifyNoMoreInteractions;
 import static org.mockito.Mockito.when;
 
+import com.google.common.collect.ImmutableMap;
+import com.google.common.util.concurrent.Futures;
 import java.util.Map;
 import java.util.concurrent.Future;
-
 import org.junit.Before;
 import org.junit.Test;
 import org.mockito.InOrder;
@@ -42,9 +44,7 @@ import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
-
-import com.google.common.collect.ImmutableMap;
-import com.google.common.util.concurrent.Futures;
+import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
 
 /**
  * Unit tests for BrokerFacade.
@@ -67,264 +67,252 @@ public class BrokerFacadeTest {
 
     BrokerFacade brokerFacade = BrokerFacade.getInstance();
 
-    CompositeNode dataNode = TestUtils.readInputToCnSn( "/parts/ietf-interfaces_interfaces.xml",
-                                                        XmlToCompositeNodeProvider.INSTANCE );
+    CompositeNode dataNode = TestUtils.readInputToCnSn("/parts/ietf-interfaces_interfaces.xml",
+            XmlToCompositeNodeProvider.INSTANCE);
 
-    QName qname = QName.create( "node" );
+    QName qname = QName.create("node");
 
-    InstanceIdentifier instanceID = InstanceIdentifier.builder().node( qname ).toInstance();
+    InstanceIdentifier instanceID = InstanceIdentifier.builder().node(qname).toInstance();
 
     @Before
     public void setUp() throws Exception {
-        MockitoAnnotations.initMocks( this );
+        MockitoAnnotations.initMocks(this);
 
-        brokerFacade.setDataService( dataBroker );
-        brokerFacade.setContext( mockConsumerSession );
+        brokerFacade.setDataService(dataBroker);
+        brokerFacade.setContext(mockConsumerSession);
     }
 
     @Test
     public void testReadConfigurationData() {
-        when( dataBroker.readConfigurationData( instanceID ) ).thenReturn( dataNode );
+        when(dataBroker.readConfigurationData(instanceID)).thenReturn(dataNode);
 
-        CompositeNode actualNode = brokerFacade.readConfigurationData( instanceID );
+        CompositeNode actualNode = brokerFacade.readConfigurationData(instanceID);
 
-        assertSame( "readConfigurationData", dataNode, actualNode );
+        assertSame("readConfigurationData", dataNode, actualNode);
     }
 
     @Test
     public void testReadConfigurationDataBehindMountPoint() {
-        when( mockMountInstance.readConfigurationData( instanceID ) ).thenReturn( dataNode );
+        when(mockMountInstance.readConfigurationData(instanceID)).thenReturn(dataNode);
 
-        CompositeNode actualNode = brokerFacade.readConfigurationDataBehindMountPoint(
-                                                                              mockMountInstance, instanceID );
+        CompositeNode actualNode = brokerFacade.readConfigurationDataBehindMountPoint(mockMountInstance, instanceID);
 
-        assertSame( "readConfigurationDataBehindMountPoint", dataNode, actualNode );
+        assertSame("readConfigurationDataBehindMountPoint", dataNode, actualNode);
     }
 
     @Test
     public void testReadOperationalData() {
-        when( dataBroker.readOperationalData( instanceID ) ).thenReturn( dataNode );
+        when(dataBroker.readOperationalData(instanceID)).thenReturn(dataNode);
 
-        CompositeNode actualNode = brokerFacade.readOperationalData( instanceID );
+        CompositeNode actualNode = brokerFacade.readOperationalData(instanceID);
 
-        assertSame( "readOperationalData", dataNode, actualNode );
+        assertSame("readOperationalData", dataNode, actualNode);
     }
 
     @Test
     public void testReadOperationalDataBehindMountPoint() {
-        when( mockMountInstance.readOperationalData( instanceID ) ).thenReturn( dataNode );
+        when(mockMountInstance.readOperationalData(instanceID)).thenReturn(dataNode);
 
-        CompositeNode actualNode = brokerFacade.readOperationalDataBehindMountPoint(
-                                                                              mockMountInstance, instanceID );
+        CompositeNode actualNode = brokerFacade.readOperationalDataBehindMountPoint(mockMountInstance, instanceID);
 
-        assertSame( "readOperationalDataBehindMountPoint", dataNode, actualNode );
+        assertSame("readOperationalDataBehindMountPoint", dataNode, actualNode);
     }
 
-    @Test(expected=RestconfDocumentedException.class)
+    @Test(expected = RestconfDocumentedException.class)
     public void testReadOperationalDataWithNoDataBroker() {
-        brokerFacade.setDataService( null );
+        brokerFacade.setDataService(null);
 
-        brokerFacade.readOperationalData( instanceID );
+        brokerFacade.readOperationalData(instanceID);
     }
 
     @SuppressWarnings("unchecked")
     @Test
     public void testInvokeRpc() throws Exception {
-        RpcResult<CompositeNode> expResult = mock( RpcResult.class );
-        Future<RpcResult<CompositeNode>> future = Futures.immediateFuture( expResult );
-        when( mockConsumerSession.rpc( qname, dataNode ) ).thenReturn( future );
+        RpcResult<CompositeNode> expResult = mock(RpcResult.class);
+        Future<RpcResult<CompositeNode>> future = Futures.immediateFuture(expResult);
+        when(mockConsumerSession.rpc(qname, dataNode)).thenReturn(future);
 
-        Future<RpcResult<CompositeNode>> actualFuture = brokerFacade.invokeRpc( qname, dataNode );
-        assertNotNull( "Future is null", actualFuture );
+        Future<RpcResult<CompositeNode>> actualFuture = brokerFacade.invokeRpc(qname, dataNode);
+        assertNotNull("Future is null", actualFuture);
         RpcResult<CompositeNode> actualResult = actualFuture.get();
 
-        assertSame( "invokeRpc", expResult, actualResult );
+        assertSame("invokeRpc", expResult, actualResult);
     }
 
-    @Test(expected=RestconfDocumentedException.class)
+    @Test(expected = RestconfDocumentedException.class)
     public void testInvokeRpcWithNoConsumerSession() {
-        brokerFacade.setContext( null );
+        brokerFacade.setContext(null);
 
-        brokerFacade.invokeRpc( qname, dataNode );
+        brokerFacade.invokeRpc(qname, dataNode);
     }
 
     @Test
     public void testCommitConfigurationDataPut() {
-        Future<RpcResult<TransactionStatus>> expFuture =  Futures.immediateFuture( null );
+        Future<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture(null);
 
-        when( dataBroker.beginTransaction() ).thenReturn( mockTransaction );
-        mockTransaction.putConfigurationData( instanceID, dataNode );
-        when( mockTransaction.commit() ).thenReturn( expFuture );
+        when(dataBroker.beginTransaction()).thenReturn(mockTransaction);
+        mockTransaction.putConfigurationData(instanceID, dataNode);
+        when(mockTransaction.commit()).thenReturn(expFuture);
 
-        Future<RpcResult<TransactionStatus>> actualFuture =
-                             brokerFacade.commitConfigurationDataPut( instanceID, dataNode );
+        Future<RpcResult<TransactionStatus>> actualFuture = brokerFacade.commitConfigurationDataPut(instanceID,
+                dataNode);
 
-        assertSame( "invokeRpc", expFuture, actualFuture );
+        assertSame("invokeRpc", expFuture, actualFuture);
 
-        InOrder inOrder = inOrder( dataBroker, mockTransaction );
-        inOrder.verify( dataBroker ).beginTransaction();
-        inOrder.verify( mockTransaction ).putConfigurationData( instanceID, dataNode );
-        inOrder.verify( mockTransaction ).commit();
+        InOrder inOrder = inOrder(dataBroker, mockTransaction);
+        inOrder.verify(dataBroker).beginTransaction();
+        inOrder.verify(mockTransaction).putConfigurationData(instanceID, dataNode);
+        inOrder.verify(mockTransaction).commit();
     }
 
     @Test
     public void testCommitConfigurationDataPutBehindMountPoint() {
-        Future<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture( null );
+        Future<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture(null);
 
-        when( mockMountInstance.beginTransaction() ).thenReturn( mockTransaction );
-        mockTransaction.putConfigurationData( instanceID, dataNode );
-        when( mockTransaction.commit() ).thenReturn( expFuture );
+        when(mockMountInstance.beginTransaction()).thenReturn(mockTransaction);
+        mockTransaction.putConfigurationData(instanceID, dataNode);
+        when(mockTransaction.commit()).thenReturn(expFuture);
 
-        Future<RpcResult<TransactionStatus>> actualFuture =
-                 brokerFacade.commitConfigurationDataPutBehindMountPoint(
-                                                       mockMountInstance, instanceID, dataNode );
+        Future<RpcResult<TransactionStatus>> actualFuture = brokerFacade.commitConfigurationDataPutBehindMountPoint(
+                mockMountInstance, instanceID, dataNode);
 
-        assertSame( "invokeRpc", expFuture, actualFuture );
+        assertSame("invokeRpc", expFuture, actualFuture);
 
-        InOrder inOrder = inOrder( mockMountInstance, mockTransaction );
-        inOrder.verify( mockMountInstance ).beginTransaction();
-        inOrder.verify( mockTransaction ).putConfigurationData( instanceID, dataNode );
-        inOrder.verify( mockTransaction ).commit();
+        InOrder inOrder = inOrder(mockMountInstance, mockTransaction);
+        inOrder.verify(mockMountInstance).beginTransaction();
+        inOrder.verify(mockTransaction).putConfigurationData(instanceID, dataNode);
+        inOrder.verify(mockTransaction).commit();
     }
 
     @Test
     public void testCommitConfigurationDataPost() {
-        Future<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture( null );
+        Future<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture(null);
 
-        Map<InstanceIdentifier, CompositeNode> nodeMap =
-                new ImmutableMap.Builder<InstanceIdentifier,CompositeNode>()
-                                                             .put( instanceID, dataNode ).build();
+        Map<InstanceIdentifier, CompositeNode> nodeMap = new ImmutableMap.Builder<InstanceIdentifier, CompositeNode>()
+                .put(instanceID, dataNode).build();
 
-        when( dataBroker.beginTransaction() ).thenReturn( mockTransaction );
-        mockTransaction.putConfigurationData( instanceID, dataNode );
-        when( mockTransaction.getCreatedConfigurationData() ).thenReturn( nodeMap );
-        when( mockTransaction.commit() ).thenReturn( expFuture );
+        when(dataBroker.beginTransaction()).thenReturn(mockTransaction);
+        mockTransaction.putConfigurationData(instanceID, dataNode);
+        when(mockTransaction.getCreatedConfigurationData()).thenReturn(nodeMap);
+        when(mockTransaction.commit()).thenReturn(expFuture);
 
-        Future<RpcResult<TransactionStatus>> actualFuture =
-                             brokerFacade.commitConfigurationDataPost( instanceID, dataNode );
+        Future<RpcResult<TransactionStatus>> actualFuture = brokerFacade.commitConfigurationDataPost(instanceID,
+                dataNode);
 
-        assertSame( "commitConfigurationDataPut", expFuture, actualFuture );
+        assertSame("commitConfigurationDataPut", expFuture, actualFuture);
 
-        InOrder inOrder = inOrder( dataBroker, mockTransaction );
-        inOrder.verify( dataBroker ).beginTransaction();
-        inOrder.verify( mockTransaction ).putConfigurationData( instanceID, dataNode );
-        inOrder.verify( mockTransaction ).commit();
+        InOrder inOrder = inOrder(dataBroker, mockTransaction);
+        inOrder.verify(dataBroker).beginTransaction();
+        inOrder.verify(mockTransaction).putConfigurationData(instanceID, dataNode);
+        inOrder.verify(mockTransaction).commit();
     }
 
-    @Test(expected=RestconfDocumentedException.class)
+    @Test(expected = RestconfDocumentedException.class)
     public void testCommitConfigurationDataPostAlreadyExists() {
-        when( dataBroker.beginTransaction() ).thenReturn( mockTransaction );
-        mockTransaction.putConfigurationData( instanceID, dataNode );
-        when ( mockTransaction.readConfigurationData( instanceID ) )
-            .thenReturn( dataNode );
+        when(dataBroker.beginTransaction()).thenReturn(mockTransaction);
+        mockTransaction.putConfigurationData(instanceID, dataNode);
+        when(mockTransaction.readConfigurationData(instanceID)).thenReturn(dataNode);
         try {
-            brokerFacade.commitConfigurationDataPost( instanceID, dataNode );
-        }
-        catch (RestconfDocumentedException e) {
-            assertEquals("getErrorTag",
-                    RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get( 0 ).getErrorTag());
+            brokerFacade.commitConfigurationDataPost(instanceID, dataNode);
+        } catch (RestconfDocumentedException e) {
+            assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
             throw e;
         }
     }
 
     @Test
     public void testCommitConfigurationDataPostBehindMountPoint() {
-        Future<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture( null );
+        Future<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture(null);
 
-        Map<InstanceIdentifier, CompositeNode> nodeMap =
-                new ImmutableMap.Builder<InstanceIdentifier,CompositeNode>()
-                                                           .put( instanceID, dataNode ).build();
+        Map<InstanceIdentifier, CompositeNode> nodeMap = new ImmutableMap.Builder<InstanceIdentifier, CompositeNode>()
+                .put(instanceID, dataNode).build();
 
-        when( mockMountInstance.beginTransaction() ).thenReturn( mockTransaction );
-        mockTransaction.putConfigurationData( instanceID, dataNode );
-        when( mockTransaction.getCreatedConfigurationData() ).thenReturn( nodeMap );
-        when( mockTransaction.commit() ).thenReturn( expFuture );
+        when(mockMountInstance.beginTransaction()).thenReturn(mockTransaction);
+        mockTransaction.putConfigurationData(instanceID, dataNode);
+        when(mockTransaction.getCreatedConfigurationData()).thenReturn(nodeMap);
+        when(mockTransaction.commit()).thenReturn(expFuture);
 
-        Future<RpcResult<TransactionStatus>> actualFuture =
-                brokerFacade.commitConfigurationDataPostBehindMountPoint( mockMountInstance,
-                                                                          instanceID, dataNode );
+        Future<RpcResult<TransactionStatus>> actualFuture = brokerFacade.commitConfigurationDataPostBehindMountPoint(
+                mockMountInstance, instanceID, dataNode);
 
-        assertSame( "commitConfigurationDataPostBehindMountPoint", expFuture, actualFuture );
+        assertSame("commitConfigurationDataPostBehindMountPoint", expFuture, actualFuture);
 
-        InOrder inOrder = inOrder( mockMountInstance, mockTransaction );
-        inOrder.verify( mockMountInstance ).beginTransaction();
-        inOrder.verify( mockTransaction ).putConfigurationData( instanceID, dataNode );
-        inOrder.verify( mockTransaction ).commit();
+        InOrder inOrder = inOrder(mockMountInstance, mockTransaction);
+        inOrder.verify(mockMountInstance).beginTransaction();
+        inOrder.verify(mockTransaction).putConfigurationData(instanceID, dataNode);
+        inOrder.verify(mockTransaction).commit();
     }
 
-    @Test(expected=RestconfDocumentedException.class)
+    @Test(expected = RestconfDocumentedException.class)
     public void testCommitConfigurationDataPostBehindMountPointAlreadyExists() {
 
-        when( mockMountInstance.beginTransaction() ).thenReturn( mockTransaction );
-        mockTransaction.putConfigurationData( instanceID, dataNode );
-        when ( mockTransaction.readConfigurationData( instanceID ) )
-            .thenReturn( dataNode );
+        when(mockMountInstance.beginTransaction()).thenReturn(mockTransaction);
+        mockTransaction.putConfigurationData(instanceID, dataNode);
+        when(mockTransaction.readConfigurationData(instanceID)).thenReturn(dataNode);
         try {
-            brokerFacade.commitConfigurationDataPostBehindMountPoint( mockMountInstance,
-                    instanceID, dataNode );
-        }
-        catch (RestconfDocumentedException e) {
-            assertEquals("getErrorTag",
-                    RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get( 0 ).getErrorTag());
+            brokerFacade.commitConfigurationDataPostBehindMountPoint(mockMountInstance, instanceID, dataNode);
+        } catch (RestconfDocumentedException e) {
+            assertEquals("getErrorTag", RestconfError.ErrorTag.DATA_EXISTS, e.getErrors().get(0).getErrorTag());
             throw e;
         }
     }
 
     @Test
     public void testCommitConfigurationDataDelete() {
-        Future<RpcResult<TransactionStatus>> expFuture =  Futures.immediateFuture( null );
+        Future<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture(null);
 
-        when( dataBroker.beginTransaction() ).thenReturn( mockTransaction );
-        mockTransaction.removeConfigurationData( instanceID );
-        when( mockTransaction.commit() ).thenReturn( expFuture );
+        when(dataBroker.beginTransaction()).thenReturn(mockTransaction);
+        when(mockTransaction.readConfigurationData(any(InstanceIdentifier.class))).thenReturn(
+                ImmutableCompositeNode.builder().toInstance());
+        mockTransaction.removeConfigurationData(instanceID);
+        when(mockTransaction.commit()).thenReturn(expFuture);
 
-        Future<RpcResult<TransactionStatus>> actualFuture =
-                             brokerFacade.commitConfigurationDataDelete( instanceID );
+        Future<RpcResult<TransactionStatus>> actualFuture = brokerFacade.commitConfigurationDataDelete(instanceID);
 
-        assertSame( "commitConfigurationDataDelete", expFuture, actualFuture );
+        assertSame("commitConfigurationDataDelete", expFuture, actualFuture);
 
-        InOrder inOrder = inOrder( dataBroker, mockTransaction );
-        inOrder.verify( dataBroker ).beginTransaction();
-        inOrder.verify( mockTransaction ).removeConfigurationData( instanceID );
-        inOrder.verify( mockTransaction ).commit();
+        InOrder inOrder = inOrder(dataBroker, mockTransaction);
+        inOrder.verify(dataBroker).beginTransaction();
+        inOrder.verify(mockTransaction).removeConfigurationData(instanceID);
+        inOrder.verify(mockTransaction).commit();
     }
 
     @Test
     public void testCommitConfigurationDataDeleteBehindMountPoint() {
-        Future<RpcResult<TransactionStatus>> expFuture =  Futures.immediateFuture( null );
+        Future<RpcResult<TransactionStatus>> expFuture = Futures.immediateFuture(null);
 
-        when( mockMountInstance.beginTransaction() ).thenReturn( mockTransaction );
-        mockTransaction.removeConfigurationData( instanceID );
-        when( mockTransaction.commit() ).thenReturn( expFuture );
+        when(mockMountInstance.beginTransaction()).thenReturn(mockTransaction);
+        when(mockTransaction.readConfigurationData(any(InstanceIdentifier.class))).thenReturn(
+                ImmutableCompositeNode.builder().toInstance());
+        mockTransaction.removeConfigurationData(instanceID);
+        when(mockTransaction.commit()).thenReturn(expFuture);
 
-        Future<RpcResult<TransactionStatus>> actualFuture =
-                             brokerFacade.commitConfigurationDataDeleteBehindMountPoint(
-                                                              mockMountInstance, instanceID );
+        Future<RpcResult<TransactionStatus>> actualFuture = brokerFacade.commitConfigurationDataDeleteBehindMountPoint(
+                mockMountInstance, instanceID);
 
-        assertSame( "commitConfigurationDataDeleteBehindMountPoint", expFuture, actualFuture );
+        assertSame("commitConfigurationDataDeleteBehindMountPoint", expFuture, actualFuture);
 
-        InOrder inOrder = inOrder( mockMountInstance, mockTransaction );
-        inOrder.verify( mockMountInstance ).beginTransaction();
-        inOrder.verify( mockTransaction ).removeConfigurationData( instanceID );
-        inOrder.verify( mockTransaction ).commit();
+        InOrder inOrder = inOrder(mockMountInstance, mockTransaction);
+        inOrder.verify(mockMountInstance).beginTransaction();
+        inOrder.verify(mockTransaction).removeConfigurationData(instanceID);
+        inOrder.verify(mockTransaction).commit();
     }
 
     @SuppressWarnings("unchecked")
     @Test
     public void testRegisterToListenDataChanges() {
-        ListenerAdapter listener = Notificator.createListener( instanceID, "stream" );
+        ListenerAdapter listener = Notificator.createListener(instanceID, "stream");
 
-        ListenerRegistration<DataChangeListener> mockRegistration = mock( ListenerRegistration.class );
-        when( dataBroker.registerDataChangeListener( instanceID, listener ) )
-            .thenReturn( mockRegistration );
+        ListenerRegistration<DataChangeListener> mockRegistration = mock(ListenerRegistration.class);
+        when(dataBroker.registerDataChangeListener(instanceID, listener)).thenReturn(mockRegistration);
 
-        brokerFacade.registerToListenDataChanges( listener );
+        brokerFacade.registerToListenDataChanges(listener);
 
-        verify( dataBroker ).registerDataChangeListener( instanceID, listener );
+        verify(dataBroker).registerDataChangeListener(instanceID, listener);
 
-        assertEquals( "isListening", true, listener.isListening() );
+        assertEquals("isListening", true, listener.isListening());
 
-        brokerFacade.registerToListenDataChanges( listener );
-        verifyNoMoreInteractions( dataBroker );
+        brokerFacade.registerToListenDataChanges(listener);
+        verifyNoMoreInteractions(dataBroker);
     }
 }
index 07d781028b99feaa03cd8dc610f499f63a0ca1dc..47171bf2470141bc509d2d96423b676a850826da 100644 (file)
@@ -9,6 +9,7 @@ package org.opendaylight.controller.sal.restconf.impl.test;
 
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
+import static org.opendaylight.controller.sal.restconf.impl.test.TestUtils.containsStringData;
 
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
@@ -19,16 +20,13 @@ import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
-
 import javax.ws.rs.WebApplicationException;
 import javax.xml.stream.XMLEventReader;
 import javax.xml.stream.XMLInputFactory;
 import javax.xml.stream.XMLStreamException;
 import javax.xml.stream.events.StartElement;
 import javax.xml.stream.events.XMLEvent;
-
 import org.junit.BeforeClass;
-import org.junit.Ignore;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToJsonProvider;
 import org.opendaylight.controller.sal.rest.impl.StructuredDataToXmlProvider;
@@ -39,9 +37,10 @@ import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifie
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifierWithPredicates;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeWithValue;
 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
+import org.opendaylight.yangtools.yang.data.api.SimpleNode;
+import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
 import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
+import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
 
 public class CnSnToXmlAndJsonInstanceIdentifierTest extends YangAndXmlAndDataSchemaLoader {
 
@@ -55,21 +54,16 @@ public class CnSnToXmlAndJsonInstanceIdentifierTest extends YangAndXmlAndDataSch
         CompositeNode cnSn = prepareCnSn(createInstanceIdentifier());
         String output = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSn, modules, dataSchemaNode,
                 StructuredDataToXmlProvider.INSTANCE);
-        //uncomment for debug
-        // System.out.println(output);
         validateXmlOutput(output);
 
     }
 
-    @Ignore
     @Test
     public void saveCnSnWithLeafListInstIdentifierToXmlTest() throws WebApplicationException, IOException,
-    URISyntaxException, XMLStreamException {
+            URISyntaxException, XMLStreamException {
         CompositeNode cnSn = prepareCnSn(createInstanceIdentifierWithLeafList());
         String output = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSn, modules, dataSchemaNode,
                 StructuredDataToXmlProvider.INSTANCE);
-        //uncomment for debug
-        // System.out.println(output);
         validateXmlOutputWithLeafList(output);
     }
 
@@ -79,33 +73,40 @@ public class CnSnToXmlAndJsonInstanceIdentifierTest extends YangAndXmlAndDataSch
         String output = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSn, modules, dataSchemaNode,
                 StructuredDataToJsonProvider.INSTANCE);
         boolean strInOutput = false;
-        strInOutput = output
-                .contains("\"augment-augment-module:lf111\": \"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module:lst11[augment-module:keyvalue111=\\\"value1\\\"][augment-module:keyvalue112=\\\"value2\\\"]/augment-augment-module:lf112\"");
+        strInOutput = containsStringData(
+                output,
+                "\"augment-augment-module:lf111\"",
+                ":",
+                "\"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module:lst11\\[augment-module:keyvalue111=\\\\\"value1\\\\\"\\]\\[augment-module:keyvalue112=\\\\\"value2\\\\\"\\]/augment-augment-module:lf112\"");
 
         if (!strInOutput) {
-            strInOutput = output
-                    .contains("\"augment-augment-module:lf111\": \"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module:lst11[augment-module:keyvalue111='value1'][augment-module:keyvalue112='value2']/augment-augment-module:lf112\"");
+            strInOutput = containsStringData(
+                    output,
+                    "\"augment-augment-module:lf111\"",
+                    ":",
+                    "\"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module:lst11\\[augment-module:keyvalue111='value1'\\]\\[augment-module:keyvalue112='value2'\\]/augment-augment-module:lf112\"");
         }
-        //uncomment for debug
-        // System.out.println(output);
         assertTrue(strInOutput);
     }
 
-
     @Test
     public void saveCnSnWithLeafListInstIdentifierToJsonTest() throws WebApplicationException, IOException,
-    URISyntaxException {
+            URISyntaxException {
         CompositeNode cnSn = prepareCnSn(createInstanceIdentifierWithLeafList());
         String output = TestUtils.writeCompNodeWithSchemaContextToOutput(cnSn, modules, dataSchemaNode,
                 StructuredDataToJsonProvider.INSTANCE);
-        //uncomment for debug
-        // System.out.println(output);
         boolean strInOutput = false;
-        strInOutput = output
-                .contains("\"augment-augment-module:lf111\": \"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module-leaf-list:lflst11[.='lflst11_1']\"");
+        strInOutput = containsStringData(
+                output,
+                "\"augment-augment-module:lf111\"",
+                ":",
+                "\"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module-leaf-list:lflst11\\[.='lflst11_1'\\]\"");
         if (!strInOutput) {
-            strInOutput = output
-                    .contains("\"augment-augment-module:lf111\": \"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module-leaf-list:lflst11[.=\\\"lflst11_1\\\"]\"");
+            strInOutput = containsStringData(
+                    output,
+                    "\"augment-augment-module:lf111\"",
+                    ":",
+                    "\"/instance-identifier-module:cont/instance-identifier-module:cont1/augment-module-leaf-list:lflst11\\[.=\\\\\"lflst11_1\\\\\"\\]\"");
         }
 
         assertTrue(strInOutput);
@@ -189,27 +190,21 @@ public class CnSnToXmlAndJsonInstanceIdentifierTest extends YangAndXmlAndDataSch
     }
 
     private CompositeNode prepareCnSn(final InstanceIdentifier instanceIdentifier) throws URISyntaxException {
-        MutableCompositeNode cont = NodeFactory.createMutableCompositeNode(
-                TestUtils.buildQName("cont", "instance:identifier:module", "2014-01-17"), null, null,null,null);
-        MutableCompositeNode cont1 = NodeFactory.createMutableCompositeNode(
-                TestUtils.buildQName("cont1", "instance:identifier:module", "2014-01-17"), cont, null,null,null);
-        MutableCompositeNode lst11 = NodeFactory.createMutableCompositeNode(
-                TestUtils.buildQName("lst11", "augment:module", "2014-01-17"), cont1, null,null,null);
-
-        MutableSimpleNode<?> lf111 = NodeFactory.createMutableSimpleNode(TestUtils.buildQName("lf111", "augment:augment:module", "2014-01-17"),
-                lst11, instanceIdentifier,null,null);
-
-
-        lst11.getValue().add(lf111);
-        lst11.init();
+        CompositeNodeBuilder<ImmutableCompositeNode> cont = ImmutableCompositeNode.builder();
+        cont.setQName(QName.create("instance:identifier:module", "2014-01-17", "cont"));
 
-        cont1.getValue().add(lst11);
-        cont1.init();
+        CompositeNodeBuilder<ImmutableCompositeNode> cont1 = ImmutableCompositeNode.builder();
+        cont1.setQName(QName.create("instance:identifier:module", "2014-01-17", "cont1"));
 
-        cont.getValue().add(cont1);
-        cont.init();
+        CompositeNodeBuilder<ImmutableCompositeNode> lst11 = ImmutableCompositeNode.builder();
+        lst11.setQName(QName.create("augment:module", "2014-01-17", "lst11"));
 
-        return cont;
+        SimpleNode<?> lf111 = NodeFactory.createImmutableSimpleNode(
+                QName.create("augment:augment:module", "2014-01-17", "lf111"), null, instanceIdentifier);
+        lst11.add(lf111);
+        cont1.add(lst11.toInstance());
+        cont.add(cont1.toInstance());
+        return cont.toInstance();
     }
 
     private InstanceIdentifier createInstanceIdentifier() throws URISyntaxException {
@@ -226,7 +221,7 @@ public class CnSnToXmlAndJsonInstanceIdentifierTest extends YangAndXmlAndDataSch
 
         pathArguments.add(new NodeIdentifier(new QName(new URI("augment:augment:module"), "lf112")));
 
-        return new InstanceIdentifier(pathArguments);
+        return InstanceIdentifier.create(pathArguments);
     }
 
     private InstanceIdentifier createInstanceIdentifierWithLeafList() throws URISyntaxException {
@@ -235,7 +230,7 @@ public class CnSnToXmlAndJsonInstanceIdentifierTest extends YangAndXmlAndDataSch
         pathArguments.add(new NodeIdentifier(new QName(new URI("instance:identifier:module"), "cont1")));
         pathArguments.add(new NodeWithValue(new QName(new URI("augment:module:leaf:list"), "lflst11"), "lflst11_1"));
 
-        return new InstanceIdentifier(pathArguments);
+        return InstanceIdentifier.create(pathArguments);
     }
 
 }
index 307abebdd7b1a37ebfb3cc1d716048614c3e44cc..4ff4f707106a59058702166beb99a5cf8f506cb2 100644 (file)
@@ -3,12 +3,10 @@ package org.opendaylight.controller.sal.restconf.impl.test;
 import static org.junit.Assert.assertTrue;
 
 import java.io.FileNotFoundException;
-
 import javax.ws.rs.client.Entity;
 import javax.ws.rs.core.Application;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
-
 import org.glassfish.jersey.server.ResourceConfig;
 import org.glassfish.jersey.test.JerseyTest;
 import org.junit.BeforeClass;
@@ -47,7 +45,7 @@ public class CodecsExceptionsCatchingTest extends JerseyTest {
         resourceConfig = resourceConfig.registerInstances(restConf, StructuredDataToXmlProvider.INSTANCE,
                 StructuredDataToJsonProvider.INSTANCE, XmlToCompositeNodeProvider.INSTANCE,
                 JsonToCompositeNodeProvider.INSTANCE);
-        resourceConfig.registerClasses( RestconfDocumentedExceptionMapper.class );
+        resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
         return resourceConfig;
     }
 
index 19a7eff480dece01d1e9ff5743b3ef9c5fa94c5e..8ae8d0bdac927415b7ebd514cf8c356a45a6b52e 100644 (file)
@@ -34,7 +34,6 @@ public class DummyFuture<T> implements Future<RpcResult<T>> {
         result = builder.result;
     }
 
-
     @Override
     public boolean cancel(final boolean mayInterruptIfRunning) {
         return cancel;
@@ -56,8 +55,8 @@ public class DummyFuture<T> implements Future<RpcResult<T>> {
     }
 
     @Override
-    public RpcResult<T> get(final long timeout, final TimeUnit unit) throws InterruptedException,
-    ExecutionException, TimeoutException {
+    public RpcResult<T> get(final long timeout, final TimeUnit unit) throws InterruptedException, ExecutionException,
+            TimeoutException {
         return result;
     }
 
index 16d14842db3c2cc02684e244a219f7d20da03daf..3c545c06e95054f70dd4ab21c42912179f37990d 100644 (file)
@@ -8,7 +8,6 @@
 package org.opendaylight.controller.sal.restconf.impl.test;
 
 import java.util.Collection;
-
 import org.opendaylight.yangtools.yang.common.RpcError;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 
index d90e9539c83cbbeeff51726967370dc1f6e53724..008fda4e0960b9e2ecd3b3c5518887dd03dba452 100644 (file)
@@ -8,7 +8,6 @@
 package org.opendaylight.controller.sal.restconf.impl.test;
 
 import java.util.List;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.opendaylight.yangtools.yang.model.api.Status;
index 910ca8e20aab453d02b4e320b0493775666d3575..313b766ed3312bad6cb5f74a542e84893226aa54 100644 (file)
@@ -19,6 +19,9 @@ import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.when;
 
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
 import java.io.FileNotFoundException;
 import java.net.URI;
 import java.net.URISyntaxException;
@@ -27,12 +30,13 @@ import java.util.Collections;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
-
+import javax.ws.rs.core.MultivaluedHashMap;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.UriInfo;
 import org.junit.Before;
 import org.junit.BeforeClass;
 import org.junit.Test;
-import org.opendaylight.controller.sal.common.util.RpcErrors;
-import org.opendaylight.controller.sal.common.util.Rpcs;
+
 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
@@ -45,8 +49,8 @@ import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
 import org.opendaylight.controller.sal.restconf.impl.StructuredData;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.RpcError;
-import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
 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.ModifyAction;
 import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
@@ -56,42 +60,38 @@ import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-
 public class InvokeRpcMethodTest {
 
     private RestconfImpl restconfImpl = null;
     private static ControllerContext controllerContext = null;
-
+    private static UriInfo uriInfo;
 
     @BeforeClass
     public static void init() throws FileNotFoundException {
-        Set<Module> allModules = new HashSet<Module>( TestUtils
-                .loadModulesFrom("/full-versions/yangs") );
-        allModules.addAll( TestUtils.loadModulesFrom("/invoke-rpc") );
+        Set<Module> allModules = new HashSet<Module>(TestUtils.loadModulesFrom("/full-versions/yangs"));
+        allModules.addAll(TestUtils.loadModulesFrom("/invoke-rpc"));
         assertNotNull(allModules);
         Module module = TestUtils.resolveModule("invoke-rpc-module", allModules);
         assertNotNull(module);
         SchemaContext schemaContext = TestUtils.loadSchemaContext(allModules);
-        controllerContext = spy( ControllerContext.getInstance() );
+        controllerContext = spy(ControllerContext.getInstance());
         controllerContext.setSchemas(schemaContext);
-
+        uriInfo = mock(UriInfo.class);
+        MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
+        map.put("prettyPrint", Collections.singletonList("true"));
+        when(uriInfo.getQueryParameters(any(Boolean.class))).thenReturn(map);
     }
 
     @Before
-    public void initMethod()
-    {
+    public void initMethod() {
         restconfImpl = RestconfImpl.getInstance();
-        restconfImpl.setControllerContext( controllerContext );
+        restconfImpl.setControllerContext(controllerContext);
     }
 
     /**
-     * Test method invokeRpc in RestconfImpl class tests if composite node as
-     * input parameter of method invokeRpc (second argument) is wrapped to
-     * parent composite node which has QName equals to QName of rpc (resolved
-     * from string - first argument).
+     * Test method invokeRpc in RestconfImpl class tests if composite node as input parameter of method invokeRpc
+     * (second argument) is wrapped to parent composite node which has QName equals to QName of rpc (resolved from
+     * string - first argument).
      */
     @Test
     public void invokeRpcMtethodTest() {
@@ -110,11 +110,10 @@ public class InvokeRpcMethodTest {
 
         CompositeNode payload = preparePayload();
 
-        when(mockedBrokerFacade.invokeRpc(any(QName.class), any(CompositeNode.class)))
-            .thenReturn( Futures.<RpcResult<CompositeNode>>immediateFuture(
-                                               Rpcs.<CompositeNode>getRpcResult( true ) ) );
+        when(mockedBrokerFacade.invokeRpc(any(QName.class), any(CompositeNode.class))).thenReturn(
+                Futures.<RpcResult<CompositeNode>> immediateFuture(RpcResultBuilder.<CompositeNode>success().build()));
 
-        StructuredData structData = restconf.invokeRpc("invoke-rpc-module:rpc-test", payload);
+        StructuredData structData = restconf.invokeRpc("invoke-rpc-module:rpc-test", payload, uriInfo);
         assertTrue(structData == null);
 
     }
@@ -132,207 +131,205 @@ public class InvokeRpcMethodTest {
 
     @Test
     public void testInvokeRpcWithNoPayloadRpc_FailNoErrors() {
-        RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode>getRpcResult( false );
+        RpcResult<CompositeNode> rpcResult = RpcResultBuilder.<CompositeNode>failed().build();
 
         BrokerFacade brokerFacade = mock(BrokerFacade.class);
-        when( brokerFacade.invokeRpc(
-                 eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")),
-                 any(CompositeNode.class)))
-            .thenReturn( Futures.<RpcResult<CompositeNode>>immediateFuture( rpcResult ) );
+        when(
+                brokerFacade.invokeRpc(
+                        eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")),
+                        any(CompositeNode.class))).thenReturn(
+                Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
 
         restconfImpl.setBroker(brokerFacade);
 
         try {
-            restconfImpl.invokeRpc("toaster:cancel-toast", "");
+            restconfImpl.invokeRpc("toaster:cancel-toast", "", uriInfo);
             fail("Expected an exception to be thrown.");
-        }
-        catch (RestconfDocumentedException e) {
-            verifyRestconfDocumentedException( e, 0, ErrorType.RPC, ErrorTag.OPERATION_FAILED,
-                                               Optional.<String>absent(), Optional.<String>absent() );
+        } catch (RestconfDocumentedException e) {
+            verifyRestconfDocumentedException(e, 0, ErrorType.RPC, ErrorTag.OPERATION_FAILED,
+                    Optional.<String> absent(), Optional.<String> absent());
         }
     }
 
-    void verifyRestconfDocumentedException( final RestconfDocumentedException e, final int index,
-                                            final ErrorType expErrorType, final ErrorTag expErrorTag,
-                                            final Optional<String> expErrorMsg,
-                                            final Optional<String> expAppTag ) {
+    void verifyRestconfDocumentedException(final RestconfDocumentedException e, final int index,
+            final ErrorType expErrorType, final ErrorTag expErrorTag, final Optional<String> expErrorMsg,
+            final Optional<String> expAppTag) {
         RestconfError actual = null;
         try {
-            actual = e.getErrors().get( index );
-        }
-        catch( ArrayIndexOutOfBoundsException ex ) {
-            fail( "RestconfError not found at index " + index );
+            actual = e.getErrors().get(index);
+        } catch (ArrayIndexOutOfBoundsException ex) {
+            fail("RestconfError not found at index " + index);
         }
 
-        assertEquals( "getErrorType", expErrorType, actual.getErrorType() );
-        assertEquals( "getErrorTag", expErrorTag, actual.getErrorTag() );
-        assertNotNull( "getErrorMessage is null", actual.getErrorMessage() );
+        assertEquals("getErrorType", expErrorType, actual.getErrorType());
+        assertEquals("getErrorTag", expErrorTag, actual.getErrorTag());
+        assertNotNull("getErrorMessage is null", actual.getErrorMessage());
 
-        if( expErrorMsg.isPresent() ) {
-            assertEquals( "getErrorMessage", expErrorMsg.get(), actual.getErrorMessage() );
+        if (expErrorMsg.isPresent()) {
+            assertEquals("getErrorMessage", expErrorMsg.get(), actual.getErrorMessage());
         }
 
-        if( expAppTag.isPresent() ) {
-            assertEquals( "getErrorAppTag", expAppTag.get(), actual.getErrorAppTag() );
+        if (expAppTag.isPresent()) {
+            assertEquals("getErrorAppTag", expAppTag.get(), actual.getErrorAppTag());
         }
     }
 
     @Test
     public void testInvokeRpcWithNoPayloadRpc_FailWithRpcError() {
         List<RpcError> rpcErrors = Arrays.asList(
-            RpcErrors.getRpcError( null, "bogusTag", null, ErrorSeverity.ERROR, "foo",
-                                   RpcError.ErrorType.TRANSPORT, null ),
-            RpcErrors.getRpcError( "app-tag", "in-use", null, ErrorSeverity.WARNING, "bar",
-                                   RpcError.ErrorType.RPC, null ));
+            RpcResultBuilder.newError( RpcError.ErrorType.TRANSPORT, "bogusTag", "foo" ),
+            RpcResultBuilder.newWarning( RpcError.ErrorType.RPC, "in-use", "bar",
+                                         "app-tag", null, null ) );
 
-        RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode>getRpcResult( false, rpcErrors );
+        RpcResult<CompositeNode> rpcResult = RpcResultBuilder.<CompositeNode>failed()
+                                                              .withRpcErrors(rpcErrors).build();
 
         BrokerFacade brokerFacade = mock(BrokerFacade.class);
-        when( brokerFacade.invokeRpc(
-                 eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")),
-                 any(CompositeNode.class)))
-            .thenReturn( Futures.<RpcResult<CompositeNode>>immediateFuture( rpcResult ) );
+        when(
+                brokerFacade.invokeRpc(
+                        eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")),
+                        any(CompositeNode.class))).thenReturn(
+                Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
 
         restconfImpl.setBroker(brokerFacade);
 
         try {
-            restconfImpl.invokeRpc("toaster:cancel-toast", "");
+            restconfImpl.invokeRpc("toaster:cancel-toast", "", uriInfo);
             fail("Expected an exception to be thrown.");
-        }
-        catch (RestconfDocumentedException e) {
-            verifyRestconfDocumentedException( e, 0, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED,
-                                               Optional.of( "foo" ), Optional.<String>absent() );
-            verifyRestconfDocumentedException( e, 1, ErrorType.RPC, ErrorTag.IN_USE,
-                                               Optional.of( "bar" ), Optional.of( "app-tag" ) );
+        } catch (RestconfDocumentedException e) {
+            verifyRestconfDocumentedException(e, 0, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED, Optional.of("foo"),
+                    Optional.<String> absent());
+            verifyRestconfDocumentedException(e, 1, ErrorType.RPC, ErrorTag.IN_USE, Optional.of("bar"),
+                    Optional.of("app-tag"));
         }
     }
 
     @Test
     public void testInvokeRpcWithNoPayload_Success() {
-        RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode>getRpcResult( true );
+        RpcResult<CompositeNode> rpcResult = RpcResultBuilder.<CompositeNode>success().build();
 
         BrokerFacade brokerFacade = mock(BrokerFacade.class);
-        when( brokerFacade.invokeRpc(
-                 eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")),
-                 any( CompositeNode.class )))
-            .thenReturn( Futures.<RpcResult<CompositeNode>>immediateFuture( rpcResult ) );
+        when(
+                brokerFacade.invokeRpc(
+                        eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")),
+                        any(CompositeNode.class))).thenReturn(
+                Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
 
         restconfImpl.setBroker(brokerFacade);
 
-        StructuredData output = restconfImpl.invokeRpc("toaster:cancel-toast",
-                "");
+        StructuredData output = restconfImpl.invokeRpc("toaster:cancel-toast", "", uriInfo);
         assertEquals(null, output);
-        //additional validation in the fact that the restconfImpl does not throw an exception.
+        // additional validation in the fact that the restconfImpl does not
+        // throw an exception.
     }
 
     @Test
     public void testInvokeRpcMethodExpectingNoPayloadButProvidePayload() {
         try {
-            restconfImpl.invokeRpc("toaster:cancel-toast", " a payload ");
+            restconfImpl.invokeRpc("toaster:cancel-toast", " a payload ", uriInfo);
             fail("Expected an exception");
         } catch (RestconfDocumentedException e) {
-            verifyRestconfDocumentedException( e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
-                                               Optional.<String>absent(), Optional.<String>absent() );
+            verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
+                    Optional.<String> absent(), Optional.<String> absent());
         }
     }
 
     @Test
     public void testInvokeRpcMethodWithBadMethodName() {
         try {
-            restconfImpl.invokeRpc("toaster:bad-method", "");
+            restconfImpl.invokeRpc("toaster:bad-method", "", uriInfo);
             fail("Expected an exception");
-        }
-        catch (RestconfDocumentedException e) {
-            verifyRestconfDocumentedException( e, 0, ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT,
-                                               Optional.<String>absent(), Optional.<String>absent() );
+        } catch (RestconfDocumentedException e) {
+            verifyRestconfDocumentedException(e, 0, ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT,
+                    Optional.<String> absent(), Optional.<String> absent());
         }
     }
 
     @Test
     public void testInvokeRpcMethodWithInput() {
-        RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode>getRpcResult( true );
+        RpcResult<CompositeNode> rpcResult = RpcResultBuilder.<CompositeNode>success().build();
 
         CompositeNode payload = mock(CompositeNode.class);
 
         BrokerFacade brokerFacade = mock(BrokerFacade.class);
-        when( brokerFacade.invokeRpc(
-                 eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)make-toast")),
-                 any(CompositeNode.class)))
-            .thenReturn( Futures.<RpcResult<CompositeNode>>immediateFuture( rpcResult ) );
+        when(
+                brokerFacade.invokeRpc(
+                        eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)make-toast")),
+                        any(CompositeNode.class))).thenReturn(
+                Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
 
         restconfImpl.setBroker(brokerFacade);
 
-        StructuredData output = restconfImpl.invokeRpc("toaster:make-toast",
-                payload);
+        StructuredData output = restconfImpl.invokeRpc("toaster:make-toast", payload, uriInfo);
         assertEquals(null, output);
-        //additional validation in the fact that the restconfImpl does not throw an exception.
+        // additional validation in the fact that the restconfImpl does not
+        // throw an exception.
     }
 
     @Test
     public void testThrowExceptionWhenSlashInModuleName() {
         try {
-            restconfImpl.invokeRpc("toaster/slash", "");
+            restconfImpl.invokeRpc("toaster/slash", "", uriInfo);
             fail("Expected an exception.");
-        }
-        catch (RestconfDocumentedException e) {
-            verifyRestconfDocumentedException( e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
-                                               Optional.<String>absent(), Optional.<String>absent() );
+        } catch (RestconfDocumentedException e) {
+            verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
+                    Optional.<String> absent(), Optional.<String> absent());
         }
     }
 
     @Test
     public void testInvokeRpcWithNoPayloadWithOutput_Success() {
-        CompositeNode compositeNode = mock( CompositeNode.class );
-        RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode>getRpcResult( true, compositeNode,
-                                                            Collections.<RpcError>emptyList() );
+        CompositeNode compositeNode = mock(CompositeNode.class);
+        RpcResult<CompositeNode> rpcResult =
+                                  RpcResultBuilder.<CompositeNode>success(compositeNode).build();
 
         BrokerFacade brokerFacade = mock(BrokerFacade.class);
-        when( brokerFacade.invokeRpc(
+        when(
+                brokerFacade.invokeRpc(
                         eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)testOutput")),
-                        any( CompositeNode.class )))
-            .thenReturn( Futures.<RpcResult<CompositeNode>>immediateFuture( rpcResult ) );
+                        any(CompositeNode.class))).thenReturn(
+                Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
 
         restconfImpl.setBroker(brokerFacade);
 
-        StructuredData output = restconfImpl.invokeRpc("toaster:testOutput", "");
-        assertNotNull( output );
-        assertSame( compositeNode, output.getData() );
-        assertNotNull( output.getSchema() );
+        StructuredData output = restconfImpl.invokeRpc("toaster:testOutput", "", uriInfo);
+        assertNotNull(output);
+        assertSame(compositeNode, output.getData());
+        assertNotNull(output.getSchema());
     }
 
     @Test
-    public void testMountedRpcCallNoPayload_Success() throws Exception
-    {
-        RpcResult<CompositeNode> rpcResult = Rpcs.<CompositeNode>getRpcResult( true );
+    public void testMountedRpcCallNoPayload_Success() throws Exception {
+        RpcResult<CompositeNode> rpcResult = RpcResultBuilder.<CompositeNode>success().build();
 
-        ListenableFuture<RpcResult<CompositeNode>> mockListener = mock( ListenableFuture.class );
-        when( mockListener.get() ).thenReturn( rpcResult );
+        ListenableFuture<RpcResult<CompositeNode>> mockListener = mock(ListenableFuture.class);
+        when(mockListener.get()).thenReturn(rpcResult);
 
-        QName cancelToastQName = QName.create( "namespace", "2014-05-28", "cancelToast" );
+        QName cancelToastQName = QName.create("namespace", "2014-05-28", "cancelToast");
 
-        RpcDefinition mockRpc = mock( RpcDefinition.class );
-        when( mockRpc.getQName() ).thenReturn( cancelToastQName );
+        RpcDefinition mockRpc = mock(RpcDefinition.class);
+        when(mockRpc.getQName()).thenReturn(cancelToastQName);
 
-        MountInstance mockMountPoint = mock( MountInstance.class );
-        when( mockMountPoint.rpc( eq( cancelToastQName ), any( CompositeNode.class ) ) )
-        .thenReturn( mockListener );
+        MountInstance mockMountPoint = mock(MountInstance.class);
+        when(mockMountPoint.rpc(eq(cancelToastQName), any(CompositeNode.class))).thenReturn(mockListener);
 
-        InstanceIdWithSchemaNode mockedInstanceId = mock( InstanceIdWithSchemaNode.class );
-        when( mockedInstanceId.getMountPoint() ).thenReturn( mockMountPoint );
+        InstanceIdWithSchemaNode mockedInstanceId = mock(InstanceIdWithSchemaNode.class);
+        when(mockedInstanceId.getMountPoint()).thenReturn(mockMountPoint);
 
-        ControllerContext mockedContext = mock( ControllerContext.class );
+        ControllerContext mockedContext = mock(ControllerContext.class);
         String cancelToastStr = "toaster:cancel-toast";
-        when( mockedContext.urlPathArgDecode( cancelToastStr ) ).thenReturn( cancelToastStr );
-        when( mockedContext.getRpcDefinition( cancelToastStr ) ).thenReturn( mockRpc );
-        when( mockedContext.toMountPointIdentifier(  "opendaylight-inventory:nodes/node/"
-                + "REMOTE_HOST/yang-ext:mount/toaster:cancel-toast" ) ).thenReturn( mockedInstanceId );
+        when(mockedContext.urlPathArgDecode(cancelToastStr)).thenReturn(cancelToastStr);
+        when(mockedContext.getRpcDefinition(cancelToastStr)).thenReturn(mockRpc);
+        when(
+                mockedContext.toMountPointIdentifier("opendaylight-inventory:nodes/node/"
+                        + "REMOTE_HOST/yang-ext:mount/toaster:cancel-toast")).thenReturn(mockedInstanceId);
 
-        restconfImpl.setControllerContext( mockedContext );
+        restconfImpl.setControllerContext(mockedContext);
         StructuredData output = restconfImpl.invokeRpc(
-                "opendaylight-inventory:nodes/node/REMOTE_HOST/yang-ext:mount/toaster:cancel-toast",
-                "");
+                "opendaylight-inventory:nodes/node/REMOTE_HOST/yang-ext:mount/toaster:cancel-toast", "", uriInfo);
         assertEquals(null, output);
 
-        //additional validation in the fact that the restconfImpl does not throw an exception.
+        // additional validation in the fact that the restconfImpl does not
+        // throw an exception.
     }
 }
index 319603dfc14b1f6a4965d6de46e99bf1a6199f8f..3dd3101a2e2a325f8da94cdacef60dbaa0c0add0 100644 (file)
@@ -19,12 +19,10 @@ import static org.opendaylight.controller.sal.restconf.impl.test.RestOperationUt
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.UnsupportedEncodingException;
-
 import javax.ws.rs.client.Entity;
 import javax.ws.rs.core.Application;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.UriInfo;
-
 import org.glassfish.jersey.server.ResourceConfig;
 import org.glassfish.jersey.test.JerseyTest;
 import org.junit.BeforeClass;
@@ -55,10 +53,10 @@ public class MediaTypesTest extends JerseyTest {
     @Override
     protected Application configure() {
         /* enable/disable Jersey logs to console */
-//        enable(TestProperties.LOG_TRAFFIC);
-//        enable(TestProperties.DUMP_ENTITY);
-//        enable(TestProperties.RECORD_LOG_LEVEL);
-//        set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
+        // enable(TestProperties.LOG_TRAFFIC);
+        // enable(TestProperties.DUMP_ENTITY);
+        // enable(TestProperties.RECORD_LOG_LEVEL);
+        // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
         ResourceConfig resourceConfig = new ResourceConfig();
         resourceConfig = resourceConfig.registerInstances(restconfService, StructuredDataToXmlProvider.INSTANCE,
                 StructuredDataToJsonProvider.INSTANCE, XmlToCompositeNodeProvider.INSTANCE,
@@ -66,31 +64,31 @@ public class MediaTypesTest extends JerseyTest {
         return resourceConfig;
     }
 
-  @Test
-  public void testPostOperationsWithInputDataMediaTypes() throws UnsupportedEncodingException {
-      String uriPrefix = "/operations/";
-      String uriPath = "ietf-interfaces:interfaces";
-      String uri = uriPrefix + uriPath;
-      when(restconfService.invokeRpc(eq(uriPath), any(CompositeNode.class))).thenReturn(null);
-      post(uri, Draft02.MediaTypes.OPERATION+JSON, Draft02.MediaTypes.OPERATION+JSON, jsonData);
-      verify(restconfService, times(1)).invokeRpc(eq(uriPath), any(CompositeNode.class));
-      post(uri, Draft02.MediaTypes.OPERATION+XML, Draft02.MediaTypes.OPERATION+XML, xmlData);
-      verify(restconfService, times(2)).invokeRpc(eq(uriPath), any(CompositeNode.class));
-      post(uri, MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, jsonData);
-      verify(restconfService, times(3)).invokeRpc(eq(uriPath), any(CompositeNode.class));
-      post(uri, MediaType.APPLICATION_XML, MediaType.APPLICATION_XML, xmlData);
-      verify(restconfService, times(4)).invokeRpc(eq(uriPath), any(CompositeNode.class));
-      post(uri, MediaType.TEXT_XML, MediaType.TEXT_XML, xmlData);
-      verify(restconfService, times(5)).invokeRpc(eq(uriPath), any(CompositeNode.class));
-      post(uri, null, MediaType.TEXT_XML, xmlData);
-      verify(restconfService, times(6)).invokeRpc(eq(uriPath), any(CompositeNode.class));
-
-      // negative tests
-      post(uri, MediaType.TEXT_PLAIN, MediaType.TEXT_XML, xmlData);
-      verify(restconfService, times(6)).invokeRpc(eq(uriPath), any(CompositeNode.class));
-      post(uri, MediaType.TEXT_XML, MediaType.TEXT_PLAIN, xmlData);
-      verify(restconfService, times(6)).invokeRpc(eq(uriPath), any(CompositeNode.class));
-  }
+    @Test
+    public void testPostOperationsWithInputDataMediaTypes() throws UnsupportedEncodingException {
+        String uriPrefix = "/operations/";
+        String uriPath = "ietf-interfaces:interfaces";
+        String uri = uriPrefix + uriPath;
+        when(restconfService.invokeRpc(eq(uriPath), any(CompositeNode.class), any(UriInfo.class))).thenReturn(null);
+        post(uri, Draft02.MediaTypes.OPERATION + JSON, Draft02.MediaTypes.OPERATION + JSON, jsonData);
+        verify(restconfService, times(1)).invokeRpc(eq(uriPath), any(CompositeNode.class), any(UriInfo.class));
+        post(uri, Draft02.MediaTypes.OPERATION + XML, Draft02.MediaTypes.OPERATION + XML, xmlData);
+        verify(restconfService, times(2)).invokeRpc(eq(uriPath), any(CompositeNode.class), any(UriInfo.class));
+        post(uri, MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON, jsonData);
+        verify(restconfService, times(3)).invokeRpc(eq(uriPath), any(CompositeNode.class), any(UriInfo.class));
+        post(uri, MediaType.APPLICATION_XML, MediaType.APPLICATION_XML, xmlData);
+        verify(restconfService, times(4)).invokeRpc(eq(uriPath), any(CompositeNode.class), any(UriInfo.class));
+        post(uri, MediaType.TEXT_XML, MediaType.TEXT_XML, xmlData);
+        verify(restconfService, times(5)).invokeRpc(eq(uriPath), any(CompositeNode.class), any(UriInfo.class));
+        post(uri, null, MediaType.TEXT_XML, xmlData);
+        verify(restconfService, times(6)).invokeRpc(eq(uriPath), any(CompositeNode.class), any(UriInfo.class));
+
+        // negative tests
+        post(uri, MediaType.TEXT_PLAIN, MediaType.TEXT_XML, xmlData);
+        verify(restconfService, times(6)).invokeRpc(eq(uriPath), any(CompositeNode.class), any(UriInfo.class));
+        post(uri, MediaType.TEXT_XML, MediaType.TEXT_PLAIN, xmlData);
+        verify(restconfService, times(6)).invokeRpc(eq(uriPath), any(CompositeNode.class), any(UriInfo.class));
+    }
 
     @Test
     public void testGetConfigMediaTypes() throws UnsupportedEncodingException {
@@ -98,9 +96,9 @@ public class MediaTypesTest extends JerseyTest {
         String uriPath = "ietf-interfaces:interfaces";
         String uri = uriPrefix + uriPath;
         when(restconfService.readConfigurationData(eq(uriPath), any(UriInfo.class))).thenReturn(null);
-        get(uri, Draft02.MediaTypes.DATA+JSON);
+        get(uri, Draft02.MediaTypes.DATA + JSON);
         verify(restconfService, times(1)).readConfigurationData(eq(uriPath), any(UriInfo.class));
-        get(uri, Draft02.MediaTypes.DATA+XML);
+        get(uri, Draft02.MediaTypes.DATA + XML);
         verify(restconfService, times(2)).readConfigurationData(eq(uriPath), any(UriInfo.class));
         get(uri, MediaType.APPLICATION_JSON);
         verify(restconfService, times(3)).readConfigurationData(eq(uriPath), any(UriInfo.class));
@@ -120,9 +118,9 @@ public class MediaTypesTest extends JerseyTest {
         String uriPath = "ietf-interfaces:interfaces";
         String uri = uriPrefix + uriPath;
         when(restconfService.readOperationalData(eq(uriPath), any(UriInfo.class))).thenReturn(null);
-        get(uri, Draft02.MediaTypes.DATA+JSON);
+        get(uri, Draft02.MediaTypes.DATA + JSON);
         verify(restconfService, times(1)).readOperationalData(eq(uriPath), any(UriInfo.class));
-        get(uri, Draft02.MediaTypes.DATA+XML);
+        get(uri, Draft02.MediaTypes.DATA + XML);
         verify(restconfService, times(2)).readOperationalData(eq(uriPath), any(UriInfo.class));
         get(uri, MediaType.APPLICATION_JSON);
         verify(restconfService, times(3)).readOperationalData(eq(uriPath), any(UriInfo.class));
@@ -142,9 +140,9 @@ public class MediaTypesTest extends JerseyTest {
         String uriPath = "ietf-interfaces:interfaces";
         String uri = uriPrefix + uriPath;
         when(restconfService.updateConfigurationData(eq(uriPath), any(CompositeNode.class))).thenReturn(null);
-        put(uri, null, Draft02.MediaTypes.DATA+JSON, jsonData);
+        put(uri, null, Draft02.MediaTypes.DATA + JSON, jsonData);
         verify(restconfService, times(1)).updateConfigurationData(eq(uriPath), any(CompositeNode.class));
-        put(uri, null, Draft02.MediaTypes.DATA+XML, xmlData);
+        put(uri, null, Draft02.MediaTypes.DATA + XML, xmlData);
         verify(restconfService, times(2)).updateConfigurationData(eq(uriPath), any(CompositeNode.class));
         put(uri, null, MediaType.APPLICATION_JSON, jsonData);
         verify(restconfService, times(3)).updateConfigurationData(eq(uriPath), any(CompositeNode.class));
@@ -162,9 +160,9 @@ public class MediaTypesTest extends JerseyTest {
         String uriPath = "ietf-interfaces:interfaces";
         String uri = uriPrefix + uriPath;
         when(restconfService.createConfigurationData(eq(uriPath), any(CompositeNode.class))).thenReturn(null);
-        post(uri, null, Draft02.MediaTypes.DATA+JSON, jsonData);
+        post(uri, null, Draft02.MediaTypes.DATA + JSON, jsonData);
         verify(restconfService, times(1)).createConfigurationData(eq(uriPath), any(CompositeNode.class));
-        post(uri, null, Draft02.MediaTypes.DATA+XML, xmlData);
+        post(uri, null, Draft02.MediaTypes.DATA + XML, xmlData);
         verify(restconfService, times(2)).createConfigurationData(eq(uriPath), any(CompositeNode.class));
         post(uri, null, MediaType.APPLICATION_JSON, jsonData);
         verify(restconfService, times(3)).createConfigurationData(eq(uriPath), any(CompositeNode.class));
@@ -181,9 +179,9 @@ public class MediaTypesTest extends JerseyTest {
         String uriPrefix = "/config/";
         String uri = uriPrefix;
         when(restconfService.createConfigurationData(any(CompositeNode.class))).thenReturn(null);
-        post(uri, null, Draft02.MediaTypes.DATA+JSON, jsonData);
+        post(uri, null, Draft02.MediaTypes.DATA + JSON, jsonData);
         verify(restconfService, times(1)).createConfigurationData(any(CompositeNode.class));
-        post(uri, null, Draft02.MediaTypes.DATA+XML, xmlData);
+        post(uri, null, Draft02.MediaTypes.DATA + XML, xmlData);
         verify(restconfService, times(2)).createConfigurationData(any(CompositeNode.class));
         post(uri, null, MediaType.APPLICATION_JSON, jsonData);
         verify(restconfService, times(3)).createConfigurationData(any(CompositeNode.class));
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/MultipleEqualNamesForDataNodesTest.java b/opendaylight/md-sal/sal-rest-connector/src/test/java/org/opendaylight/controller/sal/restconf/impl/test/MultipleEqualNamesForDataNodesTest.java
new file mode 100644 (file)
index 0000000..5fbfc45
--- /dev/null
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.sal.restconf.impl.test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+
+import java.util.List;
+import java.util.Set;
+import javax.ws.rs.ext.MessageBodyReader;
+import org.junit.Test;
+import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
+import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
+import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
+import org.opendaylight.controller.sal.restconf.impl.RestconfError;
+import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
+import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.model.api.Module;
+
+/**
+ * If more then one data element with equal name exists where container or leaf schema node should be present the
+ * RestconfDocumentedException has to be raised
+ *
+ * Tests for BUG 1204
+ */
+public class MultipleEqualNamesForDataNodesTest {
+
+    @Test
+    public void multipleEqualNameDataNodeTestForContainerJsonTest() {
+        multipleEqualNameDataNodeTest("/equal-data-node-names/equal-name-data-for-container.json",
+                ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, JsonToCompositeNodeProvider.INSTANCE);
+    }
+
+    @Test
+    public void multipleEqualNameDataNodeTestForLeafJsonTest() {
+        multipleEqualNameDataNodeTest("/equal-data-node-names/equal-name-data-for-leaf.json", ErrorType.PROTOCOL,
+                ErrorTag.MALFORMED_MESSAGE, JsonToCompositeNodeProvider.INSTANCE);
+    }
+
+    @Test
+    public void multipleEqualNameDataNodeTestForContainerXmlTest() {
+        multipleEqualNameDataNodeTest("/equal-data-node-names/equal-name-data-for-container.xml",
+                ErrorType.APPLICATION, ErrorTag.BAD_ELEMENT, XmlToCompositeNodeProvider.INSTANCE);
+    }
+
+    @Test
+    public void multipleEqualNameDataNodeTestForLeafXmlTest() {
+        multipleEqualNameDataNodeTest("/equal-data-node-names/equal-name-data-for-leaf.xml", ErrorType.APPLICATION,
+                ErrorTag.BAD_ELEMENT, XmlToCompositeNodeProvider.INSTANCE);
+    }
+
+    private void multipleEqualNameDataNodeTest(String path, ErrorType errorType, ErrorTag errorTag,
+            MessageBodyReader<CompositeNode> messageBodyReader) {
+        try {
+            CompositeNode compositeNode = TestUtils.readInputToCnSn(path, false, messageBodyReader);
+            assertNotNull(compositeNode);
+
+            Set<Module> modules = null;
+            modules = TestUtils.loadModulesFrom("/equal-data-node-names/yang");
+            assertNotNull(modules);
+
+            TestUtils.normalizeCompositeNode(compositeNode, modules, "equal-data-node-names" + ":" + "cont");
+            fail("Exception RestconfDocumentedException should be raised");
+        } catch (RestconfDocumentedException e) {
+            List<RestconfError> errors = e.getErrors();
+            assertNotNull(errors);
+
+            assertEquals(1, errors.size());
+
+            RestconfError restconfError = errors.get(0);
+
+            assertEquals(errorType, restconfError.getErrorType());
+            assertEquals(errorTag, restconfError.getErrorTag());
+        }
+    }
+
+}
index 158569af7386eb35081ba046af00d96b0de08d96..7c354acc4077a4c1d50ad9da0d27e3a009973127 100644 (file)
@@ -11,7 +11,6 @@ import static org.junit.Assert.assertNotNull;
 
 import java.net.URI;
 import java.net.URISyntaxException;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
@@ -26,7 +25,7 @@ public class NormalizeNodeTest extends YangAndXmlAndDataSchemaLoader {
         dataLoad("/normalize-node/yang/");
     }
 
-    @Test(expected=RestconfDocumentedException.class)
+    @Test(expected = RestconfDocumentedException.class)
     public void namespaceNotNullAndInvalidNamespaceAndNoModuleNameTest() {
 
         TestUtils.normalizeCompositeNode(prepareCnSn("wrongnamespace"), modules, schemaNodePath);
index 024a93b78e7e2a52e76059b198363fec003ababd..4000c7cc807f7e62c3583649ee3d04e2acd32f53 100644 (file)
@@ -12,7 +12,6 @@ import static org.junit.Assert.assertNull;
 import static org.mockito.Mockito.mock;
 
 import java.util.Collections;
-
 import org.junit.Test;
 import org.opendaylight.controller.sal.restconf.impl.RestCodec;
 import org.opendaylight.yangtools.concepts.Codec;
@@ -28,7 +27,7 @@ public class RestCodecExceptionsTest {
 
     @Test
     public void serializeExceptionTest() {
-        Codec<Object, Object> codec = RestCodec.from(BitsType.create(PATH, Collections.<Bit>emptyList()), null);
+        Codec<Object, Object> codec = RestCodec.from(BitsType.create(PATH, Collections.<Bit> emptyList()), null);
         String serializedValue = (String) codec.serialize("incorrect value"); // set
                                                                               // expected
         assertEquals("incorrect value", serializedValue);
index e8cbf3140f35f9f750612ddc5c932a8763034a4b..d1d2a5babf5bcbd554b1f5612979c59b2c032730 100644 (file)
@@ -57,10 +57,10 @@ public class RestDeleteOperationTest extends JerseyTest {
     @Override
     protected Application configure() {
         /* enable/disable Jersey logs to console */
-//        enable(TestProperties.LOG_TRAFFIC);
-//        enable(TestProperties.DUMP_ENTITY);
-//        enable(TestProperties.RECORD_LOG_LEVEL);
-//        set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
+        // enable(TestProperties.LOG_TRAFFIC);
+        // enable(TestProperties.DUMP_ENTITY);
+        // enable(TestProperties.RECORD_LOG_LEVEL);
+        // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
         ResourceConfig resourceConfig = new ResourceConfig();
         resourceConfig = resourceConfig.registerInstances(restconfImpl, StructuredDataToXmlProvider.INSTANCE,
                 XmlToCompositeNodeProvider.INSTANCE);
@@ -82,7 +82,8 @@ public class RestDeleteOperationTest extends JerseyTest {
     }
 
     private Future<RpcResult<TransactionStatus>> createFuture(TransactionStatus statusName) {
-        RpcResult<TransactionStatus> rpcResult = new DummyRpcResult.Builder<TransactionStatus>().result(statusName).build();
+        RpcResult<TransactionStatus> rpcResult = new DummyRpcResult.Builder<TransactionStatus>().result(statusName)
+                .build();
         return new DummyFuture.Builder<TransactionStatus>().rpcResult(rpcResult).build();
     }
 
index 53183c611cf54329d5555b2de8b56b01cedfdf0d..bab06e92451985b5a0d95032e99174adb91ba4b0 100644 (file)
@@ -12,7 +12,6 @@ import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
 import java.io.FileNotFoundException;
-
 import org.junit.BeforeClass;
 import org.junit.Rule;
 import org.junit.Test;
@@ -47,10 +46,9 @@ public class RestGetAugmentedElementWhenEqualNamesTest {
     public void nodeWithoutNamespaceHasMoreAugments() {
         try {
             controllerContext.toInstanceIdentifier("main:cont/cont1");
-            fail( "Expected exception" );
+            fail("Expected exception");
         } catch (RestconfDocumentedException e) {
-            assertTrue(e.getErrors().get( 0 ).getErrorMessage().contains(
-                                    "is added as augment from more than one module"));
+            assertTrue(e.getErrors().get(0).getErrorMessage().contains("is added as augment from more than one module"));
         }
     }
 }
index f0a232fba670539c5a872e5894a89bd7c214c778..536d140cf1b78e05b7a3e77d38e43a32d8a1f8f4 100644 (file)
@@ -7,8 +7,9 @@
  */
 package org.opendaylight.controller.sal.restconf.impl.test;
 
-import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 import static org.mockito.Matchers.any;
@@ -16,6 +17,8 @@ import static org.mockito.Matchers.eq;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
 import java.io.FileNotFoundException;
 import java.io.InputStream;
 import java.io.UnsupportedEncodingException;
@@ -29,14 +32,12 @@ import java.util.List;
 import java.util.Map;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
-
 import javax.ws.rs.core.Application;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.MultivaluedHashMap;
 import javax.ws.rs.core.MultivaluedMap;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.UriInfo;
-
 import org.glassfish.jersey.server.ResourceConfig;
 import org.glassfish.jersey.test.JerseyTest;
 import org.junit.BeforeClass;
@@ -68,16 +69,13 @@ import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.w3c.dom.NodeList;
 
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-
 public class RestGetOperationTest extends JerseyTest {
 
     static class NodeData {
         Object key;
         Object data; // List for a CompositeNode, value Object for a SimpleNode
 
-        NodeData( Object key, Object data ) {
+        NodeData(final Object key, final Object data) {
             this.key = key;
             this.data = data;
         }
@@ -119,7 +117,7 @@ public class RestGetOperationTest extends JerseyTest {
         resourceConfig = resourceConfig.registerInstances(restconfImpl, StructuredDataToXmlProvider.INSTANCE,
                 StructuredDataToJsonProvider.INSTANCE, XmlToCompositeNodeProvider.INSTANCE,
                 JsonToCompositeNodeProvider.INSTANCE);
-        resourceConfig.registerClasses( RestconfDocumentedExceptionMapper.class );
+        resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
         return resourceConfig;
     }
 
@@ -174,12 +172,11 @@ public class RestGetOperationTest extends JerseyTest {
     /**
      * MountPoint test. URI represents mount point.
      *
-     * Slashes in URI behind mount point. lst1 element with key
-     * GigabitEthernet0%2F0%2F0%2F0 (GigabitEthernet0/0/0/0) is requested via
-     * GET HTTP operation. It is tested whether %2F character is replaced with
-     * simple / in InstanceIdentifier parameter in method
-     * {@link BrokerFacade#readConfigurationDataBehindMountPoint(MountInstance, InstanceIdentifier)}
-     * which is called in method {@link RestconfImpl#readConfigurationData}
+     * Slashes in URI behind mount point. lst1 element with key GigabitEthernet0%2F0%2F0%2F0 (GigabitEthernet0/0/0/0) is
+     * requested via GET HTTP operation. It is tested whether %2F character is replaced with simple / in
+     * InstanceIdentifier parameter in method
+     * {@link BrokerFacade#readConfigurationDataBehindMountPoint(MountInstance, InstanceIdentifier)} which is called in
+     * method {@link RestconfImpl#readConfigurationData}
      *
      *
      * @throws ParseException
@@ -214,7 +211,7 @@ public class RestGetOperationTest extends JerseyTest {
         parameters.add(new InstanceIdentifier.NodeIdentifier(qNameCont));
         parameters.add(new InstanceIdentifier.NodeIdentifierWithPredicates(qNameList, qNameKeyList,
                 "GigabitEthernet0/0/0/0"));
-        return new InstanceIdentifier(parameters);
+        return InstanceIdentifier.create(parameters);
     }
 
     @Test
@@ -356,7 +353,7 @@ public class RestGetOperationTest extends JerseyTest {
 
     }
 
-    private Matcher validateOperationsResponseJson(String searchIn, String rpcName, String moduleName) {
+    private Matcher validateOperationsResponseJson(final String searchIn, final String rpcName, final String moduleName) {
         StringBuilder regex = new StringBuilder();
         regex.append("^");
 
@@ -390,7 +387,7 @@ public class RestGetOperationTest extends JerseyTest {
 
     }
 
-    private Matcher validateOperationsResponseXml(String searchIn, String rpcName, String namespace) {
+    private Matcher validateOperationsResponseXml(final String searchIn, final String rpcName, final String namespace) {
         StringBuilder regex = new StringBuilder();
 
         regex.append("^");
@@ -494,7 +491,7 @@ public class RestGetOperationTest extends JerseyTest {
 
     }
 
-    private void validateModulesResponseXml(Response response) {
+    private void validateModulesResponseXml(final Response response) {
         assertEquals(200, response.getStatus());
         String responseBody = response.readEntity(String.class);
 
@@ -506,7 +503,7 @@ public class RestGetOperationTest extends JerseyTest {
                 .find());
     }
 
-    private void validateModulesResponseJson(Response response) {
+    private void validateModulesResponseJson(final Response response) {
         assertEquals(200, response.getStatus());
         String responseBody = response.readEntity(String.class);
 
@@ -518,7 +515,8 @@ public class RestGetOperationTest extends JerseyTest {
                 .find());
     }
 
-    private Matcher prepareJsonRegex(String module, String revision, String namespace, String searchIn) {
+    private Matcher prepareJsonRegex(final String module, final String revision, final String namespace,
+            final String searchIn) {
         StringBuilder regex = new StringBuilder();
         regex.append("^");
 
@@ -544,7 +542,8 @@ public class RestGetOperationTest extends JerseyTest {
 
     }
 
-    private Matcher prepareXmlRegex(String module, String revision, String namespace, String searchIn) {
+    private Matcher prepareXmlRegex(final String module, final String revision, final String namespace,
+            final String searchIn) {
         StringBuilder regex = new StringBuilder();
         regex.append("^");
 
@@ -572,13 +571,14 @@ public class RestGetOperationTest extends JerseyTest {
         return ptrn.matcher(searchIn);
     }
 
-    private void prepareMockForModulesTest(ControllerContext mockedControllerContext) throws FileNotFoundException {
+    private void prepareMockForModulesTest(final ControllerContext mockedControllerContext)
+            throws FileNotFoundException {
         SchemaContext schemaContext = TestUtils.loadSchemaContext("/modules");
         mockedControllerContext.setGlobalSchema(schemaContext);
         // when(mockedControllerContext.getGlobalSchema()).thenReturn(schemaContext);
     }
 
-    private int get(String uri, String mediaType) {
+    private int get(final String uri, final String mediaType) {
         return target(uri).request(mediaType).get().getStatus();
     }
 
@@ -615,314 +615,325 @@ public class RestGetOperationTest extends JerseyTest {
         return null;
     }
 
+    /**
+     * If includeWhiteChars URI parameter is set to false then no white characters can be included in returned output
+     *
+     * @throws UnsupportedEncodingException
+     */
+    @Test
+    public void getDataWithUriIncludeWhiteCharsParameterTest() throws UnsupportedEncodingException {
+        getDataWithUriIncludeWhiteCharsParameter("config");
+        getDataWithUriIncludeWhiteCharsParameter("operational");
+    }
+
+    private void getDataWithUriIncludeWhiteCharsParameter(String target) throws UnsupportedEncodingException {
+        mockReadConfigurationDataMethod();
+        String uri = "/" + target + "/ietf-interfaces:interfaces/interface/eth0";
+        Response response = target(uri).queryParam("prettyPrint", "false").request("application/xml").get();
+        String xmlData = response.readEntity(String.class);
+
+        Pattern pattern = Pattern.compile(".*(>\\s+|\\s+<).*", Pattern.DOTALL);
+        Matcher matcher = pattern.matcher(xmlData);
+        // XML element can't surrounded with white character (e.g ">    " or
+        // "    <")
+        assertFalse(matcher.matches());
+
+        response = target(uri).queryParam("prettyPrint", "false").request("application/json").get();
+        String jsonData = response.readEntity(String.class);
+        pattern = Pattern.compile(".*(\\}\\s+|\\s+\\{|\\]\\s+|\\s+\\[|\\s+:|:\\s+).*", Pattern.DOTALL);
+        matcher = pattern.matcher(jsonData);
+        // JSON element can't surrounded with white character (e.g "} ", " {",
+        // "] ", " [", " :" or ": ")
+        assertFalse(matcher.matches());
+    }
+
     @Test
     public void getDataWithUriDepthParameterTest() throws UnsupportedEncodingException {
 
-        ControllerContext.getInstance().setGlobalSchema( schemaContextModules );
-
-        CompositeNode depth1Cont = toCompositeNode(
-            toCompositeNodeData( toNestedQName( "depth1-cont" ),
-                toCompositeNodeData( toNestedQName( "depth2-cont1" ),
-                    toCompositeNodeData( toNestedQName( "depth3-cont1" ),
-                        toCompositeNodeData( toNestedQName( "depth4-cont1" ),
-                            toSimpleNodeData( toNestedQName( "depth5-leaf1" ), "depth5-leaf1-value" )
-                        ),
-                        toSimpleNodeData( toNestedQName( "depth4-leaf1" ), "depth4-leaf1-value" )
-                    ),
-                    toSimpleNodeData( toNestedQName( "depth3-leaf1" ), "depth3-leaf1-value" )
-                ),
-                toCompositeNodeData( toNestedQName( "depth2-cont2" ),
-                    toCompositeNodeData( toNestedQName( "depth3-cont2" ),
-                        toCompositeNodeData( toNestedQName( "depth4-cont2" ),
-                            toSimpleNodeData( toNestedQName( "depth5-leaf2" ), "depth5-leaf2-value" )
-                        ),
-                        toSimpleNodeData( toNestedQName( "depth4-leaf2" ), "depth4-leaf2-value" )
-                    ),
-                    toSimpleNodeData( toNestedQName( "depth3-leaf2" ), "depth3-leaf2-value" )
-                ),
-                toSimpleNodeData( toNestedQName( "depth2-leaf1" ), "depth2-leaf1-value" )
-            ) );
-
-        when( brokerFacade.readConfigurationData( any( InstanceIdentifier.class ) ) )
-            .thenReturn( depth1Cont );
+        ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
+
+        CompositeNode depth1Cont = toCompositeNode(toCompositeNodeData(
+                toNestedQName("depth1-cont"),
+                toCompositeNodeData(
+                        toNestedQName("depth2-cont1"),
+                        toCompositeNodeData(
+                                toNestedQName("depth3-cont1"),
+                                toCompositeNodeData(toNestedQName("depth4-cont1"),
+                                        toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
+                                toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
+                        toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")),
+                toCompositeNodeData(
+                        toNestedQName("depth2-cont2"),
+                        toCompositeNodeData(
+                                toNestedQName("depth3-cont2"),
+                                toCompositeNodeData(toNestedQName("depth4-cont2"),
+                                        toSimpleNodeData(toNestedQName("depth5-leaf2"), "depth5-leaf2-value")),
+                                toSimpleNodeData(toNestedQName("depth4-leaf2"), "depth4-leaf2-value")),
+                        toSimpleNodeData(toNestedQName("depth3-leaf2"), "depth3-leaf2-value")),
+                toSimpleNodeData(toNestedQName("depth2-leaf1"), "depth2-leaf1-value")));
+
+        when(brokerFacade.readConfigurationData(any(InstanceIdentifier.class))).thenReturn(depth1Cont);
 
         // Test config with depth 1
 
-        Response response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "1" )
-                                .request( "application/xml" ).get();
+        Response response = target("/config/nested-module:depth1-cont").queryParam("depth", "1")
+                .request("application/xml").get();
 
-        verifyXMLResponse( response, expectEmptyContainer( "depth1-cont" ) );
+        verifyXMLResponse(response, expectEmptyContainer("depth1-cont"));
 
         // Test config with depth 2
 
-        response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "2" )
-                       .request( "application/xml" ).get();
+        response = target("/config/nested-module:depth1-cont").queryParam("depth", "2").request("application/xml")
+                .get();
 
-//        String xml="<depth1-cont><depth2-cont1/><depth2-cont2/><depth2-leaf1>depth2-leaf1-value</depth2-leaf1></depth1-cont>";
-//        Response mr=mock(Response.class);
-//        when(mr.getEntity()).thenReturn( new java.io.StringBufferInputStream(xml) );
+        // String
+        // xml="<depth1-cont><depth2-cont1/><depth2-cont2/><depth2-leaf1>depth2-leaf1-value</depth2-leaf1></depth1-cont>";
+        // Response mr=mock(Response.class);
+        // when(mr.getEntity()).thenReturn( new
+        // java.io.StringBufferInputStream(xml) );
 
-        verifyXMLResponse( response,
-            expectContainer( "depth1-cont",
-                expectEmptyContainer( "depth2-cont1" ),
-                expectEmptyContainer( "depth2-cont2" ),
-                expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
-            ) );
+        verifyXMLResponse(
+                response,
+                expectContainer("depth1-cont", expectEmptyContainer("depth2-cont1"),
+                        expectEmptyContainer("depth2-cont2"), expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
 
         // Test config with depth 3
 
-        response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "3" )
-                       .request( "application/xml" ).get();
-
-        verifyXMLResponse( response,
-            expectContainer( "depth1-cont",
-                expectContainer( "depth2-cont1",
-                    expectEmptyContainer( "depth3-cont1" ),
-                    expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
-                ),
-                expectContainer( "depth2-cont2",
-                    expectEmptyContainer( "depth3-cont2" ),
-                    expectLeaf( "depth3-leaf2", "depth3-leaf2-value" )
-                ),
-                expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
-           ) );
+        response = target("/config/nested-module:depth1-cont").queryParam("depth", "3").request("application/xml")
+                .get();
+
+        verifyXMLResponse(
+                response,
+                expectContainer(
+                        "depth1-cont",
+                        expectContainer("depth2-cont1", expectEmptyContainer("depth3-cont1"),
+                                expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
+                        expectContainer("depth2-cont2", expectEmptyContainer("depth3-cont2"),
+                                expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
+                        expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
 
         // Test config with depth 4
 
-        response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "4" )
-                      .request( "application/xml" ).get();
-
-        verifyXMLResponse( response,
-            expectContainer( "depth1-cont",
-                expectContainer( "depth2-cont1",
-                    expectContainer( "depth3-cont1",
-                        expectEmptyContainer( "depth4-cont1" ),
-                        expectLeaf( "depth4-leaf1", "depth4-leaf1-value" )
-                    ),
-                    expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
-                ),
-                expectContainer( "depth2-cont2",
-                    expectContainer( "depth3-cont2",
-                        expectEmptyContainer( "depth4-cont2" ),
-                        expectLeaf( "depth4-leaf2", "depth4-leaf2-value" )
-                    ),
-                    expectLeaf( "depth3-leaf2", "depth3-leaf2-value" )
-                ),
-                expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
-            ) );
+        response = target("/config/nested-module:depth1-cont").queryParam("depth", "4").request("application/xml")
+                .get();
+
+        verifyXMLResponse(
+                response,
+                expectContainer(
+                        "depth1-cont",
+                        expectContainer(
+                                "depth2-cont1",
+                                expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
+                                        expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
+                                expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
+                        expectContainer(
+                                "depth2-cont2",
+                                expectContainer("depth3-cont2", expectEmptyContainer("depth4-cont2"),
+                                        expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
+                                expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
+                        expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
 
         // Test config with depth 5
 
-        response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "5" )
-                       .request( "application/xml" ).get();
-
-        verifyXMLResponse( response,
-            expectContainer( "depth1-cont",
-                expectContainer( "depth2-cont1",
-                    expectContainer( "depth3-cont1",
-                        expectContainer( "depth4-cont1",
-                            expectLeaf( "depth5-leaf1", "depth5-leaf1-value" )
-                        ),
-                        expectLeaf( "depth4-leaf1", "depth4-leaf1-value" )
-                    ),
-                    expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
-                ),
-                expectContainer( "depth2-cont2",
-                    expectContainer( "depth3-cont2",
-                        expectContainer( "depth4-cont2",
-                            expectLeaf( "depth5-leaf2", "depth5-leaf2-value" )
-                        ),
-                        expectLeaf( "depth4-leaf2", "depth4-leaf2-value" )
-                    ),
-                    expectLeaf( "depth3-leaf2", "depth3-leaf2-value" )
-                ),
-                expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
-            ) );
+        response = target("/config/nested-module:depth1-cont").queryParam("depth", "5").request("application/xml")
+                .get();
+
+        verifyXMLResponse(
+                response,
+                expectContainer(
+                        "depth1-cont",
+                        expectContainer(
+                                "depth2-cont1",
+                                expectContainer(
+                                        "depth3-cont1",
+                                        expectContainer("depth4-cont1",
+                                                expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
+                                        expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
+                                expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
+                        expectContainer(
+                                "depth2-cont2",
+                                expectContainer(
+                                        "depth3-cont2",
+                                        expectContainer("depth4-cont2",
+                                                expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
+                                        expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
+                                expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
+                        expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
 
         // Test config with depth unbounded
 
-        response = target( "/config/nested-module:depth1-cont" ).queryParam( "depth", "unbounded" )
-                       .request( "application/xml" ).get();
-
-        verifyXMLResponse( response,
-            expectContainer( "depth1-cont",
-                expectContainer( "depth2-cont1",
-                    expectContainer( "depth3-cont1",
-                        expectContainer( "depth4-cont1",
-                            expectLeaf( "depth5-leaf1", "depth5-leaf1-value" )
-                        ),
-                        expectLeaf( "depth4-leaf1", "depth4-leaf1-value" )
-                    ),
-                    expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
-                ),
-                expectContainer( "depth2-cont2",
-                    expectContainer( "depth3-cont2",
-                        expectContainer( "depth4-cont2",
-                            expectLeaf( "depth5-leaf2", "depth5-leaf2-value" )
-                        ),
-                        expectLeaf( "depth4-leaf2", "depth4-leaf2-value" )
-                    ),
-                    expectLeaf( "depth3-leaf2", "depth3-leaf2-value" )
-                ),
-                expectLeaf( "depth2-leaf1", "depth2-leaf1-value" )
-            ) );
+        response = target("/config/nested-module:depth1-cont").queryParam("depth", "unbounded")
+                .request("application/xml").get();
+
+        verifyXMLResponse(
+                response,
+                expectContainer(
+                        "depth1-cont",
+                        expectContainer(
+                                "depth2-cont1",
+                                expectContainer(
+                                        "depth3-cont1",
+                                        expectContainer("depth4-cont1",
+                                                expectLeaf("depth5-leaf1", "depth5-leaf1-value")),
+                                        expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
+                                expectLeaf("depth3-leaf1", "depth3-leaf1-value")),
+                        expectContainer(
+                                "depth2-cont2",
+                                expectContainer(
+                                        "depth3-cont2",
+                                        expectContainer("depth4-cont2",
+                                                expectLeaf("depth5-leaf2", "depth5-leaf2-value")),
+                                        expectLeaf("depth4-leaf2", "depth4-leaf2-value")),
+                                expectLeaf("depth3-leaf2", "depth3-leaf2-value")),
+                        expectLeaf("depth2-leaf1", "depth2-leaf1-value")));
 
         // Test operational
 
-        CompositeNode depth2Cont1 = toCompositeNode(
-            toCompositeNodeData( toNestedQName( "depth2-cont1" ),
-                toCompositeNodeData( toNestedQName( "depth3-cont1" ),
-                    toCompositeNodeData( toNestedQName( "depth4-cont1" ),
-                        toSimpleNodeData( toNestedQName( "depth5-leaf1" ), "depth5-leaf1-value" )
-                    ),
-                    toSimpleNodeData( toNestedQName( "depth4-leaf1" ), "depth4-leaf1-value" )
-                ),
-                toSimpleNodeData( toNestedQName( "depth3-leaf1" ), "depth3-leaf1-value" )
-            ) );
-
-        when( brokerFacade.readOperationalData( any( InstanceIdentifier.class ) ) )
-             .thenReturn( depth2Cont1 );
-
-        response = target( "/operational/nested-module:depth1-cont/depth2-cont1" )
-                       .queryParam( "depth", "3" ).request( "application/xml" ).get();
-
-        verifyXMLResponse( response,
-            expectContainer( "depth2-cont1",
-                expectContainer( "depth3-cont1",
-                    expectEmptyContainer( "depth4-cont1" ),
-                    expectLeaf( "depth4-leaf1", "depth4-leaf1-value" )
-                ),
-                expectLeaf( "depth3-leaf1", "depth3-leaf1-value" )
-            ) );
+        CompositeNode depth2Cont1 = toCompositeNode(toCompositeNodeData(
+                toNestedQName("depth2-cont1"),
+                toCompositeNodeData(
+                        toNestedQName("depth3-cont1"),
+                        toCompositeNodeData(toNestedQName("depth4-cont1"),
+                                toSimpleNodeData(toNestedQName("depth5-leaf1"), "depth5-leaf1-value")),
+                        toSimpleNodeData(toNestedQName("depth4-leaf1"), "depth4-leaf1-value")),
+                toSimpleNodeData(toNestedQName("depth3-leaf1"), "depth3-leaf1-value")));
+
+        when(brokerFacade.readOperationalData(any(InstanceIdentifier.class))).thenReturn(depth2Cont1);
+
+        response = target("/operational/nested-module:depth1-cont/depth2-cont1").queryParam("depth", "3")
+                .request("application/xml").get();
+
+        verifyXMLResponse(
+                response,
+                expectContainer(
+                        "depth2-cont1",
+                        expectContainer("depth3-cont1", expectEmptyContainer("depth4-cont1"),
+                                expectLeaf("depth4-leaf1", "depth4-leaf1-value")),
+                        expectLeaf("depth3-leaf1", "depth3-leaf1-value")));
     }
 
     @Test
     public void getDataWithInvalidDepthParameterTest() {
 
-        ControllerContext.getInstance().setGlobalSchema( schemaContextModules );
+        ControllerContext.getInstance().setGlobalSchema(schemaContextModules);
 
-        final MultivaluedMap<String,String> paramMap = new MultivaluedHashMap<>();
-        paramMap.putSingle( "depth", "1o" );
-        UriInfo mockInfo = mock( UriInfo.class );
-        when( mockInfo.getQueryParameters( false ) ).thenAnswer(
-            new Answer<MultivaluedMap<String,String>>() {
-                @Override
-                public MultivaluedMap<String, String> answer( InvocationOnMock invocation ) {
-                    return paramMap;
-                }
-            } );
+        final MultivaluedMap<String, String> paramMap = new MultivaluedHashMap<>();
+        paramMap.putSingle("depth", "1o");
+        UriInfo mockInfo = mock(UriInfo.class);
+        when(mockInfo.getQueryParameters(false)).thenAnswer(new Answer<MultivaluedMap<String, String>>() {
+            @Override
+            public MultivaluedMap<String, String> answer(final InvocationOnMock invocation) {
+                return paramMap;
+            }
+        });
 
-        getDataWithInvalidDepthParameterTest( mockInfo );
+        getDataWithInvalidDepthParameterTest(mockInfo);
 
-        paramMap.putSingle( "depth", "0" );
-        getDataWithInvalidDepthParameterTest( mockInfo );
+        paramMap.putSingle("depth", "0");
+        getDataWithInvalidDepthParameterTest(mockInfo);
 
-        paramMap.putSingle( "depth", "-1" );
-        getDataWithInvalidDepthParameterTest( mockInfo );
+        paramMap.putSingle("depth", "-1");
+        getDataWithInvalidDepthParameterTest(mockInfo);
     }
 
-    private void getDataWithInvalidDepthParameterTest( UriInfo uriInfo ) {
+    private void getDataWithInvalidDepthParameterTest(final UriInfo uriInfo) {
         try {
-            restconfImpl.readConfigurationData( "nested-module:depth1-cont", uriInfo );
-            fail( "Expected RestconfDocumentedException" );
-        }
-        catch( RestconfDocumentedException e ) {
-            assertTrue( "Unexpected error message: " + e.getErrors().get( 0 ).getErrorMessage(),
-                        e.getErrors().get( 0 ).getErrorMessage().contains( "depth" ) );
+            restconfImpl.readConfigurationData("nested-module:depth1-cont", uriInfo);
+            fail("Expected RestconfDocumentedException");
+        } catch (RestconfDocumentedException e) {
+            assertTrue("Unexpected error message: " + e.getErrors().get(0).getErrorMessage(), e.getErrors().get(0)
+                    .getErrorMessage().contains("depth"));
         }
     }
 
-    private void verifyXMLResponse( Response response, NodeData nodeData ) {
+    private void verifyXMLResponse(final Response response, final NodeData nodeData) {
 
-        Document doc = TestUtils.loadDocumentFrom( (InputStream) response.getEntity() );
-        assertNotNull( "Could not parse XML document", doc );
+        Document doc = TestUtils.loadDocumentFrom((InputStream) response.getEntity());
+        assertNotNull("Could not parse XML document", doc);
 
-        //System.out.println(TestUtils.getDocumentInPrintableForm( doc ));
+        // System.out.println(TestUtils.getDocumentInPrintableForm( doc ));
 
-        verifyContainerElement( doc.getDocumentElement(), nodeData );
+        verifyContainerElement(doc.getDocumentElement(), nodeData);
     }
 
     @SuppressWarnings("unchecked")
-    private void verifyContainerElement( Element element, NodeData nodeData ) {
+    private void verifyContainerElement(final Element element, final NodeData nodeData) {
 
-        assertEquals( "Element local name", nodeData.key, element.getNodeName() );
+        assertEquals("Element local name", nodeData.key, element.getNodeName());
 
         NodeList childNodes = element.getChildNodes();
-        if( nodeData.data == null ) { // empty container
-            assertTrue( "Expected no child elements for \"" + element.getNodeName() + "\"",
-                        childNodes.getLength() == 0 );
+        if (nodeData.data == null) { // empty container
+            assertTrue("Expected no child elements for \"" + element.getNodeName() + "\"", childNodes.getLength() == 0);
             return;
         }
 
-        Map<String,NodeData> expChildMap = Maps.newHashMap();
-        for( NodeData expChild: (List<NodeData>)nodeData.data ) {
-            expChildMap.put( expChild.key.toString(), expChild );
+        Map<String, NodeData> expChildMap = Maps.newHashMap();
+        for (NodeData expChild : (List<NodeData>) nodeData.data) {
+            expChildMap.put(expChild.key.toString(), expChild);
         }
 
-        for( int i = 0; i < childNodes.getLength(); i++ ) {
-            org.w3c.dom.Node actualChild = childNodes.item( i );
-            if( !( actualChild instanceof Element ) ) {
+        for (int i = 0; i < childNodes.getLength(); i++) {
+            org.w3c.dom.Node actualChild = childNodes.item(i);
+            if (!(actualChild instanceof Element)) {
                 continue;
             }
 
-            Element actualElement = (Element)actualChild;
-            NodeData expChild = expChildMap.remove( actualElement.getNodeName() );
-            assertNotNull( "Unexpected child element for parent \"" + element.getNodeName() +
-                           "\": " + actualElement.getNodeName(), expChild );
-
-            if( expChild.data == null || expChild.data instanceof List ) {
-                verifyContainerElement( actualElement, expChild );
-            }
-            else {
-                assertEquals( "Text content for element: " + actualElement.getNodeName(),
-                              expChild.data, actualElement.getTextContent() );
+            Element actualElement = (Element) actualChild;
+            NodeData expChild = expChildMap.remove(actualElement.getNodeName());
+            assertNotNull(
+                    "Unexpected child element for parent \"" + element.getNodeName() + "\": "
+                            + actualElement.getNodeName(), expChild);
+
+            if (expChild.data == null || expChild.data instanceof List) {
+                verifyContainerElement(actualElement, expChild);
+            else {
+                assertEquals("Text content for element: " + actualElement.getNodeName(), expChild.data,
+                        actualElement.getTextContent());
             }
         }
 
-        if( !expChildMap.isEmpty() ) {
-            fail( "Missing elements for parent \"" + element.getNodeName() +
-                  "\": " + expChildMap.keySet() );
+        if (!expChildMap.isEmpty()) {
+            fail("Missing elements for parent \"" + element.getNodeName() + "\": " + expChildMap.keySet());
         }
     }
 
-    private NodeData expectContainer( String name, NodeData... childData ) {
-        return new NodeData( name, Lists.newArrayList( childData ) );
+    private NodeData expectContainer(final String name, final NodeData... childData) {
+        return new NodeData(name, Lists.newArrayList(childData));
     }
 
-    private NodeData expectEmptyContainer( String name ) {
-        return new NodeData( name, null );
+    private NodeData expectEmptyContainer(final String name) {
+        return new NodeData(name, null);
     }
 
-    private NodeData expectLeaf( String name, Object value ) {
-        return new NodeData( name, value );
+    private NodeData expectLeaf(final String name, final Object value) {
+        return new NodeData(name, value);
     }
 
-    private QName toNestedQName( String localName ) {
-        return QName.create( "urn:nested:module", "2014-06-3", localName );
+    private QName toNestedQName(final String localName) {
+        return QName.create("urn:nested:module", "2014-06-3", localName);
     }
 
     @SuppressWarnings("unchecked")
-    private CompositeNode toCompositeNode( NodeData nodeData ) {
+    private CompositeNode toCompositeNode(final NodeData nodeData) {
         CompositeNodeBuilder<ImmutableCompositeNode> builder = ImmutableCompositeNode.builder();
-        builder.setQName( (QName) nodeData.key );
+        builder.setQName((QName) nodeData.key);
 
-        for( NodeData child: (List<NodeData>)nodeData.data ) {
-            if( child.data instanceof List ) {
-                builder.add( toCompositeNode( child ) );
-            }
-            else {
-                builder.addLeaf( (QName) child.key, child.data );
+        for (NodeData child : (List<NodeData>) nodeData.data) {
+            if (child.data instanceof List) {
+                builder.add(toCompositeNode(child));
+            } else {
+                builder.addLeaf((QName) child.key, child.data);
             }
         }
 
         return builder.toInstance();
     }
 
-    private NodeData toCompositeNodeData( QName key, NodeData... childData ) {
-        return new NodeData( key, Lists.newArrayList( childData ) );
+    private NodeData toCompositeNodeData(final QName key, final NodeData... childData) {
+        return new NodeData(key, Lists.newArrayList(childData));
     }
 
-    private NodeData toSimpleNodeData( QName key, Object value ) {
-        return new NodeData( key, value );
+    private NodeData toSimpleNodeData(final QName key, final Object value) {
+        return new NodeData(key, value);
     }
 }
index 5b36fd52f78c329649fb3d593034d6bf028031f0..af9dd283594ea3943f9265e5a2ecade495a85e7f 100644 (file)
@@ -37,7 +37,6 @@ import org.junit.BeforeClass;
 import org.junit.Test;
 import org.mockito.ArgumentCaptor;
 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
-import org.opendaylight.controller.sal.common.util.RpcErrors;
 import org.opendaylight.controller.sal.core.api.mount.MountInstance;
 import org.opendaylight.controller.sal.core.api.mount.MountService;
 import org.opendaylight.controller.sal.rest.api.Draft02;
@@ -52,7 +51,7 @@ import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
 import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.RpcError;
-import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
@@ -125,10 +124,12 @@ public class RestPostOperationTest extends JerseyTest {
         assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
 
         List<RpcError> rpcErrors = new ArrayList<>();
-        rpcErrors.add( RpcErrors.getRpcError("applicationTag1", "tag1", "info1", ErrorSeverity.ERROR, "message1", ErrorType.RPC, null));
-        rpcErrors.add( RpcErrors.getRpcError("applicationTag2", "tag2", "info2", ErrorSeverity.WARNING, "message2", ErrorType.PROTOCOL, null));
+        rpcErrors.add( RpcResultBuilder.newError( ErrorType.RPC, "tag1", "message1",
+                                                  "applicationTag1", "info1", null ) );
+        rpcErrors.add( RpcResultBuilder.newWarning( ErrorType.PROTOCOL, "tag2", "message2",
+                                                    "applicationTag2", "info2", null ) );
         mockInvokeRpc(null, false, rpcErrors);
-        assertEquals(500,post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
+        assertEquals(500, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
 
         uri = "/operations/test-module:rpc-wrongtest";
         assertEquals(400, post(uri, MediaType.APPLICATION_XML, xmlDataRpcInput));
@@ -198,8 +199,8 @@ public class RestPostOperationTest extends JerseyTest {
             builder.errors(errors);
         }
         RpcResult<CompositeNode> rpcResult = builder.build();
-        when(brokerFacade.invokeRpc(any(QName.class), any(CompositeNode.class)))
-                .thenReturn(Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
+        when(brokerFacade.invokeRpc(any(QName.class), any(CompositeNode.class))).thenReturn(
+                Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
     }
 
     private void mockInvokeRpc(CompositeNode result, boolean sucessful) {
index e146cf8f4fa165a4d3234b616e3bbad1516004e1..b8c0270a61407a8358a741abe2515bc83395ef60 100644 (file)
@@ -9,6 +9,7 @@
 package org.opendaylight.controller.sal.restconf.impl.test;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
@@ -18,6 +19,12 @@ import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.reset;
 import static org.mockito.Mockito.when;
 
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Maps;
+import com.google.common.io.ByteStreams;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonElement;
+import com.google.gson.JsonParser;
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
@@ -29,7 +36,8 @@ import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;
-
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 import javax.ws.rs.core.Application;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
@@ -41,7 +49,6 @@ import javax.xml.xpath.XPath;
 import javax.xml.xpath.XPathConstants;
 import javax.xml.xpath.XPathExpression;
 import javax.xml.xpath.XPathFactory;
-
 import org.glassfish.jersey.server.ResourceConfig;
 import org.glassfish.jersey.test.JerseyTest;
 import org.junit.Before;
@@ -63,13 +70,6 @@ import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Maps;
-import com.google.common.io.ByteStreams;
-import com.google.gson.JsonArray;
-import com.google.gson.JsonElement;
-import com.google.gson.JsonParser;
-
 /**
  * Unit tests for RestconfDocumentedExceptionMapper.
  *
@@ -78,63 +78,61 @@ import com.google.gson.JsonParser;
 public class RestconfDocumentedExceptionMapperTest extends JerseyTest {
 
     interface ErrorInfoVerifier {
-        void verifyXML( Node errorInfoNode );
-        void verifyJson( JsonElement errorInfoElement );
+        void verifyXML(Node errorInfoNode);
+
+        void verifyJson(JsonElement errorInfoElement);
     }
 
     static class ComplexErrorInfoVerifier implements ErrorInfoVerifier {
 
         Map<String, String> expErrorInfo;
 
-        public ComplexErrorInfoVerifier( final Map<String, String> expErrorInfo ) {
+        public ComplexErrorInfoVerifier(final Map<String, String> expErrorInfo) {
             this.expErrorInfo = expErrorInfo;
         }
 
         @Override
-        public void verifyXML( final Node errorInfoNode ) {
+        public void verifyXML(final Node errorInfoNode) {
 
-            Map<String, String> mutableExpMap = Maps.newHashMap( expErrorInfo );
+            Map<String, String> mutableExpMap = Maps.newHashMap(expErrorInfo);
             NodeList childNodes = errorInfoNode.getChildNodes();
-            for( int i = 0; i < childNodes.getLength(); i++ ) {
-                Node child = childNodes.item( i );
-                if( child  instanceof Element ) {
-                    String expValue = mutableExpMap.remove( child.getNodeName() );
-                    assertNotNull( "Found unexpected \"error-info\" child node: " +
-                            child.getNodeName(), expValue );
-                    assertEquals( "Text content for \"error-info\" child node " +
-                            child.getNodeName(), expValue, child.getTextContent() );
+            for (int i = 0; i < childNodes.getLength(); i++) {
+                Node child = childNodes.item(i);
+                if (child instanceof Element) {
+                    String expValue = mutableExpMap.remove(child.getNodeName());
+                    assertNotNull("Found unexpected \"error-info\" child node: " + child.getNodeName(), expValue);
+                    assertEquals("Text content for \"error-info\" child node " + child.getNodeName(), expValue,
+                            child.getTextContent());
                 }
             }
 
-            if( !mutableExpMap.isEmpty() ) {
-                fail( "Missing \"error-info\" child nodes: " + mutableExpMap );
+            if (!mutableExpMap.isEmpty()) {
+                fail("Missing \"error-info\" child nodes: " + mutableExpMap);
             }
         }
 
         @Override
-        public void verifyJson( final JsonElement errorInfoElement ) {
+        public void verifyJson(final JsonElement errorInfoElement) {
 
-            assertTrue( "\"error-info\" Json element is not an Object",
-                    errorInfoElement.isJsonObject() );
+            assertTrue("\"error-info\" Json element is not an Object", errorInfoElement.isJsonObject());
 
             Map<String, String> actualErrorInfo = Maps.newHashMap();
-            for( Entry<String, JsonElement> entry: errorInfoElement.getAsJsonObject().entrySet() ) {
+            for (Entry<String, JsonElement> entry : errorInfoElement.getAsJsonObject().entrySet()) {
                 String leafName = entry.getKey();
                 JsonElement leafElement = entry.getValue();
-                actualErrorInfo.put( leafName, leafElement.getAsString() );
+                actualErrorInfo.put(leafName, leafElement.getAsString());
             }
 
-            Map<String, String> mutableExpMap = Maps.newHashMap( expErrorInfo );
-            for( Entry<String,String> actual: actualErrorInfo.entrySet() ) {
-                String expValue = mutableExpMap.remove( actual.getKey() );
-                assertNotNull( "Found unexpected \"error-info\" child node: " +
-                        actual.getKey(), expValue );
-                assertEquals( "Text content for \"error-info\" child node " +
-                        actual.getKey(), expValue, actual.getValue() );
+            Map<String, String> mutableExpMap = Maps.newHashMap(expErrorInfo);
+            for (Entry<String, String> actual : actualErrorInfo.entrySet()) {
+                String expValue = mutableExpMap.remove(actual.getKey());
+                assertNotNull("Found unexpected \"error-info\" child node: " + actual.getKey(), expValue);
+                assertEquals("Text content for \"error-info\" child node " + actual.getKey(), expValue,
+                        actual.getValue());
             }
 
-            if( !mutableExpMap.isEmpty() ) {
-                fail( "Missing \"error-info\" child nodes: " + mutableExpMap );
+            if (!mutableExpMap.isEmpty()) {
+                fail("Missing \"error-info\" child nodes: " + mutableExpMap);
             }
         }
     }
@@ -143,27 +141,27 @@ public class RestconfDocumentedExceptionMapperTest extends JerseyTest {
 
         String expTextContent;
 
-        public SimpleErrorInfoVerifier( final String expErrorInfo ) {
+        public SimpleErrorInfoVerifier(final String expErrorInfo) {
             this.expTextContent = expErrorInfo;
         }
 
-        void verifyContent( final String actualContent ) {
-            assertNotNull( "Actual \"error-info\" text content is null", actualContent );
-            assertTrue( "", actualContent.contains( expTextContent ) );
+        void verifyContent(final String actualContent) {
+            assertNotNull("Actual \"error-info\" text content is null", actualContent);
+            assertTrue("", actualContent.contains(expTextContent));
         }
 
         @Override
-        public void verifyXML( final Node errorInfoNode ) {
-            verifyContent( errorInfoNode.getTextContent() );
+        public void verifyXML(final Node errorInfoNode) {
+            verifyContent(errorInfoNode.getTextContent());
         }
 
         @Override
-        public void verifyJson( final JsonElement errorInfoElement ) {
-            verifyContent( errorInfoElement.getAsString() );
+        public void verifyJson(final JsonElement errorInfoElement) {
+            verifyContent(errorInfoElement.getAsString());
         }
     }
 
-    static RestconfService mockRestConf = mock( RestconfService.class );
+    static RestconfService mockRestConf = mock(RestconfService.class);
 
     static XPath XPATH = XPathFactory.newInstance().newXPath();
     static XPathExpression ERROR_LIST;
@@ -175,738 +173,650 @@ public class RestconfDocumentedExceptionMapperTest extends JerseyTest {
 
     @BeforeClass
     public static void init() throws Exception {
-        ControllerContext.getInstance().setGlobalSchema( TestUtils.loadSchemaContext("/modules") );
+        ControllerContext.getInstance().setGlobalSchema(TestUtils.loadSchemaContext("/modules"));
 
         NamespaceContext nsContext = new NamespaceContext() {
             @Override
-            public Iterator<?> getPrefixes( final String namespaceURI ) {
+            public Iterator<?> getPrefixes(final String namespaceURI) {
                 return null;
             }
 
             @Override
-            public String getPrefix( final String namespaceURI ) {
+            public String getPrefix(final String namespaceURI) {
                 return null;
             }
 
             @Override
-            public String getNamespaceURI( final String prefix ) {
-                return "ietf-restconf".equals( prefix ) ? Draft02.RestConfModule.NAMESPACE : null;
+            public String getNamespaceURI(final String prefix) {
+                return "ietf-restconf".equals(prefix) ? Draft02.RestConfModule.NAMESPACE : null;
             }
         };
 
-        XPATH.setNamespaceContext( nsContext );
-        ERROR_LIST = XPATH.compile( "ietf-restconf:errors/ietf-restconf:error" );
-        ERROR_TYPE = XPATH.compile( "ietf-restconf:error-type" );
-        ERROR_TAG = XPATH.compile( "ietf-restconf:error-tag" );
-        ERROR_MESSAGE = XPATH.compile( "ietf-restconf:error-message" );
-        ERROR_APP_TAG = XPATH.compile( "ietf-restconf:error-app-tag" );
-        ERROR_INFO = XPATH.compile( "ietf-restconf:error-info" );
+        XPATH.setNamespaceContext(nsContext);
+        ERROR_LIST = XPATH.compile("ietf-restconf:errors/ietf-restconf:error");
+        ERROR_TYPE = XPATH.compile("ietf-restconf:error-type");
+        ERROR_TAG = XPATH.compile("ietf-restconf:error-tag");
+        ERROR_MESSAGE = XPATH.compile("ietf-restconf:error-message");
+        ERROR_APP_TAG = XPATH.compile("ietf-restconf:error-app-tag");
+        ERROR_INFO = XPATH.compile("ietf-restconf:error-info");
     }
 
     @Override
     @Before
     public void setUp() throws Exception {
-        reset( mockRestConf );
+        reset(mockRestConf);
         super.setUp();
     }
 
     @Override
     protected Application configure() {
         ResourceConfig resourceConfig = new ResourceConfig();
-        resourceConfig = resourceConfig.registerInstances( mockRestConf, StructuredDataToXmlProvider.INSTANCE,
-                StructuredDataToJsonProvider.INSTANCE );
-        resourceConfig.registerClasses( RestconfDocumentedExceptionMapper.class );
+        resourceConfig = resourceConfig.registerInstances(mockRestConf, StructuredDataToXmlProvider.INSTANCE,
+                StructuredDataToJsonProvider.INSTANCE);
+        resourceConfig.registerClasses(RestconfDocumentedExceptionMapper.class);
         return resourceConfig;
     }
 
-    void stageMockEx( final RestconfDocumentedException ex ) {
-        reset( mockRestConf );
-        when( mockRestConf.readOperationalData( any( String.class ), any( UriInfo.class ) ) ).thenThrow( ex );
+    void stageMockEx(final RestconfDocumentedException ex) {
+        reset(mockRestConf);
+        when(mockRestConf.readOperationalData(any(String.class), any(UriInfo.class))).thenThrow(ex);
     }
 
-    void testJsonResponse( final RestconfDocumentedException ex, final Status expStatus, final ErrorType expErrorType,
+    void testJsonResponse(final RestconfDocumentedException ex, final Status expStatus, final ErrorType expErrorType,
             final ErrorTag expErrorTag, final String expErrorMessage, final String expErrorAppTag,
-            final ErrorInfoVerifier errorInfoVerifier ) throws Exception {
+            final ErrorInfoVerifier errorInfoVerifier) throws Exception {
 
-        stageMockEx( ex );
+        stageMockEx(ex);
 
-        Response resp = target("/operational/foo").request( MediaType.APPLICATION_JSON ).get();
+        Response resp = target("/operational/foo").request(MediaType.APPLICATION_JSON).get();
 
-        InputStream stream = verifyResponse( resp, MediaType.APPLICATION_JSON, expStatus );
+        InputStream stream = verifyResponse(resp, MediaType.APPLICATION_JSON, expStatus);
 
-        verifyJsonResponseBody( stream, expErrorType, expErrorTag, expErrorMessage,
-                expErrorAppTag, errorInfoVerifier );
+        verifyJsonResponseBody(stream, expErrorType, expErrorTag, expErrorMessage, expErrorAppTag, errorInfoVerifier);
     }
 
     @Test
     public void testToJsonResponseWithMessageOnly() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error" ), Status.INTERNAL_SERVER_ERROR,
-                ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error"), Status.INTERNAL_SERVER_ERROR,
+                ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null, null);
 
         // To test verification code
-        //        String json =
-        //            "{ errors: {" +
-        //            "    error: [{" +
-        //            "      error-tag : \"operation-failed\"" +
-        //            "      ,error-type : \"application\"" +
-        //            "      ,error-message : \"An error occurred\"" +
-        //            "      ,error-info : {" +
-        //            "        session-id: \"123\"" +
-        //            "        ,address: \"1.2.3.4\"" +
-        //            "      }" +
-        //            "    }]" +
-        //            "  }" +
-        //            "}";
+        // String json =
+        // "{ errors: {" +
+        // "    error: [{" +
+        // "      error-tag : \"operation-failed\"" +
+        // "      ,error-type : \"application\"" +
+        // "      ,error-message : \"An error occurred\"" +
+        // "      ,error-info : {" +
+        // "        session-id: \"123\"" +
+        // "        ,address: \"1.2.3.4\"" +
+        // "      }" +
+        // "    }]" +
+        // "  }" +
+        // "}";
         //
-        //        verifyJsonResponseBody( new java.io.StringBufferInputStream(json ), ErrorType.APPLICATION,
-        //            ErrorTag.OPERATION_FAILED, "An error occurred", null,
-        //            com.google.common.collect.ImmutableMap.of( "session-id", "123", "address", "1.2.3.4" ) );
+        // verifyJsonResponseBody( new java.io.StringBufferInputStream(json ),
+        // ErrorType.APPLICATION,
+        // ErrorTag.OPERATION_FAILED, "An error occurred", null,
+        // com.google.common.collect.ImmutableMap.of( "session-id", "123",
+        // "address", "1.2.3.4" ) );
     }
 
     @Test
     public void testToJsonResponseWithInUseErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.IN_USE ),
-                Status.CONFLICT, ErrorType.PROTOCOL,
-                ErrorTag.IN_USE, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.IN_USE),
+                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.IN_USE, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithInvalidValueErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.RPC,
-                ErrorTag.INVALID_VALUE ),
-                Status.BAD_REQUEST, ErrorType.RPC,
-                ErrorTag.INVALID_VALUE, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.RPC, ErrorTag.INVALID_VALUE),
+                Status.BAD_REQUEST, ErrorType.RPC, ErrorTag.INVALID_VALUE, "mock error", null, null);
 
     }
 
     @Test
     public void testToJsonResponseWithTooBigErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.TRANSPORT,
-                ErrorTag.TOO_BIG ),
-                Status.REQUEST_ENTITY_TOO_LARGE, ErrorType.TRANSPORT,
-                ErrorTag.TOO_BIG, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.TRANSPORT, ErrorTag.TOO_BIG),
+                Status.REQUEST_ENTITY_TOO_LARGE, ErrorType.TRANSPORT, ErrorTag.TOO_BIG, "mock error", null, null);
 
     }
 
     @Test
     public void testToJsonResponseWithMissingAttributeErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.MISSING_ATTRIBUTE ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.MISSING_ATTRIBUTE, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithBadAttributeErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.BAD_ATTRIBUTE ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.BAD_ATTRIBUTE, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE, "mock error", null, null);
     }
+
     @Test
     public void testToJsonResponseWithUnknownAttributeErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_ATTRIBUTE ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_ATTRIBUTE, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ATTRIBUTE),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ATTRIBUTE, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithBadElementErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.BAD_ELEMENT ),
-                Status.BAD_REQUEST,
-                ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithUnknownElementErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_ELEMENT ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_ELEMENT, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithUnknownNamespaceErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_NAMESPACE ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_NAMESPACE, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithMalformedMessageErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.MALFORMED_MESSAGE ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.MALFORMED_MESSAGE, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithAccessDeniedErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.ACCESS_DENIED ),
-                Status.FORBIDDEN, ErrorType.PROTOCOL,
-                ErrorTag.ACCESS_DENIED, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.ACCESS_DENIED),
+                Status.FORBIDDEN, ErrorType.PROTOCOL, ErrorTag.ACCESS_DENIED, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithLockDeniedErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.LOCK_DENIED ),
-                Status.CONFLICT, ErrorType.PROTOCOL,
-                ErrorTag.LOCK_DENIED, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.LOCK_DENIED),
+                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.LOCK_DENIED, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithResourceDeniedErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.RESOURCE_DENIED ),
-                Status.CONFLICT, ErrorType.PROTOCOL,
-                ErrorTag.RESOURCE_DENIED, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.RESOURCE_DENIED),
+                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.RESOURCE_DENIED, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithRollbackFailedErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.ROLLBACK_FAILED ),
-                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL,
-                ErrorTag.ROLLBACK_FAILED, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.ROLLBACK_FAILED),
+                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.ROLLBACK_FAILED, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithDataExistsErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.DATA_EXISTS ),
-                Status.CONFLICT, ErrorType.PROTOCOL,
-                ErrorTag.DATA_EXISTS, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS),
+                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithDataMissingErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.DATA_MISSING ),
-                Status.CONFLICT, ErrorType.PROTOCOL,
-                ErrorTag.DATA_MISSING, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING),
+                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithOperationNotSupportedErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.OPERATION_NOT_SUPPORTED ),
-                Status.NOT_IMPLEMENTED, ErrorType.PROTOCOL,
-                ErrorTag.OPERATION_NOT_SUPPORTED, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL,
+                ErrorTag.OPERATION_NOT_SUPPORTED), Status.NOT_IMPLEMENTED, ErrorType.PROTOCOL,
+                ErrorTag.OPERATION_NOT_SUPPORTED, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithOperationFailedErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.OPERATION_FAILED ),
-                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL,
-                ErrorTag.OPERATION_FAILED, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.OPERATION_FAILED),
+                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.OPERATION_FAILED, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithPartialOperationErrorTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.PARTIAL_OPERATION ),
-                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL,
-                ErrorTag.PARTIAL_OPERATION, "mock error", null, null );
+        testJsonResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.PARTIAL_OPERATION),
+                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.PARTIAL_OPERATION, "mock error", null, null);
     }
 
     @Test
     public void testToJsonResponseWithErrorAppTag() throws Exception {
 
-        testJsonResponse( new RestconfDocumentedException( new RestconfError(
-                ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
-                "mock error", "mock-app-tag" ) ),
-                Status.BAD_REQUEST, ErrorType.APPLICATION,
-                ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", null );
+        testJsonResponse(new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION,
+                ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag")), Status.BAD_REQUEST, ErrorType.APPLICATION,
+                ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", null);
     }
 
     @Test
     public void testToJsonResponseWithMultipleErrors() throws Exception {
 
-        List<RestconfError> errorList = Arrays.asList(
-                new RestconfError( ErrorType.APPLICATION, ErrorTag.LOCK_DENIED, "mock error1" ),
-                new RestconfError( ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2" ) );
-        stageMockEx( new RestconfDocumentedException( errorList ) );
+        List<RestconfError> errorList = Arrays.asList(new RestconfError(ErrorType.APPLICATION, ErrorTag.LOCK_DENIED,
+                "mock error1"), new RestconfError(ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2"));
+        stageMockEx(new RestconfDocumentedException(errorList));
 
-        Response resp = target("/operational/foo").request( MediaType.APPLICATION_JSON ).get();
+        Response resp = target("/operational/foo").request(MediaType.APPLICATION_JSON).get();
 
-        InputStream stream = verifyResponse( resp, MediaType.APPLICATION_JSON, Status.CONFLICT );
+        InputStream stream = verifyResponse(resp, MediaType.APPLICATION_JSON, Status.CONFLICT);
 
-        JsonArray arrayElement = parseJsonErrorArrayElement( stream );
+        JsonArray arrayElement = parseJsonErrorArrayElement(stream);
 
-        assertEquals( "\"error\" Json array element length", 2, arrayElement.size() );
+        assertEquals("\"error\" Json array element length", 2, arrayElement.size());
 
-        verifyJsonErrorNode( arrayElement.get( 0 ), ErrorType.APPLICATION, ErrorTag.LOCK_DENIED,
-                "mock error1", null, null );
+        verifyJsonErrorNode(arrayElement.get(0), ErrorType.APPLICATION, ErrorTag.LOCK_DENIED, "mock error1", null, null);
 
-        verifyJsonErrorNode( arrayElement.get( 1 ), ErrorType.RPC, ErrorTag.ROLLBACK_FAILED,
-                "mock error2", null, null );
+        verifyJsonErrorNode(arrayElement.get(1), ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2", null, null);
     }
 
     @Test
     public void testToJsonResponseWithErrorInfo() throws Exception {
 
         String errorInfo = "<address>1.2.3.4</address> <session-id>123</session-id>";
-        testJsonResponse( new RestconfDocumentedException( new RestconfError(
-                ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
-                "mock error", "mock-app-tag", errorInfo ) ),
-                Status.BAD_REQUEST, ErrorType.APPLICATION,
-                ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag",
-                new ComplexErrorInfoVerifier( ImmutableMap.of(
-                        "session-id", "123", "address", "1.2.3.4" ) ) );
+        testJsonResponse(new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION,
+                ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", errorInfo)), Status.BAD_REQUEST,
+                ErrorType.APPLICATION, ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag",
+                new ComplexErrorInfoVerifier(ImmutableMap.of("session-id", "123", "address", "1.2.3.4")));
     }
 
     @Test
     public void testToJsonResponseWithExceptionCause() throws Exception {
 
-        Exception cause = new Exception( "mock exception cause" );
-        testJsonResponse( new RestconfDocumentedException( "mock error", cause ),
-                Status.INTERNAL_SERVER_ERROR, ErrorType.APPLICATION,
-                ErrorTag.OPERATION_FAILED, "mock error", null,
-                new SimpleErrorInfoVerifier( cause.getMessage() ) );
+        Exception cause = new Exception("mock exception cause");
+        testJsonResponse(new RestconfDocumentedException("mock error", cause), Status.INTERNAL_SERVER_ERROR,
+                ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null,
+                new SimpleErrorInfoVerifier(cause.getMessage()));
     }
 
-    void testXMLResponse( final RestconfDocumentedException ex, final Status expStatus, final ErrorType expErrorType,
-            final ErrorTag expErrorTag, final String expErrorMessage,
-            final String expErrorAppTag, final ErrorInfoVerifier errorInfoVerifier ) throws Exception
-    {
-        stageMockEx( ex );
+    void testXMLResponse(final RestconfDocumentedException ex, final Status expStatus, final ErrorType expErrorType,
+            final ErrorTag expErrorTag, final String expErrorMessage, final String expErrorAppTag,
+            final ErrorInfoVerifier errorInfoVerifier) throws Exception {
+        stageMockEx(ex);
 
-        Response resp = target("/operational/foo").request( MediaType.APPLICATION_XML ).get();
+        Response resp = target("/operational/foo").request(MediaType.APPLICATION_XML).get();
 
-        InputStream stream = verifyResponse( resp, MediaType.APPLICATION_XML, expStatus );
+        InputStream stream = verifyResponse(resp, MediaType.APPLICATION_XML, expStatus);
 
-        verifyXMLResponseBody( stream, expErrorType, expErrorTag, expErrorMessage,
-                expErrorAppTag, errorInfoVerifier );
+        verifyXMLResponseBody(stream, expErrorType, expErrorTag, expErrorMessage, expErrorAppTag, errorInfoVerifier);
     }
 
     @Test
     public void testToXMLResponseWithMessageOnly() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error" ), Status.INTERNAL_SERVER_ERROR,
-                ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error"), Status.INTERNAL_SERVER_ERROR,
+                ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null, null);
 
         // To test verification code
-        //        String xml =
-        //            "<errors xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\">"+
-        //            "  <error>" +
-        //            "    <error-type>application</error-type>"+
-        //            "    <error-tag>operation-failed</error-tag>"+
-        //            "    <error-message>An error occurred</error-message>"+
-        //            "    <error-info>" +
-        //            "      <session-id>123</session-id>" +
-        //            "      <address>1.2.3.4</address>" +
-        //            "    </error-info>" +
-        //            "  </error>" +
-        //            "</errors>";
+        // String xml =
+        // "<errors xmlns=\"urn:ietf:params:xml:ns:yang:ietf-restconf\">"+
+        // "  <error>" +
+        // "    <error-type>application</error-type>"+
+        // "    <error-tag>operation-failed</error-tag>"+
+        // "    <error-message>An error occurred</error-message>"+
+        // "    <error-info>" +
+        // "      <session-id>123</session-id>" +
+        // "      <address>1.2.3.4</address>" +
+        // "    </error-info>" +
+        // "  </error>" +
+        // "</errors>";
         //
-        //        verifyXMLResponseBody( new java.io.StringBufferInputStream(xml), ErrorType.APPLICATION,
-        //                ErrorTag.OPERATION_FAILED, "An error occurred", null,
-        //                com.google.common.collect.ImmutableMap.of( "session-id", "123", "address", "1.2.3.4" ) );
+        // verifyXMLResponseBody( new java.io.StringBufferInputStream(xml),
+        // ErrorType.APPLICATION,
+        // ErrorTag.OPERATION_FAILED, "An error occurred", null,
+        // com.google.common.collect.ImmutableMap.of( "session-id", "123",
+        // "address", "1.2.3.4" ) );
     }
 
     @Test
     public void testToXMLResponseWithInUseErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.IN_USE ),
-                Status.CONFLICT, ErrorType.PROTOCOL,
-                ErrorTag.IN_USE, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.IN_USE),
+                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.IN_USE, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithInvalidValueErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.RPC,
-                ErrorTag.INVALID_VALUE ),
-                Status.BAD_REQUEST, ErrorType.RPC,
-                ErrorTag.INVALID_VALUE, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.RPC, ErrorTag.INVALID_VALUE),
+                Status.BAD_REQUEST, ErrorType.RPC, ErrorTag.INVALID_VALUE, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithTooBigErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.TRANSPORT,
-                ErrorTag.TOO_BIG ),
-                Status.REQUEST_ENTITY_TOO_LARGE, ErrorType.TRANSPORT,
-                ErrorTag.TOO_BIG, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.TRANSPORT, ErrorTag.TOO_BIG),
+                Status.REQUEST_ENTITY_TOO_LARGE, ErrorType.TRANSPORT, ErrorTag.TOO_BIG, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithMissingAttributeErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.MISSING_ATTRIBUTE ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.MISSING_ATTRIBUTE, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.MISSING_ATTRIBUTE, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithBadAttributeErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.BAD_ATTRIBUTE ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.BAD_ATTRIBUTE, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE, "mock error", null, null);
     }
+
     @Test
     public void testToXMLResponseWithUnknownAttributeErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_ATTRIBUTE ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_ATTRIBUTE, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ATTRIBUTE),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ATTRIBUTE, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithBadElementErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.BAD_ELEMENT ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.BAD_ELEMENT, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.BAD_ELEMENT, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithUnknownElementErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_ELEMENT ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_ELEMENT, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_ELEMENT, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithUnknownNamespaceErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_NAMESPACE ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.UNKNOWN_NAMESPACE, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithMalformedMessageErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.MALFORMED_MESSAGE ),
-                Status.BAD_REQUEST, ErrorType.PROTOCOL,
-                ErrorTag.MALFORMED_MESSAGE, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE),
+                Status.BAD_REQUEST, ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithAccessDeniedErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.ACCESS_DENIED ),
-                Status.FORBIDDEN, ErrorType.PROTOCOL,
-                ErrorTag.ACCESS_DENIED, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.ACCESS_DENIED),
+                Status.FORBIDDEN, ErrorType.PROTOCOL, ErrorTag.ACCESS_DENIED, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithLockDeniedErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.LOCK_DENIED ),
-                Status.CONFLICT, ErrorType.PROTOCOL,
-                ErrorTag.LOCK_DENIED, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.LOCK_DENIED),
+                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.LOCK_DENIED, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithResourceDeniedErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.RESOURCE_DENIED ),
-                Status.CONFLICT, ErrorType.PROTOCOL,
-                ErrorTag.RESOURCE_DENIED, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.RESOURCE_DENIED),
+                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.RESOURCE_DENIED, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithRollbackFailedErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.ROLLBACK_FAILED ),
-                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL,
-                ErrorTag.ROLLBACK_FAILED, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.ROLLBACK_FAILED),
+                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.ROLLBACK_FAILED, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithDataExistsErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.DATA_EXISTS ),
-                Status.CONFLICT, ErrorType.PROTOCOL,
-                ErrorTag.DATA_EXISTS, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS),
+                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.DATA_EXISTS, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithDataMissingErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.DATA_MISSING ),
-                Status.CONFLICT, ErrorType.PROTOCOL,
-                ErrorTag.DATA_MISSING, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.DATA_MISSING),
+                Status.CONFLICT, ErrorType.PROTOCOL, ErrorTag.DATA_MISSING, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithOperationNotSupportedErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.OPERATION_NOT_SUPPORTED ),
-                Status.NOT_IMPLEMENTED, ErrorType.PROTOCOL,
-                ErrorTag.OPERATION_NOT_SUPPORTED, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL,
+                ErrorTag.OPERATION_NOT_SUPPORTED), Status.NOT_IMPLEMENTED, ErrorType.PROTOCOL,
+                ErrorTag.OPERATION_NOT_SUPPORTED, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithOperationFailedErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.OPERATION_FAILED ),
-                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL,
-                ErrorTag.OPERATION_FAILED, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.OPERATION_FAILED),
+                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.OPERATION_FAILED, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithPartialOperationErrorTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( "mock error", ErrorType.PROTOCOL,
-                ErrorTag.PARTIAL_OPERATION ),
-                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL,
-                ErrorTag.PARTIAL_OPERATION, "mock error", null, null );
+        testXMLResponse(new RestconfDocumentedException("mock error", ErrorType.PROTOCOL, ErrorTag.PARTIAL_OPERATION),
+                Status.INTERNAL_SERVER_ERROR, ErrorType.PROTOCOL, ErrorTag.PARTIAL_OPERATION, "mock error", null, null);
     }
 
     @Test
     public void testToXMLResponseWithErrorAppTag() throws Exception {
 
-        testXMLResponse( new RestconfDocumentedException( new RestconfError(
-                ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
-                "mock error", "mock-app-tag" ) ),
-                Status.BAD_REQUEST, ErrorType.APPLICATION,
-                ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", null );
+        testXMLResponse(new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION,
+                ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag")), Status.BAD_REQUEST, ErrorType.APPLICATION,
+                ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", null);
     }
 
     @Test
     public void testToXMLResponseWithErrorInfo() throws Exception {
 
         String errorInfo = "<address>1.2.3.4</address> <session-id>123</session-id>";
-        testXMLResponse( new RestconfDocumentedException( new RestconfError(
-                ErrorType.APPLICATION, ErrorTag.INVALID_VALUE,
-                "mock error", "mock-app-tag", errorInfo ) ),
-                Status.BAD_REQUEST, ErrorType.APPLICATION,
-                ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag",
-                new ComplexErrorInfoVerifier( ImmutableMap.of(
-                        "session-id", "123", "address", "1.2.3.4" ) ) );
+        testXMLResponse(new RestconfDocumentedException(new RestconfError(ErrorType.APPLICATION,
+                ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag", errorInfo)), Status.BAD_REQUEST,
+                ErrorType.APPLICATION, ErrorTag.INVALID_VALUE, "mock error", "mock-app-tag",
+                new ComplexErrorInfoVerifier(ImmutableMap.of("session-id", "123", "address", "1.2.3.4")));
     }
 
     @Test
     public void testToXMLResponseWithExceptionCause() throws Exception {
 
-        Exception cause = new Exception( "mock exception cause" );
-        testXMLResponse( new RestconfDocumentedException( "mock error", cause ),
-                Status.INTERNAL_SERVER_ERROR, ErrorType.APPLICATION,
-                ErrorTag.OPERATION_FAILED, "mock error", null,
-                new SimpleErrorInfoVerifier( cause.getMessage() ) );
+        Exception cause = new Exception("mock exception cause");
+        testXMLResponse(new RestconfDocumentedException("mock error", cause), Status.INTERNAL_SERVER_ERROR,
+                ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null,
+                new SimpleErrorInfoVerifier(cause.getMessage()));
     }
 
     @Test
     public void testToXMLResponseWithMultipleErrors() throws Exception {
 
-        List<RestconfError> errorList = Arrays.asList(
-                new RestconfError( ErrorType.APPLICATION, ErrorTag.LOCK_DENIED, "mock error1" ),
-                new RestconfError( ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2" ) );
-        stageMockEx( new RestconfDocumentedException( errorList ) );
+        List<RestconfError> errorList = Arrays.asList(new RestconfError(ErrorType.APPLICATION, ErrorTag.LOCK_DENIED,
+                "mock error1"), new RestconfError(ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2"));
+        stageMockEx(new RestconfDocumentedException(errorList));
 
-        Response resp = target("/operational/foo").request( MediaType.APPLICATION_XML ).get();
+        Response resp = target("/operational/foo").request(MediaType.APPLICATION_XML).get();
 
-        InputStream stream = verifyResponse( resp, MediaType.APPLICATION_XML, Status.CONFLICT );
+        InputStream stream = verifyResponse(resp, MediaType.APPLICATION_XML, Status.CONFLICT);
 
-        Document doc = parseXMLDocument( stream );
+        Document doc = parseXMLDocument(stream);
 
-        NodeList children = getXMLErrorList( doc, 2 );
+        NodeList children = getXMLErrorList(doc, 2);
 
-        verifyXMLErrorNode( children.item( 0 ), ErrorType.APPLICATION, ErrorTag.LOCK_DENIED,
-                "mock error1", null, null );
+        verifyXMLErrorNode(children.item(0), ErrorType.APPLICATION, ErrorTag.LOCK_DENIED, "mock error1", null, null);
 
-        verifyXMLErrorNode( children.item( 1 ), ErrorType.RPC, ErrorTag.ROLLBACK_FAILED,
-                "mock error2", null, null );
+        verifyXMLErrorNode(children.item(1), ErrorType.RPC, ErrorTag.ROLLBACK_FAILED, "mock error2", null, null);
     }
 
     @Test
     public void testToResponseWithAcceptHeader() throws Exception {
 
-        stageMockEx( new RestconfDocumentedException( "mock error" ) );
+        stageMockEx(new RestconfDocumentedException("mock error"));
 
-        Response resp = target("/operational/foo")
-                .request().header( "Accept", MediaType.APPLICATION_JSON ).get();
+        Response resp = target("/operational/foo").request().header("Accept", MediaType.APPLICATION_JSON).get();
 
-        InputStream stream = verifyResponse( resp, MediaType.APPLICATION_JSON,
-                Status.INTERNAL_SERVER_ERROR );
+        InputStream stream = verifyResponse(resp, MediaType.APPLICATION_JSON, Status.INTERNAL_SERVER_ERROR);
 
-        verifyJsonResponseBody( stream, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error",
-                null, null );
+        verifyJsonResponseBody(stream, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED, "mock error", null, null);
     }
 
     @Test
     public void testToResponseWithStatusOnly() throws Exception {
 
-        // The StructuredDataToJsonProvider should throw a RestconfDocumentedException with no data
+        // The StructuredDataToJsonProvider should throw a
+        // RestconfDocumentedException with no data
 
-        when( mockRestConf.readOperationalData( any( String.class ), any( UriInfo.class ) ) )
-            .thenReturn( new StructuredData( null, null, null ) );
+        when(mockRestConf.readOperationalData(any(String.class), any(UriInfo.class))).thenReturn(
+                new StructuredData(null, null, null));
 
-        Response resp = target("/operational/foo").request( MediaType.APPLICATION_JSON ).get();
+        Response resp = target("/operational/foo").request(MediaType.APPLICATION_JSON).get();
 
-        verifyResponse( resp, MediaType.TEXT_PLAIN, Status.NOT_FOUND );
+        verifyResponse(resp, MediaType.TEXT_PLAIN, Status.NOT_FOUND);
     }
 
-    InputStream verifyResponse( final Response resp, final String expMediaType, final Status expStatus ) {
-        assertEquals( "getMediaType", MediaType.valueOf( expMediaType ), resp.getMediaType() );
-        assertEquals( "getStatus", expStatus.getStatusCode(), resp.getStatus() );
+    InputStream verifyResponse(final Response resp, final String expMediaType, final Status expStatus) {
+        assertEquals("getMediaType", MediaType.valueOf(expMediaType), resp.getMediaType());
+        assertEquals("getStatus", expStatus.getStatusCode(), resp.getStatus());
 
         Object entity = resp.getEntity();
-        assertEquals( "Response entity", true, entity instanceof InputStream );
-        InputStream stream = (InputStream)entity;
+        assertEquals("Response entity", true, entity instanceof InputStream);
+        InputStream stream = (InputStream) entity;
         return stream;
     }
 
-    void verifyJsonResponseBody( final InputStream stream, final ErrorType expErrorType, final ErrorTag expErrorTag,
-            final String expErrorMessage, final String expErrorAppTag,
-            final ErrorInfoVerifier errorInfoVerifier ) throws Exception {
+    void verifyJsonResponseBody(final InputStream stream, final ErrorType expErrorType, final ErrorTag expErrorTag,
+            final String expErrorMessage, final String expErrorAppTag, final ErrorInfoVerifier errorInfoVerifier)
+            throws Exception {
 
-        JsonArray arrayElement = parseJsonErrorArrayElement( stream );
+        JsonArray arrayElement = parseJsonErrorArrayElement(stream);
 
-        assertEquals( "\"error\" Json array element length", 1, arrayElement.size() );
+        assertEquals("\"error\" Json array element length", 1, arrayElement.size());
 
-        verifyJsonErrorNode( arrayElement.get( 0 ),  expErrorType, expErrorTag, expErrorMessage,
-                expErrorAppTag, errorInfoVerifier );
+        verifyJsonErrorNode(arrayElement.get(0), expErrorType, expErrorTag, expErrorMessage, expErrorAppTag,
+                errorInfoVerifier);
     }
 
-    private JsonArray parseJsonErrorArrayElement( final InputStream stream ) throws IOException {
+    private JsonArray parseJsonErrorArrayElement(final InputStream stream) throws IOException {
         ByteArrayOutputStream bos = new ByteArrayOutputStream();
-        ByteStreams.copy( stream, bos );
+        ByteStreams.copy(stream, bos);
 
-        System.out.println("JSON: "+bos.toString());
+        System.out.println("JSON: " + bos.toString());
 
         JsonParser parser = new JsonParser();
         JsonElement rootElement;
 
         try {
-            rootElement = parser.parse(
-                    new InputStreamReader( new ByteArrayInputStream( bos.toByteArray() ) ) );
-        }
-        catch( Exception e ) {
-            throw new IllegalArgumentException( "Invalid JSON response:\n" + bos.toString(), e );
+            rootElement = parser.parse(new InputStreamReader(new ByteArrayInputStream(bos.toByteArray())));
+        } catch (Exception e) {
+            throw new IllegalArgumentException("Invalid JSON response:\n" + bos.toString(), e);
         }
 
-        assertTrue( "Root element of Json is not an Object", rootElement.isJsonObject() );
+        assertTrue("Root element of Json is not an Object", rootElement.isJsonObject());
 
         Set<Entry<String, JsonElement>> errorsEntrySet = rootElement.getAsJsonObject().entrySet();
-        assertEquals( "Json Object element set count", 1, errorsEntrySet.size() );
+        assertEquals("Json Object element set count", 1, errorsEntrySet.size());
 
         Entry<String, JsonElement> errorsEntry = errorsEntrySet.iterator().next();
         JsonElement errorsElement = errorsEntry.getValue();
-        assertEquals( "First Json element name", "errors", errorsEntry.getKey() );
-        assertTrue( "\"errors\" Json element is not an Object", errorsElement.isJsonObject() );
+        assertEquals("First Json element name", "errors", errorsEntry.getKey());
+        assertTrue("\"errors\" Json element is not an Object", errorsElement.isJsonObject());
 
         Set<Entry<String, JsonElement>> errorListEntrySet = errorsElement.getAsJsonObject().entrySet();
-        assertEquals( "Root \"errors\" element child count", 1, errorListEntrySet.size() );
+        assertEquals("Root \"errors\" element child count", 1, errorListEntrySet.size());
 
         JsonElement errorListElement = errorListEntrySet.iterator().next().getValue();
-        assertEquals( "\"errors\" child Json element name", "error",
-                errorListEntrySet.iterator().next().getKey() );
-        assertTrue( "\"error\" Json element is not an Array", errorListElement.isJsonArray() );
+        assertEquals("\"errors\" child Json element name", "error", errorListEntrySet.iterator().next().getKey());
+        assertTrue("\"error\" Json element is not an Array", errorListElement.isJsonArray());
+
+        // As a final check, make sure there aren't multiple "error" array
+        // elements. Unfortunately,
+        // the call above to getAsJsonObject().entrySet() will out duplicate
+        // "error" elements. So
+        // we'll use regex on the json string to verify this.
+
+        Matcher matcher = Pattern.compile("\"error\"[ ]*:[ ]*\\[", Pattern.DOTALL).matcher(bos.toString());
+        assertTrue("Expected 1 \"error\" element", matcher.find());
+        assertFalse("Found multiple \"error\" elements", matcher.find());
 
         return errorListElement.getAsJsonArray();
     }
 
-    void verifyJsonErrorNode( final JsonElement errorEntryElement, final ErrorType expErrorType, final ErrorTag expErrorTag,
-            final String expErrorMessage, final String expErrorAppTag,
-            final ErrorInfoVerifier errorInfoVerifier ) {
+    void verifyJsonErrorNode(final JsonElement errorEntryElement, final ErrorType expErrorType,
+            final ErrorTag expErrorTag, final String expErrorMessage, final String expErrorAppTag,
+            final ErrorInfoVerifier errorInfoVerifier) {
 
         JsonElement errorInfoElement = null;
-        Map<String, String> actualErrorInfo = null;
         Map<String, String> leafMap = Maps.newHashMap();
-        for( Entry<String, JsonElement> entry: errorEntryElement.getAsJsonObject().entrySet() ) {
+        for (Entry<String, JsonElement> entry : errorEntryElement.getAsJsonObject().entrySet()) {
             String leafName = entry.getKey();
             JsonElement leafElement = entry.getValue();
 
-            if( "error-info".equals( leafName ) ) {
-                assertNotNull( "Found unexpected \"error-info\" element", errorInfoVerifier );
+            if ("error-info".equals(leafName)) {
+                assertNotNull("Found unexpected \"error-info\" element", errorInfoVerifier);
                 errorInfoElement = leafElement;
-            }
-            else {
-                assertTrue( "\"error\" leaf Json element " + leafName +
-                        " is not a Primitive", leafElement.isJsonPrimitive() );
+            } else {
+                assertTrue("\"error\" leaf Json element " + leafName + " is not a Primitive",
+                        leafElement.isJsonPrimitive());
 
-                leafMap.put( leafName, leafElement.getAsString() );
+                leafMap.put(leafName, leafElement.getAsString());
             }
         }
 
-        assertEquals( "error-type", expErrorType.getErrorTypeTag(), leafMap.remove( "error-type" ) );
-        assertEquals( "error-tag", expErrorTag.getTagValue(), leafMap.remove( "error-tag" ) );
+        assertEquals("error-type", expErrorType.getErrorTypeTag(), leafMap.remove("error-type"));
+        assertEquals("error-tag", expErrorTag.getTagValue(), leafMap.remove("error-tag"));
 
-        verifyOptionalJsonLeaf( leafMap.remove( "error-message" ), expErrorMessage, "error-message" );
-        verifyOptionalJsonLeaf( leafMap.remove( "error-app-tag" ), expErrorAppTag, "error-app-tag" );
+        verifyOptionalJsonLeaf(leafMap.remove("error-message"), expErrorMessage, "error-message");
+        verifyOptionalJsonLeaf(leafMap.remove("error-app-tag"), expErrorAppTag, "error-app-tag");
 
-        if( !leafMap.isEmpty() ) {
-            fail( "Found unexpected Json leaf elements for \"error\" element: " + leafMap );
+        if (!leafMap.isEmpty()) {
+            fail("Found unexpected Json leaf elements for \"error\" element: " + leafMap);
         }
 
-        if( errorInfoVerifier != null ) {
-            assertNotNull( "Missing \"error-info\" element", errorInfoElement );
-            errorInfoVerifier.verifyJson( errorInfoElement );
+        if (errorInfoVerifier != null) {
+            assertNotNull("Missing \"error-info\" element", errorInfoElement);
+            errorInfoVerifier.verifyJson(errorInfoElement);
         }
     }
 
-    void verifyOptionalJsonLeaf( final String actualValue, final String expValue, final String tagName ) {
-        if( expValue != null ) {
-            assertEquals( tagName, expValue, actualValue );
-        }
-        else {
-            assertNull( "Found unexpected \"error\" leaf entry for: " + tagName, actualValue );
+    void verifyOptionalJsonLeaf(final String actualValue, final String expValue, final String tagName) {
+        if (expValue != null) {
+            assertEquals(tagName, expValue, actualValue);
+        } else {
+            assertNull("Found unexpected \"error\" leaf entry for: " + tagName, actualValue);
         }
     }
 
-    void verifyXMLResponseBody( final InputStream stream, final ErrorType expErrorType, final ErrorTag expErrorTag,
-            final String expErrorMessage, final String expErrorAppTag,
-            final ErrorInfoVerifier errorInfoVerifier )
-                    throws Exception {
+    void verifyXMLResponseBody(final InputStream stream, final ErrorType expErrorType, final ErrorTag expErrorTag,
+            final String expErrorMessage, final String expErrorAppTag, final ErrorInfoVerifier errorInfoVerifier)
+            throws Exception {
 
-        Document doc = parseXMLDocument( stream );
+        Document doc = parseXMLDocument(stream);
 
-        NodeList children = getXMLErrorList( doc, 1 );
+        NodeList children = getXMLErrorList(doc, 1);
 
-        verifyXMLErrorNode( children.item( 0 ), expErrorType, expErrorTag, expErrorMessage,
-                expErrorAppTag, errorInfoVerifier );
+        verifyXMLErrorNode(children.item(0), expErrorType, expErrorTag, expErrorMessage, expErrorAppTag,
+                errorInfoVerifier);
     }
 
-    private Document parseXMLDocument( final InputStream stream ) throws IOException {
+    private Document parseXMLDocument(final InputStream stream) throws IOException {
         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         factory.setNamespaceAware(true);
         factory.setCoalescing(true);
@@ -914,60 +824,57 @@ public class RestconfDocumentedExceptionMapperTest extends JerseyTest {
         factory.setIgnoringComments(true);
 
         ByteArrayOutputStream bos = new ByteArrayOutputStream();
-        ByteStreams.copy( stream, bos );
+        ByteStreams.copy(stream, bos);
 
-        System.out.println("XML: "+bos.toString());
+        System.out.println("XML: " + bos.toString());
 
         Document doc = null;
         try {
-            doc = factory.newDocumentBuilder().parse( new ByteArrayInputStream( bos.toByteArray() ) );
-        }
-        catch( Exception e ) {
-            throw new IllegalArgumentException( "Invalid XML response:\n" + bos.toString(), e );
+            doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(bos.toByteArray()));
+        } catch (Exception e) {
+            throw new IllegalArgumentException("Invalid XML response:\n" + bos.toString(), e);
         }
         return doc;
     }
 
-    void verifyXMLErrorNode( final Node errorNode, final ErrorType expErrorType, final ErrorTag expErrorTag,
-            final String expErrorMessage, final String expErrorAppTag,
-            final ErrorInfoVerifier errorInfoVerifier ) throws Exception {
+    void verifyXMLErrorNode(final Node errorNode, final ErrorType expErrorType, final ErrorTag expErrorTag,
+            final String expErrorMessage, final String expErrorAppTag, final ErrorInfoVerifier errorInfoVerifier)
+            throws Exception {
 
-        String errorType = (String)ERROR_TYPE.evaluate( errorNode, XPathConstants.STRING );
-        assertEquals( "error-type", expErrorType.getErrorTypeTag(), errorType );
+        String errorType = (String) ERROR_TYPE.evaluate(errorNode, XPathConstants.STRING);
+        assertEquals("error-type", expErrorType.getErrorTypeTag(), errorType);
 
-        String errorTag = (String)ERROR_TAG.evaluate( errorNode, XPathConstants.STRING );
-        assertEquals( "error-tag", expErrorTag.getTagValue(), errorTag );
+        String errorTag = (String) ERROR_TAG.evaluate(errorNode, XPathConstants.STRING);
+        assertEquals("error-tag", expErrorTag.getTagValue(), errorTag);
 
-        verifyOptionalXMLLeaf( errorNode, ERROR_MESSAGE, expErrorMessage, "error-message" );
-        verifyOptionalXMLLeaf( errorNode, ERROR_APP_TAG, expErrorAppTag, "error-app-tag" );
+        verifyOptionalXMLLeaf(errorNode, ERROR_MESSAGE, expErrorMessage, "error-message");
+        verifyOptionalXMLLeaf(errorNode, ERROR_APP_TAG, expErrorAppTag, "error-app-tag");
 
-        Node errorInfoNode = (Node)ERROR_INFO.evaluate( errorNode, XPathConstants.NODE );
-        if( errorInfoVerifier != null ) {
-            assertNotNull( "Missing \"error-info\" node", errorInfoNode );
+        Node errorInfoNode = (Node) ERROR_INFO.evaluate(errorNode, XPathConstants.NODE);
+        if (errorInfoVerifier != null) {
+            assertNotNull("Missing \"error-info\" node", errorInfoNode);
 
-            errorInfoVerifier.verifyXML( errorInfoNode );
-        }
-        else {
-            assertNull( "Found unexpected \"error-info\" node", errorInfoNode );
+            errorInfoVerifier.verifyXML(errorInfoNode);
+        } else {
+            assertNull("Found unexpected \"error-info\" node", errorInfoNode);
         }
     }
 
-    void verifyOptionalXMLLeaf( final Node fromNode, final XPathExpression xpath, final String expValue,
-            final String tagName ) throws Exception {
-        if( expValue != null ) {
-            String actual = (String)xpath.evaluate( fromNode, XPathConstants.STRING );
-            assertEquals( tagName, expValue, actual );
-        }
-        else {
-            assertNull( "Found unexpected \"error\" leaf entry for: " + tagName,
-                    xpath.evaluate( fromNode, XPathConstants.NODE ) );
+    void verifyOptionalXMLLeaf(final Node fromNode, final XPathExpression xpath, final String expValue,
+            final String tagName) throws Exception {
+        if (expValue != null) {
+            String actual = (String) xpath.evaluate(fromNode, XPathConstants.STRING);
+            assertEquals(tagName, expValue, actual);
+        } else {
+            assertNull("Found unexpected \"error\" leaf entry for: " + tagName,
+                    xpath.evaluate(fromNode, XPathConstants.NODE));
         }
     }
 
-    NodeList getXMLErrorList( final Node fromNode, final int count ) throws Exception {
-        NodeList errorList = (NodeList)ERROR_LIST.evaluate( fromNode, XPathConstants.NODESET );
-        assertNotNull( "Root errors node is empty", errorList );
-        assertEquals( "Root errors node child count", count, errorList.getLength() );
+    NodeList getXMLErrorList(final Node fromNode, final int count) throws Exception {
+        NodeList errorList = (NodeList) ERROR_LIST.evaluate(fromNode, XPathConstants.NODESET);
+        assertNotNull("Root errors node is empty", errorList);
+        assertEquals("Root errors node child count", count, errorList.getLength());
         return errorList;
     }
 }
index a1b87325540e51a65b5918a9674148e9e2cbea26..18311104a41f9761dd5bede15965df9625ea061b 100644 (file)
@@ -1,10 +1,10 @@
 /*
-* Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
-*
-* This program and the accompanying materials are made available under the
-* terms of the Eclipse Public License v1.0 which accompanies this distribution,
-* and is available at http://www.eclipse.org/legal/epl-v10.html
-*/
+ * Copyright (c) 2014 Brocade Communications Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
 package org.opendaylight.controller.sal.restconf.impl.test;
 
 import static org.hamcrest.CoreMatchers.equalTo;
@@ -14,18 +14,15 @@ import static org.junit.Assert.assertThat;
 
 import java.util.HashMap;
 import java.util.Map;
-
 import org.hamcrest.BaseMatcher;
 import org.hamcrest.Description;
 import org.hamcrest.Matcher;
 import org.junit.Test;
-
-import static org.opendaylight.controller.sal.common.util.RpcErrors.getRpcError;
-
 import org.opendaylight.controller.sal.restconf.impl.RestconfError;
 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
 import org.opendaylight.yangtools.yang.common.RpcError;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 
 /**
  * Unit tests for RestconfError.
@@ -40,196 +37,166 @@ public class RestconfErrorTest {
 
         private final String text;
 
-        public Contains( String text ) {
+        public Contains(String text) {
             this.text = text;
         }
 
         @Override
-        public void describeTo( Description desc ) {
-            desc.appendText( "contains " ).appendValue( text );
+        public void describeTo(Description desc) {
+            desc.appendText("contains ").appendValue(text);
         }
 
         @Override
-        public boolean matches( Object arg ) {
-            return arg != null && arg.toString().contains( text );
+        public boolean matches(Object arg) {
+            return arg != null && arg.toString().contains(text);
         }
     }
 
     @Test
-    public void testErrorTagValueOf()
-    {
-        assertEquals( ErrorTag.IN_USE,
-                ErrorTag.valueOfCaseInsensitive( ErrorTag.IN_USE.getTagValue() ) );
+    public void testErrorTagValueOf() {
+        assertEquals(ErrorTag.IN_USE, ErrorTag.valueOfCaseInsensitive(ErrorTag.IN_USE.getTagValue()));
     }
 
     @Test
-    public void testErrorTagValueOfIsLowercase()
-    {
-        assertEquals( "in-use",
-                ErrorTag.IN_USE.getTagValue() );
+    public void testErrorTagValueOfIsLowercase() {
+        assertEquals("in-use", ErrorTag.IN_USE.getTagValue());
     }
 
     @Test
-    public void testErrorTypeGetErrorTypeTagIsLowerCase()
-    {
-       assertEquals( ErrorType.APPLICATION.name().toLowerCase(),
-               ErrorType.APPLICATION.getErrorTypeTag() );
+    public void testErrorTypeGetErrorTypeTagIsLowerCase() {
+        assertEquals(ErrorType.APPLICATION.name().toLowerCase(), ErrorType.APPLICATION.getErrorTypeTag());
     }
 
     @Test
-    public void testErrorTypeValueOf()
-    {
-       assertEquals( ErrorType.APPLICATION,
-                     ErrorType.valueOfCaseInsensitive( ErrorType.APPLICATION.getErrorTypeTag() ) );
+    public void testErrorTypeValueOf() {
+        assertEquals(ErrorType.APPLICATION, ErrorType.valueOfCaseInsensitive(ErrorType.APPLICATION.getErrorTypeTag()));
     }
 
     @Test
-    public void testErrorTagStatusCodes()
-    {
-        Map<String,Integer> lookUpMap = new HashMap<String,Integer>();
-
-        lookUpMap.put( "in-use", 409);
-        lookUpMap.put( "invalid-value", 400);
-        lookUpMap.put( "too-big", 413);
-        lookUpMap.put( "missing-attribute", 400);
-        lookUpMap.put( "bad-attribute", 400);
-        lookUpMap.put( "unknown-attribute", 400);
-        lookUpMap.put( "bad-element", 400);
-        lookUpMap.put( "unknown-element", 400);
-        lookUpMap.put( "unknown-namespace", 400);
-        lookUpMap.put( "access-denied", 403);
-        lookUpMap.put( "lock-denied", 409);
-        lookUpMap.put( "resource-denied", 409);
-        lookUpMap.put( "rollback-failed", 500);
-        lookUpMap.put( "data-exists", 409);
-        lookUpMap.put( "data-missing", 409);
-        lookUpMap.put( "operation-not-supported", 501);
-        lookUpMap.put( "operation-failed", 500);
-        lookUpMap.put( "partial-operation", 500);
-        lookUpMap.put( "malformed-message", 400);
-
-        for( ErrorTag tag : ErrorTag.values() )
-        {
-            Integer expectedStatusCode = lookUpMap.get( tag.getTagValue() );
-            assertNotNull( "Failed to find " + tag.getTagValue(), expectedStatusCode );
-            assertEquals( "Status Code does not match", expectedStatusCode,
-                          Integer.valueOf( tag.getStatusCode() ) );
+    public void testErrorTagStatusCodes() {
+        Map<String, Integer> lookUpMap = new HashMap<String, Integer>();
+
+        lookUpMap.put("in-use", 409);
+        lookUpMap.put("invalid-value", 400);
+        lookUpMap.put("too-big", 413);
+        lookUpMap.put("missing-attribute", 400);
+        lookUpMap.put("bad-attribute", 400);
+        lookUpMap.put("unknown-attribute", 400);
+        lookUpMap.put("bad-element", 400);
+        lookUpMap.put("unknown-element", 400);
+        lookUpMap.put("unknown-namespace", 400);
+        lookUpMap.put("access-denied", 403);
+        lookUpMap.put("lock-denied", 409);
+        lookUpMap.put("resource-denied", 409);
+        lookUpMap.put("rollback-failed", 500);
+        lookUpMap.put("data-exists", 409);
+        lookUpMap.put("data-missing", 409);
+        lookUpMap.put("operation-not-supported", 501);
+        lookUpMap.put("operation-failed", 500);
+        lookUpMap.put("partial-operation", 500);
+        lookUpMap.put("malformed-message", 400);
+
+        for (ErrorTag tag : ErrorTag.values()) {
+            Integer expectedStatusCode = lookUpMap.get(tag.getTagValue());
+            assertNotNull("Failed to find " + tag.getTagValue(), expectedStatusCode);
+            assertEquals("Status Code does not match", expectedStatusCode, Integer.valueOf(tag.getStatusCode()));
         }
     }
 
     @Test
-    public void testRestConfDocumentedException_NoCause()
-    {
+    public void testRestConfDocumentedException_NoCause() {
         String expectedMessage = "Message";
         ErrorType expectedErrorType = ErrorType.RPC;
         ErrorTag expectedErrorTag = ErrorTag.IN_USE;
-        RestconfError e =
-                new RestconfError( expectedErrorType,
-                                                 expectedErrorTag, expectedMessage );
+        RestconfError e = new RestconfError(expectedErrorType, expectedErrorTag, expectedMessage);
 
-        validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag,
-                              null, (String)null, e);
+        validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag, null, (String) null, e);
     }
 
     @Test
-    public void testRestConfDocumentedException_WithAppTag()
-    {
+    public void testRestConfDocumentedException_WithAppTag() {
         String expectedMessage = "Message";
         ErrorType expectedErrorType = ErrorType.RPC;
         ErrorTag expectedErrorTag = ErrorTag.IN_USE;
         String expectedErrorAppTag = "application.tag";
 
-        RestconfError e =
-                new RestconfError( expectedErrorType,
-                                                 expectedErrorTag, expectedMessage, expectedErrorAppTag );
+        RestconfError e = new RestconfError(expectedErrorType, expectedErrorTag, expectedMessage, expectedErrorAppTag);
 
-        validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag,
-                              expectedErrorAppTag, (String)null, e);
+        validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag, expectedErrorAppTag, (String) null,
+                e);
     }
 
     @Test
-    public void testRestConfDocumentedException_WithAppTagErrorInfo()
-    {
+    public void testRestConfDocumentedException_WithAppTagErrorInfo() {
         String expectedMessage = "Message";
         ErrorType expectedErrorType = ErrorType.RPC;
         ErrorTag expectedErrorTag = ErrorTag.IN_USE;
         String expectedErrorAppTag = "application.tag";
         String errorInfo = "<extra><sessionid>session.id</sessionid></extra>";
 
-        RestconfError e = new RestconfError( expectedErrorType,
-                                             expectedErrorTag,
-                                             expectedMessage,
-                                             expectedErrorAppTag,
-                                             errorInfo );
+        RestconfError e = new RestconfError(expectedErrorType, expectedErrorTag, expectedMessage, expectedErrorAppTag,
+                errorInfo);
 
-        validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag,
-                expectedErrorAppTag, errorInfo, e);
+        validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag, expectedErrorAppTag, errorInfo, e);
     }
 
     @Test
     public void testRestConfErrorWithRpcError() {
 
         // All fields set
-        RpcError rpcError = getRpcError( "mock app-tag", ErrorTag.BAD_ATTRIBUTE.getTagValue(),
-                                         "mock error-info", RpcError.ErrorSeverity.ERROR,
-                                         "mock error-message", RpcError.ErrorType.PROTOCOL,
-                                         new Exception( "mock cause" ) );
+        RpcError rpcError = RpcResultBuilder.newError(
+                RpcError.ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE.getTagValue(), "mock error-message",
+                "mock app-tag", "mock error-info", new Exception( "mock cause" ) );
 
-        validateRestConfError( "mock error-message", ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE,
-                               "mock app-tag", "mock error-info",
-                               new RestconfError( rpcError ) );
+        validateRestConfError("mock error-message", ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE, "mock app-tag",
+                "mock error-info", new RestconfError(rpcError));
 
         // All fields set except 'info' - expect error-info set to 'cause'
-        rpcError = getRpcError( "mock app-tag", ErrorTag.BAD_ATTRIBUTE.getTagValue(),
-                                null, RpcError.ErrorSeverity.ERROR,
-                                "mock error-message", RpcError.ErrorType.PROTOCOL,
-                                new Exception( "mock cause" ) );
+        rpcError = RpcResultBuilder.newError(
+                RpcError.ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE.getTagValue(), "mock error-message",
+                "mock app-tag", null, new Exception( "mock cause" ) );
 
-        validateRestConfError( "mock error-message", ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE,
-                               "mock app-tag", new Contains( "mock cause" ),
-                               new RestconfError( rpcError ) );
+        validateRestConfError("mock error-message", ErrorType.PROTOCOL, ErrorTag.BAD_ATTRIBUTE, "mock app-tag",
+                new Contains("mock cause"), new RestconfError(rpcError));
 
         // Some fields set - expect error-info set to ErrorSeverity
-        rpcError = getRpcError( null, ErrorTag.ACCESS_DENIED.getTagValue(),
-                                null, RpcError.ErrorSeverity.ERROR,
-                                null, RpcError.ErrorType.RPC, null );
+        rpcError = RpcResultBuilder.newError(
+                RpcError.ErrorType.RPC, ErrorTag.ACCESS_DENIED.getTagValue(), null, null, null, null );
 
-        validateRestConfError( null, ErrorType.RPC, ErrorTag.ACCESS_DENIED,
-                               null, "<severity>error</severity>",
-                               new RestconfError( rpcError ) );
+        validateRestConfError(null, ErrorType.RPC, ErrorTag.ACCESS_DENIED, null, "<severity>error</severity>",
+                new RestconfError(rpcError));
 
-        // 'tag' field not mapped to ErrorTag - expect error-tag set to OPERATION_FAILED
-        rpcError = getRpcError( null, "not mapped",
-                                null, RpcError.ErrorSeverity.WARNING,
-                                null, RpcError.ErrorType.TRANSPORT, null );
+        // 'tag' field not mapped to ErrorTag - expect error-tag set to
+        // OPERATION_FAILED
+        rpcError = RpcResultBuilder.newWarning(
+                RpcError.ErrorType.TRANSPORT, "not mapped", null, null, null, null );
 
-        validateRestConfError( null, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED,
-                               null, "<severity>warning</severity>",
-                               new RestconfError( rpcError ) );
+        validateRestConfError(null, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED, null,
+                "<severity>warning</severity>", new RestconfError(rpcError));
 
         // No fields set - edge case
-        rpcError = getRpcError( null, null, null, null, null, null, null );
+        rpcError = RpcResultBuilder.newError( null, null, null, null, null, null );
 
         validateRestConfError( null, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED,
-                               null, (String)null, new RestconfError( rpcError ) );
+                               null, "<severity>error</severity>", new RestconfError( rpcError ) );
     }
 
-    private void validateRestConfError(String expectedMessage, ErrorType expectedErrorType,
-            ErrorTag expectedErrorTag, String expectedErrorAppTag, String errorInfo, RestconfError e) {
+    private void validateRestConfError(String expectedMessage, ErrorType expectedErrorType, ErrorTag expectedErrorTag,
+            String expectedErrorAppTag, String errorInfo, RestconfError e) {
 
-        validateRestConfError( expectedMessage, expectedErrorType, expectedErrorTag,
-                               expectedErrorAppTag, equalTo( errorInfo ), e );
+        validateRestConfError(expectedMessage, expectedErrorType, expectedErrorTag, expectedErrorAppTag,
+                equalTo(errorInfo), e);
     }
 
-    private void validateRestConfError(String expectedMessage, ErrorType expectedErrorType,
-            ErrorTag expectedErrorTag, String expectedErrorAppTag,
-            Matcher<String> errorInfoMatcher, RestconfError e) {
+    private void validateRestConfError(String expectedMessage, ErrorType expectedErrorType, ErrorTag expectedErrorTag,
+            String expectedErrorAppTag, Matcher<String> errorInfoMatcher, RestconfError e) {
 
-        assertEquals( "getErrorMessage", expectedMessage, e.getErrorMessage() );
-        assertEquals( "getErrorType", expectedErrorType, e.getErrorType() );
-        assertEquals( "getErrorTag", expectedErrorTag, e.getErrorTag() );
-        assertEquals( "getErrorAppTag", expectedErrorAppTag, e.getErrorAppTag() );
-        assertThat( "getErrorInfo", e.getErrorInfo(), errorInfoMatcher );
-        e.toString(); // really just checking for NPE etc. Don't care about contents.
+        assertEquals("getErrorMessage", expectedMessage, e.getErrorMessage());
+        assertEquals("getErrorType", expectedErrorType, e.getErrorType());
+        assertEquals("getErrorTag", expectedErrorTag, e.getErrorTag());
+        assertEquals("getErrorAppTag", expectedErrorAppTag, e.getErrorAppTag());
+        assertThat("getErrorInfo", e.getErrorInfo(), errorInfoMatcher);
+        e.toString(); // really just checking for NPE etc. Don't care about
+                      // contents.
     }
 }
index e2559f4b70ab27e2e6d990996e84bd8fbfb47045..3794815c894fe1c4cb727a97e423d265c8e6587c 100644 (file)
@@ -16,7 +16,6 @@ import static org.mockito.Mockito.when;
 
 import java.io.FileNotFoundException;
 import java.util.Set;
-
 import org.junit.Before;
 import org.junit.BeforeClass;
 import org.junit.Test;
@@ -40,33 +39,27 @@ public class RestconfImplTest {
 
     @BeforeClass
     public static void init() throws FileNotFoundException {
-        Set<Module> allModules = TestUtils
-                .loadModulesFrom("/full-versions/yangs");
+        Set<Module> allModules = TestUtils.loadModulesFrom("/full-versions/yangs");
         assertNotNull(allModules);
         SchemaContext schemaContext = TestUtils.loadSchemaContext(allModules);
-        controllerContext = spy( ControllerContext.getInstance() );
+        controllerContext = spy(ControllerContext.getInstance());
         controllerContext.setSchemas(schemaContext);
 
     }
 
     @Before
-    public void initMethod()
-    {
+    public void initMethod() {
         restconfImpl = RestconfImpl.getInstance();
-        restconfImpl.setControllerContext( controllerContext );
+        restconfImpl.setControllerContext(controllerContext);
     }
 
     @Test
     public void testExample() throws FileNotFoundException {
-        CompositeNode loadedCompositeNode = TestUtils.readInputToCnSn(
-                "/parts/ietf-interfaces_interfaces.xml",
+        CompositeNode loadedCompositeNode = TestUtils.readInputToCnSn("/parts/ietf-interfaces_interfaces.xml",
                 XmlToCompositeNodeProvider.INSTANCE);
         BrokerFacade brokerFacade = mock(BrokerFacade.class);
-        when(brokerFacade.readOperationalData(any(InstanceIdentifier.class)))
-                .thenReturn(loadedCompositeNode);
-        assertEquals(loadedCompositeNode,
-                brokerFacade.readOperationalData(null));
+        when(brokerFacade.readOperationalData(any(InstanceIdentifier.class))).thenReturn(loadedCompositeNode);
+        assertEquals(loadedCompositeNode, brokerFacade.readOperationalData(null));
     }
 
-
 }
index 853c19f93530c16449840b1043ac07d30edaab4f..ed1529540dc4fedde6fa803b909b5827e1241c79 100644 (file)
@@ -13,6 +13,7 @@ import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
+import com.google.common.base.Preconditions;
 import java.io.BufferedReader;
 import java.io.ByteArrayOutputStream;
 import java.io.File;
@@ -27,7 +28,8 @@ import java.sql.Date;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Set;
-
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 import javax.ws.rs.WebApplicationException;
 import javax.ws.rs.ext.MessageBodyReader;
 import javax.ws.rs.ext.MessageBodyWriter;
@@ -40,7 +42,6 @@ import javax.xml.transform.TransformerException;
 import javax.xml.transform.TransformerFactory;
 import javax.xml.transform.dom.DOMSource;
 import javax.xml.transform.stream.StreamResult;
-
 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
 import org.opendaylight.controller.sal.restconf.impl.CompositeNodeWrapper;
@@ -61,8 +62,6 @@ import org.slf4j.LoggerFactory;
 import org.w3c.dom.Document;
 import org.xml.sax.SAXException;
 
-import com.google.common.base.Preconditions;
-
 public final class TestUtils {
 
     private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
@@ -148,10 +147,9 @@ public final class TestUtils {
 
     /**
      *
-     * Fill missing data (namespaces) and build correct data type in
-     * {@code compositeNode} according to {@code dataSchemaNode}. The method
-     * {@link RestconfImpl#createConfigurationData createConfigurationData} is
-     * used because it contains calling of method {code normalizeNode}
+     * Fill missing data (namespaces) and build correct data type in {@code compositeNode} according to
+     * {@code dataSchemaNode}. The method {@link RestconfImpl#createConfigurationData createConfigurationData} is used
+     * because it contains calling of method {code normalizeNode}
      */
     public static void normalizeCompositeNode(CompositeNode compositeNode, Set<Module> modules, String schemaNodePath) {
         RestconfImpl restconf = RestconfImpl.getInstance();
@@ -162,9 +160,8 @@ public final class TestUtils {
     }
 
     /**
-     * Searches module with name {@code searchedModuleName} in {@code modules}.
-     * If module name isn't specified and module set has only one element then
-     * this element is returned.
+     * Searches module with name {@code searchedModuleName} in {@code modules}. If module name isn't specified and
+     * module set has only one element then this element is returned.
      *
      */
     public static Module resolveModule(String searchedModuleName, Set<Module> modules) {
@@ -280,8 +277,8 @@ public final class TestUtils {
 
         ControllerContext.getInstance().setSchemas(loadSchemaContext(modules));
 
-        messageBodyWriter.writeTo(new StructuredData(compositeNode, dataSchemaNode, null), null, null, null, null, null,
-                byteArrayOS);
+        messageBodyWriter.writeTo(new StructuredData(compositeNode, dataSchemaNode, null), null, null, null, null,
+                null, byteArrayOS);
 
         return byteArrayOS.toString();
     }
@@ -297,6 +294,22 @@ public final class TestUtils {
         }
         bufReader.close();
         return result.toString();
+    }
+
+    private static Pattern patternForStringsSeparatedByWhiteChars(String... substrings) {
+        StringBuilder pattern = new StringBuilder();
+        pattern.append(".*");
+        for (String substring : substrings) {
+            pattern.append(substring);
+            pattern.append("\\s*");
+        }
+        pattern.append(".*");
+        return Pattern.compile(pattern.toString(), Pattern.DOTALL);
+    }
 
+    public static boolean containsStringData(String jsonOutput, String... substrings) {
+        Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
+        Matcher matcher = pattern.matcher(jsonOutput);
+        return matcher.matches();
     }
 }
index 33d4b325bef2c6abc6424c044e8a572acb619ac2..18703040ee89ef6c7fff33bb57d9ced739aa6d0f 100644 (file)
@@ -14,9 +14,9 @@ import static org.mockito.Matchers.any;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
+import com.google.common.collect.Iterables;
 import java.io.FileNotFoundException;
 import java.util.Set;
-
 import org.junit.BeforeClass;
 import org.junit.Rule;
 import org.junit.Test;
@@ -131,7 +131,7 @@ public class URITest {
         initMountService(true);
         InstanceIdWithSchemaNode instanceIdentifier = controllerContext
                 .toInstanceIdentifier("simple-nodes:users/yang-ext:mount/");
-        assertEquals(true, instanceIdentifier.getInstanceIdentifier().getPath().isEmpty());
+        assertTrue(Iterables.isEmpty(instanceIdentifier.getInstanceIdentifier().getPathArguments()));
     }
 
     @Test
@@ -152,7 +152,7 @@ public class URITest {
                 .toInstanceIdentifier("simple-nodes:users/yang-ext:mount/test-interface2:class");
     }
 
-    public void initMountService(boolean withSchema) {
+    public void initMountService(final boolean withSchema) {
         MountService mountService = mock(MountService.class);
         controllerContext.setMountService(mountService);
         BrokerFacade brokerFacade = mock(BrokerFacade.class);
@@ -163,10 +163,11 @@ public class URITest {
         Set<Module> modules2 = TestUtils.loadModulesFrom("/test-config-data/yang2");
         SchemaContext schemaContext2 = TestUtils.loadSchemaContext(modules2);
         MountInstance mountInstance = mock(MountInstance.class);
-        if (withSchema)
+        if (withSchema) {
             when(mountInstance.getSchemaContext()).thenReturn(schemaContext2);
-        else
+        } else {
             when(mountInstance.getSchemaContext()).thenReturn(null);
+        }
         when(mountService.getMountPoint(any(InstanceIdentifier.class))).thenReturn(mountInstance);
     }
 }
index 5476d71320e9ae7a3a0fce6a9ec87f8dfe80088f..0799fdcff875b02ba6fb134c8f63f593660109d2 100644 (file)
@@ -15,9 +15,7 @@ import java.io.IOException;
 import java.net.URISyntaxException;
 import java.util.List;
 import java.util.Map;
-
 import javax.ws.rs.WebApplicationException;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
index e5a737e6d5d868be87fad55215d9be8b952bd0fd..483d90da0d220fc1054929d01008afabb5871175 100644 (file)
@@ -11,9 +11,7 @@ import static org.junit.Assert.assertEquals;
 
 import java.io.IOException;
 import java.net.URISyntaxException;
-
 import javax.ws.rs.WebApplicationException;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.JsonToCompositeNodeProvider;
index d5759bedb11342ae08eb5bb057ab13ee0a84813f..efcc3743c6938907e25d8dbd6af9e500e3549780 100644 (file)
@@ -11,7 +11,6 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 
 import java.util.Set;
-
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
 
index 9b382d210ebd5de7c88c01a814a16aecc4194a3f..ae07571ad93efc192cb0c395420048e8a437631e 100644 (file)
@@ -7,6 +7,8 @@
  */
 package org.opendaylight.controller.sal.restconf.impl.test.structures;
 
+import static org.junit.Assert.assertFalse;
+
 import java.util.HashMap;
 import java.util.Map;
 
@@ -56,10 +58,12 @@ public class LstItem {
     }
 
     public void addLfLst(LfLst lfLst) {
+        assertFalse("Found multiple leaf list elements for " + lfLst.getName(), lfLsts.containsKey(lfLst.getName()));
         lfLsts.put(lfLst.getName(), lfLst);
     }
 
     public void addLst(Lst lst) {
+        assertFalse("Found multiple list elements for " + lst.getName(), lsts.containsKey(lst.getName()));
         lsts.put(lst.getName(), lst);
     }
 
index 845d54ea1f568388ff6c7ba1400f0e76cac9ccf5..664aad6578c84fab98a3e569d00fa93dd3a1ee8d 100644 (file)
@@ -23,15 +23,13 @@ import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
 import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
 import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
 import io.netty.handler.codec.http.websocketx.WebSocketVersion;
-
 import java.io.BufferedReader;
 import java.io.InputStreamReader;
 import java.net.URI;
-
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class WebSocketClient  {
+public class WebSocketClient {
 
     private final URI uri;
     private Bootstrap bootstrap = new Bootstrap();;
@@ -40,51 +38,57 @@ public class WebSocketClient  {
     private Channel clientChannel;
     private final EventLoopGroup group = new NioEventLoopGroup();
 
-    public WebSocketClient(URI uri,IClientMessageCallback clientMessageCallback) {
+    public WebSocketClient(URI uri, IClientMessageCallback clientMessageCallback) {
         this.uri = uri;
-        clientHandler = new WebSocketClientHandler(
-                WebSocketClientHandshakerFactory.newHandshaker(
-                        uri, WebSocketVersion.V13, null, false,null),clientMessageCallback); // last null could be replaced with DefaultHttpHeaders
+        clientHandler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(uri,
+                WebSocketVersion.V13, null, false, null), clientMessageCallback); // last
+                                                                                  // null
+                                                                                  // could
+                                                                                  // be
+                                                                                  // replaced
+                                                                                  // with
+                                                                                  // DefaultHttpHeaders
         initialize();
     }
-    private void initialize(){
+
+    private void initialize() {
 
         String protocol = uri.getScheme();
         if (!"http".equals(protocol)) {
             throw new IllegalArgumentException("Unsupported protocol: " + protocol);
         }
 
-        bootstrap.group(group)
-                .channel(NioSocketChannel.class)
-                .handler(new ChannelInitializer<SocketChannel>() {
-                    @Override
-                    public void initChannel(SocketChannel ch) throws Exception {
-                        ChannelPipeline pipeline = ch.pipeline();
-                        pipeline.addLast("http-codec", new HttpClientCodec());
-                        pipeline.addLast("aggregator", new HttpObjectAggregator(8192));
-                        pipeline.addLast("ws-handler", clientHandler);
-                    }
-                });
+        bootstrap.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {
+            @Override
+            public void initChannel(SocketChannel ch) throws Exception {
+                ChannelPipeline pipeline = ch.pipeline();
+                pipeline.addLast("http-codec", new HttpClientCodec());
+                pipeline.addLast("aggregator", new HttpObjectAggregator(8192));
+                pipeline.addLast("ws-handler", clientHandler);
+            }
+        });
     }
-    public void connect() throws InterruptedException{
+
+    public void connect() throws InterruptedException {
         System.out.println("WebSocket Client connecting");
-        clientChannel  = bootstrap.connect(uri.getHost(), uri.getPort()).sync().channel();
+        clientChannel = bootstrap.connect(uri.getHost(), uri.getPort()).sync().channel();
         clientHandler.handshakeFuture().sync();
     }
 
-    public void writeAndFlush(String message){
+    public void writeAndFlush(String message) {
         clientChannel.writeAndFlush(new TextWebSocketFrame(message));
     }
-    public void writeAndFlush(Object message){
+
+    public void writeAndFlush(Object message) {
         clientChannel.writeAndFlush(message);
     }
 
-    public void ping(){
-        clientChannel.writeAndFlush(new PingWebSocketFrame(Unpooled.copiedBuffer(new byte[]{1, 2, 3, 4, 5, 6})));
+    public void ping() {
+        clientChannel.writeAndFlush(new PingWebSocketFrame(Unpooled.copiedBuffer(new byte[] { 1, 2, 3, 4, 5, 6 })));
     }
 
     public void close(String reasonText) throws InterruptedException {
-        CloseWebSocketFrame closeWebSocketFrame = new CloseWebSocketFrame(1000,reasonText);
+        CloseWebSocketFrame closeWebSocketFrame = new CloseWebSocketFrame(1000, reasonText);
         clientChannel.writeAndFlush(closeWebSocketFrame);
 
         // WebSocketClientHandler will close the connection when the server
@@ -122,7 +126,7 @@ public class WebSocketClient  {
         @Override
         public void onMessageReceived(Object message) {
             if (message instanceof TextWebSocketFrame) {
-                logger.info("received message {}"+ ((TextWebSocketFrame)message).text());
+                logger.info("received message {}" + ((TextWebSocketFrame) message).text());
             }
         }
     }
index 0a16e254ccc6cd6c1a2f838cb04917477ce7869d..e07d8c48f0f2c9ba253a1282f4bf0e453ae19e3f 100644 (file)
@@ -18,7 +18,6 @@ import io.netty.handler.codec.http.websocketx.PongWebSocketFrame;
 import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
 import io.netty.handler.codec.http.websocketx.WebSocketFrame;
 import io.netty.util.CharsetUtil;
-
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -29,8 +28,7 @@ public class WebSocketClientHandler extends SimpleChannelInboundHandler<Object>
     private ChannelPromise handshakeFuture;
     private final IClientMessageCallback messageListener;
 
-
-    public WebSocketClientHandler(WebSocketClientHandshaker handshaker,IClientMessageCallback listener) {
+    public WebSocketClientHandler(WebSocketClientHandshaker handshaker, IClientMessageCallback listener) {
         this.handshaker = handshaker;
         this.messageListener = listener;
     }
@@ -92,4 +90,3 @@ public class WebSocketClientHandler extends SimpleChannelInboundHandler<Object>
         ctx.close();
     }
 }
-
index d9ef2ef243986bb63960f8212f4ab2bbf81346f6..70f0f050dc9fdea84f186537eafbcad6779d7e53 100644 (file)
@@ -15,12 +15,10 @@ import static org.mockito.Mockito.mock;
 import java.io.FileNotFoundException;
 import java.io.UnsupportedEncodingException;
 import java.net.URI;
-
 import javax.ws.rs.client.Entity;
 import javax.ws.rs.core.Application;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
-
 import org.glassfish.jersey.server.ResourceConfig;
 import org.glassfish.jersey.test.JerseyTest;
 import org.junit.BeforeClass;
@@ -55,10 +53,10 @@ public class RestStream extends JerseyTest {
     @Override
     protected Application configure() {
         /* enable/disable Jersey logs to console */
-//         enable(TestProperties.LOG_TRAFFIC);
-//         enable(TestProperties.DUMP_ENTITY);
-//         enable(TestProperties.RECORD_LOG_LEVEL);
-//         set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
+        // enable(TestProperties.LOG_TRAFFIC);
+        // enable(TestProperties.DUMP_ENTITY);
+        // enable(TestProperties.RECORD_LOG_LEVEL);
+        // set(TestProperties.RECORD_LOG_LEVEL, Level.ALL.intValue());
         ResourceConfig resourceConfig = new ResourceConfig();
         resourceConfig = resourceConfig.registerInstances(restconfImpl, StructuredDataToXmlProvider.INSTANCE,
                 StructuredDataToJsonProvider.INSTANCE, XmlToCompositeNodeProvider.INSTANCE,
@@ -72,13 +70,15 @@ public class RestStream extends JerseyTest {
         Response responseWithStreamName = post(uri, MediaType.APPLICATION_XML, getRpcInput());
         String xmlResponse = responseWithStreamName.readEntity(String.class);
         assertNotNull(xmlResponse);
-        assertTrue(xmlResponse.contains("<stream-name>ietf-interfaces:interfaces/ietf-interfaces:interface/eth0</stream-name>"));
+        assertTrue(xmlResponse
+                .contains("<stream-name>ietf-interfaces:interfaces/ietf-interfaces:interface/eth0</stream-name>"));
 
         uri = "/streams/stream/ietf-interfaces:interfaces/ietf-interfaces:interface/eth0";
         Response responseWithRedirectionUri = get(uri, MediaType.APPLICATION_XML);
         final URI websocketServerUri = responseWithRedirectionUri.getLocation();
         assertNotNull(websocketServerUri);
-        assertEquals(websocketServerUri.toString(), "http://localhost:8181/ietf-interfaces:interfaces/ietf-interfaces:interface/eth0");
+        assertEquals(websocketServerUri.toString(),
+                "http://localhost:8181/ietf-interfaces:interfaces/ietf-interfaces:interface/eth0");
     }
 
     private Response post(String uri, String mediaType, String data) {
index 62159ccad6c0edf76e4e8ac75282935e80c06450..5a5a621d930b68fc240140f76b086a0d57bc0a3c 100644 (file)
@@ -10,7 +10,6 @@ package org.opendaylight.controller.sal.restconf.impl.xml.to.cnsn.test;
 import static org.junit.Assert.assertNotNull;
 
 import java.util.Set;
-
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
 import org.opendaylight.controller.sal.restconf.impl.test.TestUtils;
@@ -21,13 +20,12 @@ public class XmlAugmentedElementToCnSnTest {
 
     @Test
     public void loadDataAugmentedSchemaMoreEqualNamesTest() {
-        loadAndNormalizeData("/common/augment/xml/dataa.xml", "/common/augment/yang", "main","cont");
-        loadAndNormalizeData("/common/augment/xml/datab.xml", "/common/augment/yang", "main","cont");
+        loadAndNormalizeData("/common/augment/xml/dataa.xml", "/common/augment/yang", "main", "cont");
+        loadAndNormalizeData("/common/augment/xml/datab.xml", "/common/augment/yang", "main", "cont");
     }
 
     private void loadAndNormalizeData(String xmlPath, String yangPath, String topLevelElementName, String moduleName) {
-        CompositeNode compNode = TestUtils.readInputToCnSn(xmlPath, false,
-                XmlToCompositeNodeProvider.INSTANCE);
+        CompositeNode compNode = TestUtils.readInputToCnSn(xmlPath, false, XmlToCompositeNodeProvider.INSTANCE);
         assertNotNull(compNode);
         Set<Module> modules = TestUtils.loadModulesFrom(yangPath);
 
@@ -35,5 +33,4 @@ public class XmlAugmentedElementToCnSnTest {
         TestUtils.normalizeCompositeNode(compNode, modules, topLevelElementName + ":" + moduleName);
     }
 
-
 }
index e5b0bf507d03212bf2efedaaa18cc2f28f734567..6c11bc1861995879818ce31b3d6d75696c2decf7 100644 (file)
@@ -13,7 +13,6 @@ import static org.junit.Assert.assertTrue;
 
 import java.util.List;
 import java.util.Set;
-
 import org.junit.Ignore;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
@@ -30,8 +29,7 @@ public class XmlLeafrefToCnSnTest {
     private static final Logger LOG = LoggerFactory.getLogger(XmlLeafrefToCnSnTest.class);
 
     /**
-     * top level element represents container. second level element is list with
-     * two elements.
+     * top level element represents container. second level element is list with two elements.
      */
     @Test
     public void testXmlDataContainer() {
@@ -202,8 +200,7 @@ public class XmlLeafrefToCnSnTest {
 
     /**
      *
-     * Test case like <lf11 xmlns="namespace1"
-     * xmlns:x="namespace">identity</lf11>
+     * Test case like <lf11 xmlns="namespace1" xmlns:x="namespace">identity</lf11>
      */
 
     @Test
@@ -214,8 +211,7 @@ public class XmlLeafrefToCnSnTest {
 
     /**
      *
-     * Test case like <cont1 xmlns="namespace1"> <lf11
-     * xmlns:x="namespace">identity</lf11> </cont1>
+     * Test case like <cont1 xmlns="namespace1"> <lf11 xmlns:x="namespace">identity</lf11> </cont1>
      */
     @Test
     public void testIdentityrefDefaultNmspcInParrentElement() {
@@ -225,8 +221,7 @@ public class XmlLeafrefToCnSnTest {
 
     /**
      *
-     * Test case like <cont1 xmlns="namespace1" xmlns:x="namespace">
-     * <lf11>x:identity</lf11> </cont1>
+     * Test case like <cont1 xmlns="namespace1" xmlns:x="namespace"> <lf11>x:identity</lf11> </cont1>
      */
     @Ignore
     @Test
@@ -237,8 +232,7 @@ public class XmlLeafrefToCnSnTest {
 
     /**
      *
-     * Test case like (without namespace in xml) <cont1> <lf11>x:identity</lf11>
-     * </cont1>
+     * Test case like (without namespace in xml) <cont1> <lf11>x:identity</lf11> </cont1>
      */
     @Test
     public void testIdentityrefNoNmspcValueWithPrefix() {
@@ -248,8 +242,7 @@ public class XmlLeafrefToCnSnTest {
 
     /**
      *
-     * Test case like (without namespace in xml) <cont1> <lf11>identity</lf11>
-     * </cont1>
+     * Test case like (without namespace in xml) <cont1> <lf11>identity</lf11> </cont1>
      */
     @Test
     public void testIdentityrefNoNmspcValueWithoutPrefix() {
@@ -322,8 +315,8 @@ public class XmlLeafrefToCnSnTest {
         assertEquals((short) 100, cont1_lf11.getValue());
     }
 
-    private void testIdentityrefToCnSn(final String xmlPath, final String yangPath, final String moduleName, final String schemaName,
-            final int moduleCount, final String resultLocalName, final String resultNamespace) {
+    private void testIdentityrefToCnSn(final String xmlPath, final String yangPath, final String moduleName,
+            final String schemaName, final int moduleCount, final String resultLocalName, final String resultNamespace) {
         CompositeNode compositeNode = TestUtils.readInputToCnSn(xmlPath, false, XmlToCompositeNodeProvider.INSTANCE);
         assertNotNull(compositeNode);
 
index 5cda4a7f52014dc4a9ab3572d9073877ec12e74e..e2621d635bc3dab04629beffcb15c3d111b9eb21 100644 (file)
@@ -14,7 +14,6 @@ import static org.junit.Assert.assertTrue;
 
 import java.io.ByteArrayInputStream;
 import java.io.InputStream;
-
 import org.junit.BeforeClass;
 import org.junit.Test;
 import org.opendaylight.controller.sal.rest.impl.XmlToCompositeNodeProvider;
@@ -57,26 +56,26 @@ public class XmlToCnSnTest extends YangAndXmlAndDataSchemaLoader {
     }
 
     @Test
-    public void testXmlBlankInput() throws Exception{
-        InputStream inputStream = new ByteArrayInputStream( "".getBytes() );
-        CompositeNode compositeNode =
-                XmlToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null, inputStream);
+    public void testXmlBlankInput() throws Exception {
+        InputStream inputStream = new ByteArrayInputStream("".getBytes());
+        CompositeNode compositeNode = XmlToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null,
+                inputStream);
 
-        assertNull( compositeNode );
+        assertNull(compositeNode);
     }
 
     @Test
-    public void testXmlBlankInputUnmarkableStream() throws Exception{
-        InputStream inputStream = new ByteArrayInputStream( "".getBytes() ){
+    public void testXmlBlankInputUnmarkableStream() throws Exception {
+        InputStream inputStream = new ByteArrayInputStream("".getBytes()) {
             @Override
             public boolean markSupported() {
                 return false;
             }
         };
-        CompositeNode compositeNode =
-                XmlToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null, inputStream);
+        CompositeNode compositeNode = XmlToCompositeNodeProvider.INSTANCE.readFrom(null, null, null, null, null,
+                inputStream);
 
-        assertNull( compositeNode );
+        assertNull(compositeNode);
     }
 
 }
index 9bdea8157910f1db92ce1458876014ece1dc6487..cf6e513b30a1bdc6f10f7725bba73d54aaefac2c 100644 (file)
@@ -269,6 +269,10 @@ module simple-data-types {
         }
     }
          
-         
+       anyxml complex-any;
+       
+       anyxml simple-any;
+       
+       anyxml empty-any;
   }
 }
\ No newline at end of file
index 28d355dbab0a44375559dad7e57670f87cc7b047..ed02ca35f6f13ba2d82bd358e05fb159df537587 100644 (file)
@@ -23,7 +23,6 @@
     <lfenum>enum3</lfenum>
     <lfbits>bit3 bit2</lfbits>
     <lfbinary>ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz</lfbinary>
-    <lfempty />
     <lfunion1>324</lfunion1>
     <lfunion2>33.3</lfunion2>
     <lfunion3>55</lfunion3>
     <lfunion12>false</lfunion12>
     <lfunion13>b1</lfunion13>
     <lfunion14>zero</lfunion14>
+    <lfempty />
     <identityref1 xmlns:x="simple:data:types">x:iden</identityref1>
-</cont>
\ No newline at end of file
+    <complex-any>
+      <data>
+        <leaf1>leaf1-value</leaf1>
+        <leaf2>leaf2-value</leaf2>
+
+        <leaf-list>leaf-list-value1</leaf-list>
+        <leaf-list>leaf-list-value2</leaf-list>
+
+        <list>
+            <nested-list>
+                <nested-leaf>nested-value1</nested-leaf>
+            </nested-list>
+            <nested-list>
+                <nested-leaf>nested-value2</nested-leaf>
+            </nested-list>
+        </list>
+
+         <list>
+            <nested-list>
+                <nested-leaf>nested-value3</nested-leaf>
+            </nested-list>
+            <nested-list>
+                <nested-leaf>nested-value4</nested-leaf>
+            </nested-list>
+        </list>
+      </data>
+    </complex-any>
+    <simple-any>simple</simple-any>
+    <empty-any></empty-any>
+</cont>
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/equal-data-node-names/equal-name-data-for-container.json b/opendaylight/md-sal/sal-rest-connector/src/test/resources/equal-data-node-names/equal-name-data-for-container.json
new file mode 100644 (file)
index 0000000..78b097d
--- /dev/null
@@ -0,0 +1,16 @@
+{
+    "cont":{
+        "cont1":[
+            {
+                "lst11":{
+                    "lf111":"value1"
+                }
+            },
+            {
+                "lst11":{
+                    "lf111":"value2"
+                }
+            }
+        ]
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/equal-data-node-names/equal-name-data-for-container.xml b/opendaylight/md-sal/sal-rest-connector/src/test/resources/equal-data-node-names/equal-name-data-for-container.xml
new file mode 100644 (file)
index 0000000..26a1f5f
--- /dev/null
@@ -0,0 +1,12 @@
+<cont>
+    <cont1>
+        <lst11>
+            <lf111>value1</lf111>
+        </lst11>
+    </cont1>
+    <cont1>
+        <lst11>
+            <lf111>value1</lf111>
+        </lst11>
+    </cont1>
+</cont>
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/equal-data-node-names/equal-name-data-for-leaf.json b/opendaylight/md-sal/sal-rest-connector/src/test/resources/equal-data-node-names/equal-name-data-for-leaf.json
new file mode 100644 (file)
index 0000000..d0a9fd4
--- /dev/null
@@ -0,0 +1,15 @@
+{
+    "cont":{
+        "cont1":{
+            "lst11":[
+             {
+                "lf111":"value1",
+                "lf111":"value2"
+             },
+             {
+                "lf111":"value3"
+             }
+             ]
+         }
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/equal-data-node-names/equal-name-data-for-leaf.xml b/opendaylight/md-sal/sal-rest-connector/src/test/resources/equal-data-node-names/equal-name-data-for-leaf.xml
new file mode 100644 (file)
index 0000000..4221c2d
--- /dev/null
@@ -0,0 +1,11 @@
+<cont>
+    <cont1>
+        <lst11>
+          <lf111>value1</lf111>,
+          <lf111>value2</lf111>,
+        </lst11>
+        <lst11>
+          <lf111>value3</lf111>,
+        </lst11>
+    </cont1>
+</cont>
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/equal-data-node-names/yang/equal-data-node-names.yang b/opendaylight/md-sal/sal-rest-connector/src/test/resources/equal-data-node-names/yang/equal-data-node-names.yang
new file mode 100644 (file)
index 0000000..3a3653a
--- /dev/null
@@ -0,0 +1,18 @@
+/* bug 1204 */
+module equal-data-node-names {
+  namespace "ns:equal:data:node:names";
+
+  prefix "eqdanona";
+  revision 2014-06-26 {
+  }
+
+  container cont {
+    container cont1 {
+        list lst11 {
+            leaf lf111 {
+                type string;
+            }
+        }
+    }
+  }
+}
\ No newline at end of file
index 2e533e720e0760f6abca5b84663c52ce170a4899..baf7d1e9ae7a9f61ccdf8b33cdefe728e4c16cee 100644 (file)
@@ -4,7 +4,7 @@ module test-module {
 
   revision 2014-01-09 {
   }
-  
+
   container interfaces {
     container class {
         leaf name {
@@ -18,7 +18,7 @@ module test-module {
         }
     }
   }
-  
+
   container cont {
     container cont1 {
         leaf lf11 {
@@ -34,9 +34,18 @@ module test-module {
             type string;
         }
     }
-  }   
-  
+  }
   
+  list lst-with-composite-key {
+    key "key1 key2";
+    leaf key1 {
+        type string;
+    }
+    leaf key2 {
+        type uint8;
+    }
+  }
+
   rpc rpc-test {
     input {
       container cont {
@@ -48,16 +57,11 @@ module test-module {
                 type string;
             }
         }
-      }    
+      }
     }
     output {
         container cont-output {
         }
-    } 
-  
+    }
   }
-  
-  
-
 }
\ No newline at end of file
index 10d964d6449595e13971a80428046ac6508871a2..b886fc9da9621459dc12531c22ea1d6ac9d360e2 100644 (file)
@@ -1,5 +1,5 @@
 {
-       "cont": {       
-               "lf":                           
-       }
+    "cont": {
+        "lf":
+    }
 }
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-rest-connector/src/test/resources/multiple-nodes/multiple-nodes.yang b/opendaylight/md-sal/sal-rest-connector/src/test/resources/multiple-nodes/multiple-nodes.yang
new file mode 100644 (file)
index 0000000..22a1dae
--- /dev/null
@@ -0,0 +1,17 @@
+module multiple-nodes {
+    namespace "multiple:nodes";
+    prefix "mod1";
+    revision "2014-06-23";
+
+    container cont {
+        container cont1 {
+            leaf lf11 {
+                type string;
+            }
+        }
+
+        leaf lf1 {
+            type string;
+        }
+    }
+}
\ No newline at end of file
index 0e929afc8461c5da04bafa6dc44e7c782f83417d..8bac0d211e71cb2d88969c72d9b3f21a9fb00919 100644 (file)
@@ -14,7 +14,7 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-
+import org.apache.commons.lang3.BooleanUtils;
 import org.json.JSONArray;
 import org.json.JSONException;
 import org.json.JSONObject;
@@ -25,6 +25,7 @@ import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
 import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
@@ -85,6 +86,8 @@ public class ModelGenerator {
     private static final String NUMBER = "number";
     private static final String BOOLEAN = "boolean";
     private static final String STRING = "string";
+  private static final String ID_KEY = "id";
+  private static final String SUB_TYPES_KEY = "subTypes";
 
     private static final Map<Class<? extends TypeDefinition<?>>, String> YANG_TYPE_TO_JSON_TYPE_MAPPING;
 
@@ -115,6 +118,7 @@ public class ModelGenerator {
         JSONObject models = new JSONObject();
         processContainers(module, models);
         processRPCs(module, models);
+    processIdentities(module, models);
         return models;
     }
 
@@ -187,6 +191,58 @@ public class ModelGenerator {
         }
     }
 
+  /**
+   * Processes the 'identity' statement in a yang model
+   * and maps it to a 'model' in the Swagger JSON spec.
+   *
+   * @param module The module from which the identity stmt will be processed
+   * @param models The JSONObject in which the parsed identity will be put as a 'model' obj
+   * @throws JSONException
+   */
+  private void processIdentities(Module module, JSONObject models) throws JSONException {
+
+    String moduleName = module.getName();
+    Set<IdentitySchemaNode> idNodes =  module.getIdentities();
+    _logger.debug("Processing Identities for module {} . Found {} identity statements", moduleName, idNodes.size());
+
+    for(IdentitySchemaNode idNode : idNodes){
+      JSONObject identityObj=new JSONObject();
+      String identityName = idNode.getQName().getLocalName();
+      _logger.debug("Processing Identity: {}", identityName);
+
+      identityObj.put(ID_KEY, identityName);
+      identityObj.put(DESCRIPTION_KEY, idNode.getDescription());
+
+      JSONObject props = new JSONObject();
+      IdentitySchemaNode baseId = idNode.getBaseIdentity();
+
+
+      if(baseId==null) {
+        /**
+         * This is a base identity. So lets see if
+         * it has sub types. If it does, then add them to the model definition.
+         */
+        Set<IdentitySchemaNode> derivedIds = idNode.getDerivedIdentities();
+
+        if(derivedIds != null) {
+          JSONArray subTypes = new JSONArray();
+          for(IdentitySchemaNode derivedId : derivedIds){
+            subTypes.put(derivedId.getQName().getLocalName());
+          }
+          identityObj.put(SUB_TYPES_KEY, subTypes);
+        }
+      } else {
+        /**
+         * This is a derived entity. Add it's base type & move on.
+         */
+        props.put(TYPE_KEY, baseId.getQName().getLocalName());
+      }
+
+      //Add the properties. For a base type, this will be an empty object as required by the Swagger spec.
+      identityObj.put(PROPERTIES_KEY, props);
+      models.put(identityName, identityObj);
+    }
+  }
     /**
      * Processes the container node and populates the moduleJSON
      *
@@ -249,7 +305,7 @@ public class ModelGenerator {
                 if (node instanceof LeafSchemaNode) {
                     property = processLeafNode((LeafSchemaNode) node);
                 } else if (node instanceof ListSchemaNode) {
-                    property = processListSchemaNode((ListSchemaNode) node, moduleName, models);
+                    property = processListSchemaNode((ListSchemaNode) node, moduleName, models, isConfig);
 
                 } else if (node instanceof LeafListSchemaNode) {
                     property = processLeafListNode((LeafListSchemaNode) node);
@@ -354,15 +410,17 @@ public class ModelGenerator {
      *
      * @param listNode
      * @param moduleName
+     * @param isConfig
      * @return
      * @throws JSONException
      * @throws IOException
      */
     private JSONObject processListSchemaNode(ListSchemaNode listNode, String moduleName,
-            JSONObject models) throws JSONException, IOException {
+            JSONObject models, Boolean isConfig) throws JSONException, IOException {
 
         Set<DataSchemaNode> listChildren = listNode.getChildNodes();
-        String fileName = listNode.getQName().getLocalName();
+        String fileName = (BooleanUtils.isNotFalse(isConfig)?OperationBuilder.CONFIG:OperationBuilder.OPERATIONAL) +
+                                                                listNode.getQName().getLocalName();
 
         JSONObject childSchemaProperties = processChildren(listChildren, moduleName, models);
         JSONObject childSchema = getSchemaTemplate();
@@ -443,7 +501,7 @@ public class ModelGenerator {
             processUnionType((UnionTypeDefinition) leafTypeDef, property);
 
         } else if (leafTypeDef instanceof IdentityrefTypeDefinition) {
-            property.putOpt(TYPE_KEY, "object");
+      property.putOpt(TYPE_KEY, ((IdentityrefTypeDefinition) leafTypeDef).getIdentity().getQName().getLocalName());
         } else if (leafTypeDef instanceof BinaryTypeDefinition) {
             processBinaryType((BinaryTypeDefinition) leafTypeDef, property);
         } else {
@@ -541,12 +599,15 @@ public class ModelGenerator {
     private void processUnionType(UnionTypeDefinition unionType, JSONObject property)
             throws JSONException {
 
-        List<TypeDefinition<?>> unionTypes = unionType.getTypes();
-        JSONArray unionArray = new JSONArray();
-        for (TypeDefinition<?> typeDef : unionTypes) {
-            unionArray.put(YANG_TYPE_TO_JSON_TYPE_MAPPING.get(typeDef.getClass()));
+        StringBuilder type = new StringBuilder();
+        for (TypeDefinition<?> typeDef : unionType.getTypes() ) {
+            if( type.length() > 0 ){
+                type.append( " or " );
+            }
+            type.append(YANG_TYPE_TO_JSON_TYPE_MAPPING.get(typeDef.getClass()));
         }
-        property.put(TYPE_KEY, unionArray);
+
+        property.put(TYPE_KEY, type );
     }
 
     /**
index b996bf12348ccc89088b1426c269049a9cf98928..fcabb088f4decbac32df1ba08648cb3d2d18fdf9 100644 (file)
@@ -46,7 +46,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount
     private final Map<InstanceIdentifier, Long> instanceIdToLongId = new TreeMap<>(
             new Comparator<InstanceIdentifier>() {
                 @Override
-                public int compare(InstanceIdentifier o1, InstanceIdentifier o2) {
+                public int compare(final InstanceIdentifier o1, final InstanceIdentifier o2) {
                     return o1.toString().compareToIgnoreCase(o2.toString());
                 }
             });
@@ -71,12 +71,12 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount
         return urlToId;
     }
 
-    public void setGlobalSchema(SchemaService globalSchema) {
+    public void setGlobalSchema(final SchemaService globalSchema) {
         this.globalSchema = globalSchema;
     }
 
-    private String findModuleName(InstanceIdentifier id, SchemaContext context) {
-        PathArgument rootQName = id.getPath().get(0);
+    private String findModuleName(final InstanceIdentifier id, final SchemaContext context) {
+        PathArgument rootQName = id.getPathArguments().iterator().next();
         for (Module mod : context.getModules()) {
             if (mod.getDataChildByName(rootQName.getNodeType()) != null) {
                 return mod.getName();
@@ -85,40 +85,39 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount
         return null;
     }
 
-    private String generateUrlPrefixFromInstanceID(InstanceIdentifier key, String moduleName) {
-        List<PathArgument> path = key.getPath();
+    private String generateUrlPrefixFromInstanceID(final InstanceIdentifier key, final String moduleName) {
         StringBuilder builder = new StringBuilder();
         if (moduleName != null) {
             builder.append(moduleName);
-            builder.append(":");
+            builder.append(':');
         }
         boolean first = true;
-        for (PathArgument arg : path) {
+        for (PathArgument arg : key.getPathArguments()) {
 
             String name = arg.getNodeType().getLocalName();
             if (first) {
                 first = false;
             } else {
-                builder.append("/");
+                builder.append('/');
             }
             builder.append(name);
             if (arg instanceof InstanceIdentifier.NodeIdentifierWithPredicates) {
                 NodeIdentifierWithPredicates nodeId = (NodeIdentifierWithPredicates) arg;
                 for (Entry<QName, Object> entry : nodeId.getKeyValues().entrySet()) {
-                    builder.append("/").append(entry.getValue());
+                    builder.append('/').append(entry.getValue());
                 }
             }
         }
 
-        return builder.append("/").toString();
+        return builder.append('/').toString();
     }
 
-    private String getYangMountUrl(InstanceIdentifier key) {
+    private String getYangMountUrl(final InstanceIdentifier key) {
         String modName = findModuleName(key, globalSchema.getGlobalContext());
         return generateUrlPrefixFromInstanceID(key, modName) + "yang-ext:mount/";
     }
 
-    public ResourceList getResourceList(UriInfo uriInfo, Long id) {
+    public ResourceList getResourceList(final UriInfo uriInfo, final Long id) {
         InstanceIdentifier iid = getInstanceId(id);
         if (iid == null) {
             return null; // indicating not found.
@@ -139,7 +138,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount
         return list;
     }
 
-    private InstanceIdentifier getInstanceId(Long id) {
+    private InstanceIdentifier getInstanceId(final Long id) {
         InstanceIdentifier instanceId;
         synchronized (lock) {
             instanceId = longIdToInstanceId.get(id);
@@ -147,7 +146,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount
         return instanceId;
     }
 
-    private SchemaContext getSchemaContext(InstanceIdentifier id) {
+    private SchemaContext getSchemaContext(final InstanceIdentifier id) {
 
         if (id == null) {
             return null;
@@ -165,7 +164,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount
         return context;
     }
 
-    public ApiDeclaration getMountPointApi(UriInfo uriInfo, Long id, String module, String revision) {
+    public ApiDeclaration getMountPointApi(final UriInfo uriInfo, final Long id, final String module, final String revision) {
         InstanceIdentifier iid = getInstanceId(id);
         SchemaContext context = getSchemaContext(iid);
         String urlPrefix = getYangMountUrl(iid);
@@ -179,7 +178,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount
         return super.getApiDeclaration(module, revision, uriInfo, context, urlPrefix);
     }
 
-    private ApiDeclaration generateDataStoreApiDoc(UriInfo uriInfo, String context) {
+    private ApiDeclaration generateDataStoreApiDoc(final UriInfo uriInfo, final String context) {
 
         ApiDeclaration declaration = super.createApiDeclaration(createBasePathFromUriInfo(uriInfo));
         List<Api> apis = new LinkedList<>();
@@ -194,7 +193,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount
 
     }
 
-    private Api createGetApi(String datastore, String note, String context) {
+    private Api createGetApi(final String datastore, final String note, final String context) {
         Operation getConfig = new Operation();
         getConfig.setMethod("GET");
         getConfig.setNickname("GET " + datastore);
@@ -207,12 +206,12 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount
         return api;
     }
 
-    public void setMountService(MountProvisionService mountService) {
+    public void setMountService(final MountProvisionService mountService) {
         this.mountService = mountService;
     }
 
     @Override
-    public void onMountPointCreated(InstanceIdentifier path) {
+    public void onMountPointCreated(final InstanceIdentifier path) {
         synchronized (lock) {
             Long idLong = idKey.incrementAndGet();
             instanceIdToLongId.put(path, idLong);
@@ -221,7 +220,7 @@ public class MountPointSwagger extends BaseYangSwaggerGenerator implements Mount
     }
 
     @Override
-    public void onMountPointRemoved(InstanceIdentifier path) {
+    public void onMountPointRemoved(final InstanceIdentifier path) {
         synchronized (lock) {
             Long id = instanceIdToLongId.remove(path);
             longIdToInstanceId.remove(id);
index 2816f79e2413a90afc4125346a1a64804658a548..05a76a4cb7ca0551d0bb55322b4603f78eb7fd4b 100644 (file)
@@ -24,7 +24,6 @@
 <script src='swagger-ui.js' type='text/javascript'></script>\r
 <script src='lib/odl/list_mounts.js' type='text/javascript'></script>\r
 <script src='lib/highlight.7.3.pack.js' type='text/javascript'></script>\r
-<script src='lib/odl/rest-tree.js' type='text/javascript'></script>\r
 <script src='lib/odl/swagger.js' type='text/javascript'></script>\r
 \r
 <script type="text/javascript">\r
index 8390a385e6a136a29d79e64376a0fadf8fa03757..07c9378439d2f66551672d8a08ec20785a0a074b 100644 (file)
@@ -2,6 +2,7 @@ package org.opendaylight.controller.sal.rest.doc.impl;
 
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
 
 import java.io.File;
@@ -65,6 +66,24 @@ public class ApiDocGeneratorTest {
         }
     }
 
+    @Test
+    public void testEdgeCases() throws Exception {
+        Preconditions.checkArgument(helper.getModules() != null, "No modules found");
+
+        for (Entry<File, Module> m : helper.getModules().entrySet()) {
+            if (m.getKey().getAbsolutePath().endsWith("toaster.yang")) {
+                ApiDeclaration doc = generator.getSwaggerDocSpec(m.getValue(),
+                        "http://localhost:8080/restconf", "");
+                Assert.assertNotNull(doc);
+
+                //testing bugs.opendaylight.org bug 1290. UnionType model type.
+                String jsonString = doc.getModels().toString();
+                assertTrue(
+                        jsonString.contains( "testUnion\":{\"type\":\"integer or string\",\"required\":false}" ) );
+            }
+        }
+    }
+
     private void validateToaster(ApiDeclaration doc) throws Exception {
         Set<String> expectedUrls = new TreeSet<>(Arrays.asList(new String[] {
                 "/config/toaster2:toaster/", "/operational/toaster2:toaster/",
@@ -99,6 +118,7 @@ public class ApiDocGeneratorTest {
             expectedConfigMethods.removeAll(actualConfigMethods);
             fail("Missing expected method on config API: " + expectedConfigMethods);
         }
+
         // TODO: we should really do some more validation of the
         // documentation...
         /**
diff --git a/opendaylight/md-sal/sal-test-model/pom.xml b/opendaylight/md-sal/sal-test-model/pom.xml
new file mode 100644 (file)
index 0000000..11a0ef2
--- /dev/null
@@ -0,0 +1,81 @@
+<?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">
+    <parent>
+        <artifactId>sal-parent</artifactId>
+        <groupId>org.opendaylight.controller</groupId>
+        <version>1.1-SNAPSHOT</version>
+    </parent>
+    <modelVersion>4.0.0</modelVersion>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.opendaylight.yangtools</groupId>
+            <artifactId>yang-binding</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.opendaylight.yangtools.model</groupId>
+            <artifactId>yang-ext</artifactId>
+        </dependency>
+    </dependencies>
+
+    <artifactId>sal-test-model</artifactId>
+    <build>
+        <plugins>
+            <plugin>
+                <groupId>org.jacoco</groupId>
+                <artifactId>jacoco-maven-plugin</artifactId>
+                <configuration>
+                    <includes>
+                        <include>org.opendaylight.controller.*</include>
+                    </includes>
+                </configuration>
+                <executions>
+                    <execution>
+                        <id>pre-test</id>
+                        <goals>
+                            <goal>prepare-agent</goal>
+                        </goals>
+                    </execution>
+                    <execution>
+                        <id>post-test</id>
+                        <goals>
+                            <goal>report</goal>
+                        </goals>
+                        <phase>test</phase>
+                    </execution>
+                </executions>
+            </plugin>
+            <plugin>
+                <groupId>org.opendaylight.yangtools</groupId>
+                <artifactId>yang-maven-plugin</artifactId>
+                <executions>
+                    <execution>
+                        <goals>
+                            <goal>generate-sources</goal>
+                        </goals>
+                        <configuration>
+                            <codeGenerators>
+                                <generator>
+                                    <codeGeneratorClass>
+                                        org.opendaylight.yangtools.maven.sal.api.gen.plugin.CodeGeneratorImpl
+                                    </codeGeneratorClass>
+                                    <outputBaseDir>${salGeneratorPath}</outputBaseDir>
+                                </generator>
+                            </codeGenerators>
+                            <inspectDependencies>true</inspectDependencies>
+                        </configuration>
+                    </execution>
+                </executions>
+            </plugin>
+        </plugins>
+    </build>
+    <scm>
+        <connection>scm:git:ssh://git.opendaylight.org:29418/controller.git</connection>
+        <developerConnection>scm:git:ssh://git.opendaylight.org:29418/controller.git</developerConnection>
+        <tag>HEAD</tag>
+        <url>https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL</url>
+    </scm>
+
+</project>
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-test-model/src/main/java/org/opendaylight/controller/md/sal/test/model/util/ListsBindingUtils.java b/opendaylight/md-sal/sal-test-model/src/main/java/org/opendaylight/controller/md/sal/test/model/util/ListsBindingUtils.java
new file mode 100644 (file)
index 0000000..a0c23ae
--- /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.md.sal.test.model.util;
+
+import java.util.Arrays;
+
+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.augment.rev140709.TreeComplexUsesAugmentBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.complex.from.grouping.ListViaUses;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.complex.from.grouping.ListViaUsesBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.augment.rev140709.complex.from.grouping.ListViaUsesKey;
+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.TopBuilder;
+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.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.TopLevelListKey;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.top.level.list.NestedList;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.list.rev140701.two.level.list.top.level.list.NestedListKey;
+import org.opendaylight.yangtools.yang.binding.Augmentation;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+
+import com.google.common.collect.ImmutableList;
+
+public class ListsBindingUtils {
+
+    private static final InstanceIdentifier<Top> TOP_PATH = InstanceIdentifier.create(Top.class);
+
+    private ListsBindingUtils() {
+        throw new UnsupportedOperationException();
+    }
+
+    public static final TopLevelListKey TOP_FOO_KEY = new TopLevelListKey("foo");
+    public static final TopLevelListKey TOP_BAR_KEY = new TopLevelListKey("bar");
+    public static final ListViaUsesKey USES_ONE_KEY = new ListViaUsesKey("one");
+    public static final ListViaUsesKey USES_TWO_KEY = new ListViaUsesKey("two");
+
+
+    public static InstanceIdentifier<TopLevelList> path(final TopLevelListKey key) {
+        return TOP_PATH.child(TopLevelList.class, key);
+    }
+
+    public static InstanceIdentifier<NestedList> path(final TopLevelListKey top,final NestedListKey nested) {
+        return path(top).child(NestedList.class, nested);
+    }
+
+    public static InstanceIdentifier<ListViaUses> path(final TopLevelListKey top,final ListViaUsesKey uses) {
+        return path(top).augmentation(TreeComplexUsesAugment.class).child(ListViaUses.class, uses);
+    }
+
+    public static <T extends DataObject & Augmentation<TopLevelList>> InstanceIdentifier<T> path(final TopLevelListKey key, final Class<T> augmentation) {
+        return path(key).augmentation(augmentation);
+    }
+
+    public static Top top(final TopLevelList... listItems) {
+        return new TopBuilder().setTopLevelList(Arrays.asList(listItems)).build();
+    }
+
+    public static TopLevelList topLevelList(final TopLevelListKey key) {
+        return new TopLevelListBuilder().setKey(key).build();
+    }
+
+    public static TopLevelList topLevelList(final TopLevelListKey key, final TreeComplexUsesAugment augment) {
+        TopLevelListBuilder builder = new TopLevelListBuilder().setKey(key);
+        builder.addAugmentation(TreeComplexUsesAugment.class, augment);
+        return builder.build();
+    }
+
+    public static TreeComplexUsesAugment complexUsesAugment(final ListViaUsesKey... keys) {
+        ImmutableList.Builder<ListViaUses> listViaUses = ImmutableList.<ListViaUses> builder();
+        for (ListViaUsesKey key : keys) {
+            listViaUses.add(new ListViaUsesBuilder().setKey(key).build());
+        }
+        return new TreeComplexUsesAugmentBuilder().setListViaUses(listViaUses.build()).build();
+    }
+
+}
diff --git a/opendaylight/md-sal/sal-test-model/src/main/yang/opendaylight-mdsal-augment-test.yang b/opendaylight/md-sal/sal-test-model/src/main/yang/opendaylight-mdsal-augment-test.yang
new file mode 100644 (file)
index 0000000..ddd7687
--- /dev/null
@@ -0,0 +1,93 @@
+module opendaylight-mdsal-augment-test {
+
+    namespace "urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:augment";
+    prefix aug-test;
+
+    import opendaylight-mdsal-list-test {
+        prefix test;
+    }
+    import yang-ext {
+        prefix ext;
+    }
+
+    description
+        "This module contains a collection of YANG augmentations used for
+        some test cases.";
+
+    revision 2014-07-09 {
+        description
+        "Test model for testing data broker with nested lists.";
+    }
+
+    grouping leaf-from-grouping {
+        leaf leaf-from-grouping {
+            type string;
+        }
+    }
+
+    grouping complex-from-grouping {
+        container container-with-uses {
+            uses leaf-from-grouping;
+        }
+        list list-via-uses {
+            key "name";
+            leaf name {
+                type string;
+            }
+        }
+    
+    }
+
+    augment "/test:top/test:top-level-list" {
+        ext:augment-identifier tree-leaf-only-uses-augment;
+        uses leaf-from-grouping;
+    }
+
+    augment "/test:put-top/test:input/test:top-level-list" {
+        ext:augment-identifier rpc-leaf-only-uses-augment;
+        uses leaf-from-grouping;
+    }
+
+    augment "/test:top/test:top-level-list" {
+        ext:augment-identifier tree-complex-uses-augment;
+        uses complex-from-grouping;
+    }
+
+    augment "/test:put-top/test:input/test:top-level-list" {
+        ext:augment-identifier rpc-complex-uses-augment;
+        uses complex-from-grouping;
+    }
+
+    augment "/test:top/test:top-level-list" {
+        ext:augment-identifier tree-leaf-only-augment;
+
+        leaf simple-value {
+            type string;
+        }
+    }
+    
+    augment "/test:top/test:top-level-list" {
+        ext:augment-identifier tree-second-leaf-only-augment;
+
+        leaf second-simple-value {
+            type string;
+        }
+    }
+
+    augment "/test:put-top/test:input/test:top-level-list" {
+        ext:augment-identifier rpc-leaf-only-augment;
+
+        leaf simple-value {
+            type string;
+        }
+    }
+
+    augment "/test:put-top/test:input/test:top-level-list" {
+        ext:augment-identifier rpc-second-leaf-only-augment;
+
+        leaf second-simple-value {
+            type string;
+        }
+    }
+
+}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-test-model/src/main/yang/opendaylight-mdsal-list-test.yang b/opendaylight/md-sal/sal-test-model/src/main/yang/opendaylight-mdsal-list-test.yang
new file mode 100644 (file)
index 0000000..48666e1
--- /dev/null
@@ -0,0 +1,51 @@
+module opendaylight-mdsal-list-test {
+
+    namespace "urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:list";
+    prefix list-test;
+
+
+    description
+        "This module contains a collection of YANG definitions used for
+        some test cases.";
+
+    revision 2014-07-01 {
+        description
+        "Test model for testing data broker with nested lists.";
+    }
+
+    grouping two-level-list {
+        list top-level-list {
+            description
+                "Top Level List";
+            key "name";
+            leaf name {
+                type string;
+            }
+            list nested-list {
+                key "name";
+                leaf name {
+                    type string;
+                }
+                leaf type {
+                    type string;
+                    mandatory true;
+                    description
+                        "Mandatory type of list.";
+                }
+                ordered-by user;
+                description
+                    "A list of service functions that compose the service chain";
+            }
+        }
+    }
+
+    container top {
+        uses two-level-list;
+    }
+
+    rpc put-top {
+        input {
+            uses two-level-list;
+        }
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/md-sal/sal-test-model/src/main/yang/opendaylight-test-routed-rpc.yang b/opendaylight/md-sal/sal-test-model/src/main/yang/opendaylight-test-routed-rpc.yang
new file mode 100644 (file)
index 0000000..c3a9824
--- /dev/null
@@ -0,0 +1,46 @@
+module opendaylight-test-routed-rpc {
+    yang-version 1;
+    namespace "urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:rpc:routing";
+    prefix "rpc";
+    import yang-ext { prefix ext; }
+
+    description
+        "Test model for testing of registering rpc service on binding independent mount point 
+        and retrieving rpc service via binding aware mount point.";
+
+    revision "2014-07-01" {
+        description
+            "Initial revision";
+    }
+
+    identity test-context {
+        description "Test Context";
+    }
+    
+    typedef encapsulated-route {
+        type instance-identifier;
+    }
+    
+    grouping route-in-grouping {
+        leaf route {
+            type instance-identifier;
+            ext:context-reference test-context;
+        }
+    }
+    
+    grouping encapsulated-route-in-grouping {
+        leaf route {
+            type encapsulated-route;
+            ext:context-reference test-context;
+        }
+    }
+
+    rpc routed-simple-route {
+        input {
+            leaf route {
+                type instance-identifier;
+                ext:context-reference test-context;
+            }
+        }
+    }
+}
diff --git a/opendaylight/md-sal/sal-test-model/src/main/yang/opendaylight-test-rpc-service.yang b/opendaylight/md-sal/sal-test-model/src/main/yang/opendaylight-test-rpc-service.yang
new file mode 100644 (file)
index 0000000..3412eb5
--- /dev/null
@@ -0,0 +1,22 @@
+module opendaylight-test-rpc-service {
+    yang-version 1;
+    namespace "urn:opendaylight:params:xml:ns:yang:controller:md:sal:test:bi:ba:rpcservice";
+    prefix "rpc";
+
+    description
+        "Test model for testing of registering rpc service on binding independent mount point 
+        and retrieving rpc service via binding aware mount point.";
+
+    revision "2014-07-01" {
+        description
+            "Initial revision";
+    }
+
+    rpc rock-the-house {
+        input {
+            leaf zip-code {
+                type string;
+            }
+        }
+    }
+}
\ No newline at end of file
index f6a8306a98b6a71650ffcbc7b06a331a184dbd32..6e720299d8364e21d058e9603f86e33544697b1d 100644 (file)
       <groupId>org.opendaylight.controller</groupId>
       <artifactId>config-api</artifactId>
     </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>sal-common-util</artifactId>
+    </dependency>
     <dependency>
       <groupId>org.opendaylight.controller</groupId>
       <artifactId>sal-binding-api</artifactId>
index a23def6262a0af8e6938f59c4f7a92e3c14b0eb7..88281bd59369858f8818adfa75b741e4d4fea367 100644 (file)
@@ -9,6 +9,8 @@
  */
 package org.opendaylight.controller.config.yang.config.kitchen_service.impl;
 
+import java.util.concurrent.Future;
+
 import org.opendaylight.controller.sample.kitchen.api.EggsType;
 import org.opendaylight.controller.sample.kitchen.api.KitchenService;
 import org.opendaylight.controller.sample.kitchen.impl.KitchenServiceImpl;
@@ -16,6 +18,7 @@ import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120
 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterService;
 import org.opendaylight.yangtools.concepts.Registration;
 import org.opendaylight.yangtools.yang.binding.NotificationListener;
+import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -63,7 +66,9 @@ public final class KitchenServiceModule extends AbstractKitchenServiceModule {
             }
 
             @Override
-            public boolean makeBreakfast( final EggsType eggs, final Class<? extends ToastType> toast, final int toastDoneness ) {
+            public Future<RpcResult<Void>> makeBreakfast( final EggsType eggs,
+                                                          final Class<? extends ToastType> toast,
+                                                          final int toastDoneness ) {
                 return kitchenService.makeBreakfast( eggs, toast, toastDoneness );
             }
         }
index ef9c122ec1fb314a32d16e5566ca2275db7b5cd9..7e7f342962cba09a7204aa046b9126b77d46d33a 100644 (file)
@@ -1,7 +1,11 @@
 package org.opendaylight.controller.sample.kitchen.api;
 
+import java.util.concurrent.Future;
+
 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToastType;
+import org.opendaylight.yangtools.yang.common.RpcResult;
 
 public interface KitchenService {
-    boolean makeBreakfast( EggsType eggs, Class<? extends ToastType> toast, int toastDoneness );
+    Future<RpcResult<Void>> makeBreakfast( EggsType eggs, Class<? extends ToastType> toast,
+                                           int toastDoneness );
 }
index 911a8c87d7166edc38c7faa2597678c8f55c611a..c6aa545935af5e2ae9771343706ac24a0518a363 100644 (file)
@@ -1,10 +1,15 @@
 package org.opendaylight.controller.sample.kitchen.impl;
 
+import java.util.List;
+import java.util.concurrent.Callable;
 import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
 
 import org.opendaylight.controller.config.yang.config.kitchen_service.impl.KitchenServiceRuntimeMXBean;
 import org.opendaylight.controller.sample.kitchen.api.EggsType;
 import org.opendaylight.controller.sample.kitchen.api.KitchenService;
+import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastInput;
 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastInputBuilder;
 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToastType;
 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterListener;
@@ -12,16 +17,31 @@ import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120
 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestocked;
 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterService;
 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.WheatBread;
+import org.opendaylight.yangtools.yang.common.RpcError;
 import org.opendaylight.yangtools.yang.common.RpcResult;
+import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableList.Builder;
+import com.google.common.util.concurrent.AsyncFunction;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.JdkFutureAdapters;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
+
 public class KitchenServiceImpl implements KitchenService, KitchenServiceRuntimeMXBean, ToasterListener {
 
     private static final Logger log = LoggerFactory.getLogger( KitchenServiceImpl.class );
 
     private final ToasterService toaster;
 
+    private final ListeningExecutorService executor =
+                                   MoreExecutors.listeningDecorator( Executors.newCachedThreadPool() );
+
     private volatile boolean toasterOutOfBread;
 
     public KitchenServiceImpl(ToasterService toaster) {
@@ -29,39 +49,101 @@ public class KitchenServiceImpl implements KitchenService, KitchenServiceRuntime
     }
 
     @Override
-    public boolean makeBreakfast( EggsType eggs, Class<? extends ToastType> toast, int toastDoneness ) {
+    public Future<RpcResult<Void>> makeBreakfast( EggsType eggsType, Class<? extends ToastType> toastType,
+                                                  int toastDoneness ) {
+
+        // Call makeToast and use JdkFutureAdapters to convert the Future to a ListenableFuture,
+        // The OpendaylightToaster impl already returns a ListenableFuture so the conversion is
+        // actually a no-op.
+
+        ListenableFuture<RpcResult<Void>> makeToastFuture = JdkFutureAdapters.listenInPoolThread(
+                makeToast( toastType, toastDoneness ), executor );
+
+        ListenableFuture<RpcResult<Void>> makeEggsFuture = makeEggs( eggsType );
+
+        // Combine the 2 ListenableFutures into 1 containing a list of RpcResults.
+
+        ListenableFuture<List<RpcResult<Void>>> combinedFutures =
+                Futures.allAsList( ImmutableList.of( makeToastFuture, makeEggsFuture ) );
+
+        // Then transform the RpcResults into 1.
+
+        return Futures.transform( combinedFutures,
+            new AsyncFunction<List<RpcResult<Void>>,RpcResult<Void>>() {
+                @Override
+                public ListenableFuture<RpcResult<Void>> apply( List<RpcResult<Void>> results )
+                                                                                 throws Exception {
+                    boolean atLeastOneSucceeded = false;
+                    Builder<RpcError> errorList = ImmutableList.builder();
+                    for( RpcResult<Void> result: results ) {
+                        if( result.isSuccessful() ) {
+                            atLeastOneSucceeded = true;
+                        }
+
+                        if( result.getErrors() != null ) {
+                            errorList.addAll( result.getErrors() );
+                        }
+                    }
+
+                    return Futures.immediateFuture(
+                              RpcResultBuilder.<Void> status( atLeastOneSucceeded )
+                                              .withRpcErrors( errorList.build() ).build() );
+                }
+        } );
+    }
+
+    private ListenableFuture<RpcResult<Void>> makeEggs( EggsType eggsType ) {
+
+        return executor.submit( new Callable<RpcResult<Void>>() {
+
+            @Override
+            public RpcResult<Void> call() throws Exception {
+
+                // We don't actually do anything here - just return a successful result.
+                return RpcResultBuilder.<Void> success().build();
+            }
+        } );
+    }
+
+    private Future<RpcResult<Void>> makeToast( Class<? extends ToastType> toastType,
+                                               int toastDoneness ) {
 
         if( toasterOutOfBread )
         {
             log.info( "We're out of toast but we can make eggs" );
-            return true;
+            return Futures.immediateFuture( RpcResultBuilder.<Void> success()
+                     .withWarning( ErrorType.APPLICATION, "partial-operation",
+                                      "Toaster is out of bread but we can make you eggs" ).build() );
         }
 
         // Access the ToasterService to make the toast.
-        // We don't actually make the eggs for this example - sorry.
-        MakeToastInputBuilder toastInput = new MakeToastInputBuilder();
-        toastInput.setToasterDoneness( (long) toastDoneness);
-        toastInput.setToasterToastType( toast );
 
-        try {
-            RpcResult<Void> result = toaster.makeToast( toastInput.build() ).get();
+        MakeToastInput toastInput = new MakeToastInputBuilder()
+            .setToasterDoneness( (long) toastDoneness )
+            .setToasterToastType( toastType )
+            .build();
+
+        return toaster.makeToast( toastInput );
+    }
 
+    @Override
+    public Boolean makeScrambledWithWheat() {
+        try {
+            // This call has to block since we must return a result to the JMX client.
+            RpcResult<Void> result = makeBreakfast( EggsType.SCRAMBLED, WheatBread.class, 2 ).get();
             if( result.isSuccessful() ) {
-                log.info( "makeToast succeeded" );
+                log.info( "makeBreakfast succeeded" );
             } else {
-                log.warn( "makeToast failed: " + result.getErrors() );
+                log.warn( "makeBreakfast failed: " + result.getErrors() );
             }
 
             return result.isSuccessful();
+
         } catch( InterruptedException | ExecutionException e ) {
-            log.warn( "Error occurred during toast creation" );
+            log.warn( "An error occurred while maing breakfast: " + e );
         }
-        return false;
-    }
 
-    @Override
-    public Boolean makeScrambledWithWheat() {
-        return makeBreakfast( EggsType.SCRAMBLED, WheatBread.class, 2 );
+        return Boolean.FALSE;
     }
 
     /**
index 907b35475f80f3565e18d2965885ff505bb55d6e..30f1762197ecf58a35c8828775dfb009742a7025 100644 (file)
@@ -93,13 +93,13 @@ public class ToasterTest {
         long toastsMade = (long) platformMBeanServer.getAttribute(providerOn, "ToastsMade");
         assertEquals(0, toastsMade);
 
-        boolean toasts = true;
+        boolean success = true;
 
         // Make toasts using OSGi service
-        toasts &= kitchenService.makeBreakfast( EggsType.SCRAMBLED, HashBrown.class, 4);
-        toasts &= kitchenService.makeBreakfast( EggsType.POACHED, WhiteBread.class, 8 );
+        success &= kitchenService.makeBreakfast( EggsType.SCRAMBLED, HashBrown.class, 4).get().isSuccessful();
+        success &= kitchenService.makeBreakfast( EggsType.POACHED, WhiteBread.class, 8 ).get().isSuccessful();
 
-        Assert.assertTrue("Not all toasts done by " + kitchenService, toasts);
+        Assert.assertTrue("Not all breakfasts succeeded", success);
 
         // Verify toasts made count on provider via JMX/config-subsystem
         toastsMade = (long) platformMBeanServer.getAttribute(providerOn, "ToastsMade");
index 57581d100d619064dcb5831c5ea8e590d7670872..4cce64dcd329a9404d9273a24d45dd253db08dad 100644 (file)
@@ -99,7 +99,7 @@
                             </rpc-registry>
 
                             <data-broker>
-                              <type xmlns:binding="urn:opendaylight:params:xml:ns:yang:controller:md:sal:binding">binding:binding-data-broker</type>
+                              <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>
 
index f904f9726efce6c236526f318654fab49a81f49a..d76c2d3c22a415628beccef2eb9af4c36035840d 100644 (file)
@@ -10,7 +10,9 @@
 
   <logger name="org.opendaylight.yangtools.yang.parser" level="ERROR"/>
 
-  <root level="debug">
+  <logger name="org.opendaylight.controller.sample.toaster.provider" level="DEBUG"/>
+
+  <root level="error">
     <appender-ref ref="STDOUT" />
   </root>
 </configuration>
index bd8e89fd7a5ab99ddb1246a167d0b142f446a07f..388c78eaaf6365c77241c17cae04848680882624 100644 (file)
@@ -9,9 +9,11 @@
 */
 package org.opendaylight.controller.config.yang.config.toaster_provider.impl;
 
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataBroker.DataChangeScope;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
-import org.opendaylight.controller.sal.binding.api.data.DataChangeListener;
-import org.opendaylight.controller.sal.binding.api.data.DataProviderService;
 import org.opendaylight.controller.sample.toaster.provider.OpendaylightToaster;
 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterService;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
@@ -21,23 +23,26 @@ import org.slf4j.LoggerFactory;
 /**
 *
 */
-public final class ToasterProviderModule extends org.opendaylight.controller.config.yang.config.toaster_provider.impl.AbstractToasterProviderModule
- {
+public final class ToasterProviderModule extends
       org.opendaylight.controller.config.yang.config.toaster_provider.impl.AbstractToasterProviderModule {
     private static final Logger log = LoggerFactory.getLogger(ToasterProviderModule.class);
 
-    public ToasterProviderModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
+    public ToasterProviderModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+            final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver) {
         super(identifier, dependencyResolver);
     }
 
-    public ToasterProviderModule(org.opendaylight.controller.config.api.ModuleIdentifier identifier, org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,
-            ToasterProviderModule oldModule, java.lang.AutoCloseable oldInstance) {
+    public ToasterProviderModule(final org.opendaylight.controller.config.api.ModuleIdentifier identifier,
+            final org.opendaylight.controller.config.api.DependencyResolver dependencyResolver,
+            final ToasterProviderModule oldModule, final java.lang.AutoCloseable oldInstance) {
 
         super(identifier, dependencyResolver, oldModule, oldInstance);
     }
 
     @Override
     protected void customValidation() {
-        // No need to validate dependencies, since all dependencies have mandatory true flag in yang
+        // No need to validate dependencies, since all dependencies have
+        // mandatory true flag in yang
         // config-subsystem will perform the validation for dependencies
     }
 
@@ -48,11 +53,12 @@ public final class ToasterProviderModule extends org.opendaylight.controller.con
         // Register to md-sal
         opendaylightToaster.setNotificationProvider(getNotificationServiceDependency());
 
-        DataProviderService dataBrokerService = getDataBrokerDependency();
+        DataBroker dataBrokerService = getDataBrokerDependency();
         opendaylightToaster.setDataProvider(dataBrokerService);
 
-        final ListenerRegistration<DataChangeListener> dataChangeListenerRegistration =
-                dataBrokerService.registerDataChangeListener( OpendaylightToaster.TOASTER_IID, opendaylightToaster );
+        final ListenerRegistration<DataChangeListener> dataChangeListenerRegistration = dataBrokerService
+                .registerDataChangeListener(LogicalDatastoreType.CONFIGURATION, OpendaylightToaster.TOASTER_IID,
+                        opendaylightToaster, DataChangeScope.SUBTREE);
 
         final BindingAwareBroker.RpcRegistration<ToasterService> rpcRegistration = getRpcRegistryDependency()
                 .addRpcImplementation(ToasterService.class, opendaylightToaster);
index 2ecd7e7b684fe8bdafd6af17527cbb21daeee83f..ea2ddc9b6558248f25ea7ae2bc7aec43f2f166f7 100644 (file)
@@ -7,43 +7,50 @@
  */
 package org.opendaylight.controller.sample.toaster.provider;
 
-import java.util.Arrays;
-import java.util.Collections;
 import java.util.concurrent.Callable;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import java.util.concurrent.Future;
 import java.util.concurrent.atomic.AtomicLong;
+import java.util.concurrent.atomic.AtomicReference;
 
 import org.opendaylight.controller.config.yang.config.toaster_provider.impl.ToasterProviderRuntimeMXBean;
-import org.opendaylight.controller.md.sal.common.api.data.DataChangeEvent;
+import org.opendaylight.controller.md.sal.binding.api.DataBroker;
+import org.opendaylight.controller.md.sal.binding.api.DataChangeListener;
+import org.opendaylight.controller.md.sal.binding.api.ReadWriteTransaction;
+import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
+import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
+import org.opendaylight.controller.md.sal.common.api.data.AsyncDataChangeEvent;
+import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
+import org.opendaylight.controller.md.sal.common.api.data.OptimisticLockFailedException;
 import org.opendaylight.controller.sal.binding.api.NotificationProviderService;
-import org.opendaylight.controller.sal.binding.api.data.DataBrokerService;
-import org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction;
-import org.opendaylight.controller.sal.common.util.RpcErrors;
-import org.opendaylight.controller.sal.common.util.Rpcs;
 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.DisplayString;
 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastInput;
+import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.RestockToasterInput;
 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.Toaster;
 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.Toaster.ToasterStatus;
-import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.RestockToasterInput;
 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterBuilder;
 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterOutOfBreadBuilder;
 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestocked;
 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestockedBuilder;
 import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterService;
-import org.opendaylight.controller.sal.binding.api.data.DataChangeListener;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.common.RpcError;
+import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 import org.opendaylight.yangtools.yang.common.RpcError.ErrorType;
 import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.common.RpcError.ErrorSeverity;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.base.Function;
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.AsyncFunction;
+import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.SettableFuture;
 
 public class OpendaylightToaster implements ToasterService, ToasterProviderRuntimeMXBean,
                                             DataChangeListener, AutoCloseable {
@@ -56,14 +63,13 @@ public class OpendaylightToaster implements ToasterService, ToasterProviderRunti
     private static final DisplayString TOASTER_MODEL_NUMBER = new DisplayString("Model 1 - Binding Aware");
 
     private NotificationProviderService notificationProvider;
-    private DataBrokerService dataProvider;
+    private DataBroker dataProvider;
 
     private final ExecutorService executor;
 
-    // As you will see we are using multiple threads here. Therefore we need to be careful about concurrency.
-    // In this case we use the taskLock to provide synchronization for the current task.
-    private volatile Future<RpcResult<Void>> currentTask;
-    private final Object taskLock = new Object();
+    // The following holds the Future for the current make toast task.
+    // This is used to cancel the current toast.
+    private final AtomicReference<Future<?>> currentMakeToastTask = new AtomicReference<>();
 
     private final AtomicLong amountOfBreadInStock = new AtomicLong( 100 );
 
@@ -76,13 +82,13 @@ public class OpendaylightToaster implements ToasterService, ToasterProviderRunti
         executor = Executors.newFixedThreadPool(1);
     }
 
-    public void setNotificationProvider(NotificationProviderService salService) {
+    public void setNotificationProvider(final NotificationProviderService salService) {
         this.notificationProvider = salService;
     }
 
-    public void setDataProvider(DataBrokerService salDataProvider) {
+    public void setDataProvider(final DataBroker salDataProvider) {
         this.dataProvider = salDataProvider;
-        updateStatus();
+        setToasterStatusUp( null );
     }
 
     /**
@@ -94,32 +100,40 @@ public class OpendaylightToaster implements ToasterService, ToasterProviderRunti
         executor.shutdown();
 
         if (dataProvider != null) {
-            final DataModificationTransaction t = dataProvider.beginTransaction();
-            t.removeOperationalData(TOASTER_IID);
-            t.commit().get();
+            WriteTransaction t = dataProvider.newWriteOnlyTransaction();
+            t.delete(LogicalDatastoreType.OPERATIONAL,TOASTER_IID);
+            ListenableFuture<RpcResult<TransactionStatus>> future = t.commit();
+            Futures.addCallback( future, new FutureCallback<RpcResult<TransactionStatus>>() {
+                @Override
+                public void onSuccess( final RpcResult<TransactionStatus> result ) {
+                    LOG.debug( "Delete Toaster commit result: " + result );
+                }
+
+                @Override
+                public void onFailure( final Throwable t ) {
+                    LOG.error( "Delete of Toaster failed", t );
+                }
+            } );
         }
     }
 
-    private Toaster buildToaster() {
-        // We don't need to synchronize on currentTask here b/c it's declared volatile and
-        // we're just doing a read.
-        boolean isUp = currentTask == null;
+    private Toaster buildToaster( final ToasterStatus status ) {
 
         // note - we are simulating a device whose manufacture and model are
         // fixed (embedded) into the hardware.
         // This is why the manufacture and model number are hardcoded.
-        ToasterBuilder tb = new ToasterBuilder();
-        tb.setToasterManufacturer(TOASTER_MANUFACTURER).setToasterModelNumber(TOASTER_MODEL_NUMBER)
-                .setToasterStatus(isUp ? ToasterStatus.Up : ToasterStatus.Down);
-        return tb.build();
+        return new ToasterBuilder().setToasterManufacturer( TOASTER_MANUFACTURER )
+                                   .setToasterModelNumber( TOASTER_MODEL_NUMBER )
+                                   .setToasterStatus( status )
+                                   .build();
     }
 
     /**
      * Implemented from the DataChangeListener interface.
      */
     @Override
-    public void onDataChanged( DataChangeEvent<InstanceIdentifier<?>, DataObject> change ) {
-        DataObject dataObject = change.getUpdatedConfigurationData().get( TOASTER_IID );
+    public void onDataChanged( final AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> change ) {
+        DataObject dataObject = change.getUpdatedSubtree();
         if( dataObject instanceof Toaster )
         {
             Toaster toaster = (Toaster) dataObject;
@@ -132,57 +146,143 @@ public class OpendaylightToaster implements ToasterService, ToasterProviderRunti
     }
 
     /**
-     * RestConf RPC call implemented from the ToasterService interface.
+     * RPC call implemented from the ToasterService interface that cancels the current
+     * toast, if any.
      */
     @Override
     public Future<RpcResult<Void>> cancelToast() {
-        synchronized (taskLock) {
-            if (currentTask != null) {
-                currentTask.cancel(true);
-                currentTask = null;
-            }
+
+        Future<?> current = currentMakeToastTask.getAndSet( null );
+        if( current != null ) {
+            current.cancel( true );
         }
+
         // Always return success from the cancel toast call.
-        return Futures.immediateFuture(Rpcs.<Void> getRpcResult(true, Collections.<RpcError> emptySet()));
+        return Futures.immediateFuture( RpcResultBuilder.<Void> success().build() );
     }
 
     /**
-     * RestConf RPC call implemented from the ToasterService interface.
+     * RPC call implemented from the ToasterService interface that attempts to make toast.
      */
     @Override
-    public Future<RpcResult<Void>> makeToast(MakeToastInput input) {
+    public Future<RpcResult<Void>> makeToast(final MakeToastInput input) {
         LOG.info("makeToast: " + input);
 
-        synchronized (taskLock) {
-            if (currentTask != null) {
-                // return an error since we are already toasting some toast.
-                LOG.info( "Toaster is already making toast" );
+        final SettableFuture<RpcResult<Void>> futureResult = SettableFuture.create();
 
-                RpcResult<Void> result = Rpcs.<Void> getRpcResult(false, null, Arrays.asList(
-                        RpcErrors.getRpcError( "", "in-use", null, ErrorSeverity.WARNING,
-                                               "Toaster is busy", ErrorType.APPLICATION, null ) ) );
-                return Futures.immediateFuture(result);
-            }
-            else if( outOfBread() ) {
-                RpcResult<Void> result = Rpcs.<Void> getRpcResult(false, null, Arrays.asList(
-                        RpcErrors.getRpcError( "out-of-stock", "resource-denied", null, null,
-                                               "Toaster is out of bread",
-                                               ErrorType.APPLICATION, null ) ) );
-                return Futures.immediateFuture(result);
-            }
-            else {
-                // Notice that we are moving the actual call to another thread,
-                // allowing this thread to return immediately.
-                // The MD-SAL design encourages asynchronus programming. If the
-                // caller needs to block until the call is
-                // complete then they can leverage the blocking methods on the
-                // Future interface.
-                currentTask = executor.submit(new MakeToastTask(input));
+        checkStatusAndMakeToast( input, futureResult );
+
+        return futureResult;
+    }
+
+    private RpcError makeToasterOutOfBreadError() {
+        return RpcResultBuilder.newError( ErrorType.APPLICATION, "resource-denied",
+                "Toaster is out of bread", "out-of-stock", null, null );
+    }
+
+    private RpcError makeToasterInUseError() {
+        return RpcResultBuilder.newWarning( ErrorType.APPLICATION, "in-use",
+                "Toaster is busy", null, null, null );
+    }
+
+    private void checkStatusAndMakeToast( final MakeToastInput input,
+                                          final SettableFuture<RpcResult<Void>> futureResult ) {
+
+        // Read the ToasterStatus and, if currently Up, try to write the status to Down.
+        // If that succeeds, then we essentially have an exclusive lock and can proceed
+        // to make toast.
+
+        final ReadWriteTransaction tx = dataProvider.newReadWriteTransaction();
+        ListenableFuture<Optional<Toaster>> readFuture =
+                                          tx.read( LogicalDatastoreType.OPERATIONAL, TOASTER_IID );
+
+        final ListenableFuture<RpcResult<TransactionStatus>> commitFuture =
+            Futures.transform( readFuture, new AsyncFunction<Optional<Toaster>,
+                                                                   RpcResult<TransactionStatus>>() {
+
+                @Override
+                public ListenableFuture<RpcResult<TransactionStatus>> apply(
+                        final Optional<Toaster> toasterData ) throws Exception {
+
+                    ToasterStatus toasterStatus = ToasterStatus.Up;
+                    if( toasterData.isPresent() ) {
+                        toasterStatus = toasterData.get().getToasterStatus();
+                    }
+
+                    LOG.debug( "Read toaster status: {}", toasterStatus );
+
+                    if( toasterStatus == ToasterStatus.Up ) {
+
+                        if( outOfBread() ) {
+                            LOG.debug( "Toaster is out of bread" );
+
+                            return Futures.immediateFuture( RpcResultBuilder.<TransactionStatus>failed()
+                                    .withRpcError( makeToasterOutOfBreadError() ).build() );
+                        }
+
+                        LOG.debug( "Setting Toaster status to Down" );
+
+                        // We're not currently making toast - try to update the status to Down
+                        // to indicate we're going to make toast. This acts as a lock to prevent
+                        // concurrent toasting.
+                        tx.put( LogicalDatastoreType.OPERATIONAL, TOASTER_IID,
+                                buildToaster( ToasterStatus.Down ) );
+                        return tx.commit();
+                    }
+
+                    LOG.debug( "Oops - already making toast!" );
+
+                    // Return an error since we are already making toast. This will get
+                    // propagated to the commitFuture below which will interpret the null
+                    // TransactionStatus in the RpcResult as an error condition.
+                    return Futures.immediateFuture( RpcResultBuilder.<TransactionStatus>failed()
+                            .withRpcError( makeToasterInUseError() ).build() );
+                }
+        } );
+
+        Futures.addCallback( commitFuture, new FutureCallback<RpcResult<TransactionStatus>>() {
+            @Override
+            public void onSuccess( final RpcResult<TransactionStatus> result ) {
+                if( result.getResult() == TransactionStatus.COMMITED  ) {
+
+                    // OK to make toast
+                    currentMakeToastTask.set( executor.submit(
+                                                    new MakeToastTask( input, futureResult ) ) );
+                } else {
+
+                    LOG.debug( "Setting error result" );
+
+                    // Either the transaction failed to commit for some reason or, more likely,
+                    // the read above returned ToasterStatus.Down. Either way, fail the
+                    // futureResult and copy the errors.
+
+                    futureResult.set( RpcResultBuilder.<Void>failed().withRpcErrors(
+                                                                     result.getErrors() ).build() );
+                }
             }
-        }
 
-        updateStatus();
-        return currentTask;
+            @Override
+            public void onFailure( final Throwable ex ) {
+                if( ex instanceof OptimisticLockFailedException ) {
+
+                    // Another thread is likely trying to make toast simultaneously and updated the
+                    // status before us. Try reading the status again - if another make toast is
+                    // now in progress, we should get ToasterStatus.Down and fail.
+
+                    LOG.debug( "Got OptimisticLockFailedException - trying again" );
+
+                    checkStatusAndMakeToast( input, futureResult );
+
+                } else {
+
+                    LOG.error( "Failed to commit Toaster status", ex );
+
+                    // Got some unexpected error so fail.
+                    futureResult.set( RpcResultBuilder.<Void> failed()
+                                        .withError( ErrorType.APPLICATION, ex.getMessage() ).build() );
+                }
+            }
+        } );
     }
 
     /**
@@ -191,20 +291,18 @@ public class OpendaylightToaster implements ToasterService, ToasterProviderRunti
      * ToasterRestocked notification.
      */
     @Override
-    public Future<RpcResult<java.lang.Void>> restockToaster(RestockToasterInput input) {
+    public Future<RpcResult<java.lang.Void>> restockToaster(final RestockToasterInput input) {
         LOG.info( "restockToaster: " + input );
 
-        synchronized( taskLock ) {
-            amountOfBreadInStock.set( input.getAmountOfBreadToStock() );
+        amountOfBreadInStock.set( input.getAmountOfBreadToStock() );
 
-            if( amountOfBreadInStock.get() > 0 ) {
-                ToasterRestocked reStockedNotification =
-                    new ToasterRestockedBuilder().setAmountOfBread( input.getAmountOfBreadToStock() ).build();
-                notificationProvider.publish( reStockedNotification );
-            }
+        if( amountOfBreadInStock.get() > 0 ) {
+            ToasterRestocked reStockedNotification = new ToasterRestockedBuilder()
+                .setAmountOfBread( input.getAmountOfBreadToStock() ).build();
+            notificationProvider.publish( reStockedNotification );
         }
 
-        return Futures.immediateFuture(Rpcs.<Void> getRpcResult(true, Collections.<RpcError> emptySet()));
+        return Futures.immediateFuture( RpcResultBuilder.<Void> success().build() );
     }
 
     /**
@@ -224,20 +322,38 @@ public class OpendaylightToaster implements ToasterService, ToasterProviderRunti
         return toastsMade.get();
     }
 
-    private void updateStatus() {
-        if (dataProvider != null) {
-            final DataModificationTransaction t = dataProvider.beginTransaction();
-            t.removeOperationalData(TOASTER_IID);
-            t.putOperationalData(TOASTER_IID, buildToaster());
-
-            try {
-                t.commit().get();
-            } catch (InterruptedException | ExecutionException e) {
-                LOG.warn("Failed to update toaster status, operational otherwise", e);
+    private void setToasterStatusUp( final Function<Boolean,Void> resultCallback ) {
+
+        WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
+        tx.put( LogicalDatastoreType.OPERATIONAL,TOASTER_IID, buildToaster( ToasterStatus.Up ) );
+
+        ListenableFuture<RpcResult<TransactionStatus>> commitFuture = tx.commit();
+
+        Futures.addCallback( commitFuture, new FutureCallback<RpcResult<TransactionStatus>>() {
+            @Override
+            public void onSuccess( final RpcResult<TransactionStatus> result ) {
+                if( result.getResult() != TransactionStatus.COMMITED ) {
+                    LOG.error( "Failed to update toaster status: " + result.getErrors() );
+                }
+
+                notifyCallback( result.getResult() == TransactionStatus.COMMITED );
             }
-        } else {
-            LOG.trace("No data provider configured, not updating status");
-        }
+
+            @Override
+            public void onFailure( final Throwable t ) {
+                // We shouldn't get an OptimisticLockFailedException (or any ex) as no
+                // other component should be updating the operational state.
+                LOG.error( "Failed to update toaster status", t );
+
+                notifyCallback( false );
+            }
+
+            void notifyCallback( final boolean result ) {
+                if( resultCallback != null ) {
+                    resultCallback.apply( result );
+                }
+            }
+        } );
     }
 
     private boolean outOfBread()
@@ -245,19 +361,22 @@ public class OpendaylightToaster implements ToasterService, ToasterProviderRunti
         return amountOfBreadInStock.get() == 0;
     }
 
-    private class MakeToastTask implements Callable<RpcResult<Void>> {
+    private class MakeToastTask implements Callable<Void> {
 
         final MakeToastInput toastRequest;
+        final SettableFuture<RpcResult<Void>> futureResult;
 
-        public MakeToastTask(MakeToastInput toast) {
-            toastRequest = toast;
+        public MakeToastTask( final MakeToastInput toastRequest,
+                              final SettableFuture<RpcResult<Void>> futureResult ) {
+            this.toastRequest = toastRequest;
+            this.futureResult = futureResult;
         }
 
         @Override
-        public RpcResult<Void> call() {
+        public Void call() {
             try
             {
-                // make toast just sleeps for n secondn per doneness level.
+                // make toast just sleeps for n seconds per doneness level.
                 long darknessFactor = OpendaylightToaster.this.darknessFactor.get();
                 Thread.sleep(darknessFactor * toastRequest.getToasterDoneness());
 
@@ -275,15 +394,25 @@ public class OpendaylightToaster implements ToasterService, ToasterProviderRunti
                 notificationProvider.publish( new ToasterOutOfBreadBuilder().build() );
             }
 
-            synchronized (taskLock) {
-                currentTask = null;
-            }
+            // Set the Toaster status back to up - this essentially releases the toasting lock.
+            // We can't clear the current toast task nor set the Future result until the
+            // update has been committed so we pass a callback to be notified on completion.
+
+            setToasterStatusUp( new Function<Boolean,Void>() {
+                @Override
+                public Void apply( final Boolean result ) {
+
+                    currentMakeToastTask.set( null );
+
+                    LOG.debug("Toast done");
 
-            updateStatus();
+                    futureResult.set( RpcResultBuilder.<Void>success().build() );
 
-            LOG.debug("Toast done");
+                    return null;
+                }
+            } );
 
-            return Rpcs.<Void> getRpcResult(true, null, Collections.<RpcError> emptySet());
+            return null;
         }
     }
 }
index d6de5cfd17136d625a205b0b77122b2143c803fc..8de0c98c63e98f136ac91c98b1792fb040e0be63 100644 (file)
@@ -53,7 +53,7 @@ module toaster-provider-impl {
                 uses config:service-ref {
                     refine type {
                         mandatory false;
-                        config:required-identity mdsal:binding-data-broker;
+                        config:required-identity mdsal:binding-async-data-broker;
                     }
                 }
             }
index af61db1a8096874945fe92f7fc5478c948b0f5da..b1db280c2472802aed2e97ce525422308eca3b12 100644 (file)
@@ -95,6 +95,8 @@ final class FlowComparator {
         if (statsFlow == storedFlow) {
             return true;
         }
+        if (storedFlow == null && statsFlow != null) return false;
+        if (statsFlow == null && storedFlow != null) return false;
         if (storedFlow.getClass() != statsFlow.getClass()) {
             return false;
         }
index 0ae33b8c71fa93add1914d79c595c14538b0737f..29a27e2bb2a2cdfc85c7b49eada243bdc9f8a531 100644 (file)
@@ -48,9 +48,13 @@ public class StatisticsRequestScheduler implements DataTransactionListener {
     private final TimerTask task = new TimerTask() {
         @Override
         public void run() {
-            long now = System.nanoTime();
-            if(now > lastRequestTime+TimeUnit.MILLISECONDS.toNanos(REQUEST_MONITOR_INTERVAL)){
-                requestStatistics();
+            try{
+                long now = System.nanoTime();
+                if(now > lastRequestTime+TimeUnit.MILLISECONDS.toNanos(REQUEST_MONITOR_INTERVAL)){
+                    requestStatistics();
+                }
+            }catch (IllegalArgumentException | IllegalStateException | NullPointerException e){
+                srsLogger.warn("Exception occured while sending statistics request : {}",e);
             }
         }
     };
index c10f0a9089ed5341550d21a62ea68c3ac67c9a02..8a29139854c3f801cc372c7c7ac94a1995c20ce4 100644 (file)
                             org.opendaylight.controller.netconf.confignetconfconnector.transactions,
                             org.opendaylight.controller.netconf.confignetconfconnector.util,
                             org.opendaylight.controller.netconf.confignetconfconnector.osgi,
-                            org.opendaylight.controller.config.util,
                             org.opendaylight.controller.netconf.confignetconfconnector.exception,</Private-Package>
             <Import-Package>com.google.common.base,
                             com.google.common.collect,
                             com.google.common.io,
                             org.opendaylight.yangtools.yang.model.api.type,
                             org.opendaylight.yangtools.sal.binding.generator.spi,
-                            org.opendaylight.yangtools.sal.binding.yang.types,</Import-Package>
+                            org.opendaylight.yangtools.sal.binding.yang.types,
+                            org.opendaylight.controller.config.util
+              </Import-Package>
             <Export-Package></Export-Package>
           </instructions>
         </configuration>
index f86d641112585515198e9cbad18cce3c62a89389..2b363ea153960eeb98754855ffa54473e43fad14 100644 (file)
@@ -13,11 +13,12 @@ import java.util.Map;
 import javax.management.InstanceNotFoundException;
 import javax.management.ObjectName;
 import org.opendaylight.controller.config.api.ServiceReferenceReadableRegistry;
+import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
 import org.opendaylight.yangtools.yang.common.QName;
 
 public class ServiceRegistryWrapper {
 
-    private ServiceReferenceReadableRegistry configServiceRefRegistry;
+    private final ServiceReferenceReadableRegistry configServiceRefRegistry;
 
     public ServiceRegistryWrapper(ServiceReferenceReadableRegistry configServiceRefRegistry) {
         this.configServiceRefRegistry = configServiceRefRegistry;
@@ -43,7 +44,12 @@ public class ServiceRegistryWrapper {
 
         String qNameOfService = configServiceRefRegistry.getServiceInterfaceName(namespace, serviceName);
         try {
-            return configServiceRefRegistry.getServiceReference(qNameOfService, refName);
+            /*
+             Remove transaction name as this is redundant - will be stripped in DynamicWritableWrapper,
+             and makes it hard to compare with service references got from MXBean attributes
+            */
+            return ObjectNameUtil.withoutTransactionName(
+                    configServiceRefRegistry.getServiceReference(qNameOfService, refName));
         } catch (InstanceNotFoundException e) {
             throw new IllegalArgumentException("No serviceInstance mapped to " + refName
                     + " under service name " + serviceName + " , " + refNameToInstance.keySet(), e);
index 37ad2bb22260ab45027b635d5671da8077d823b7..59a1d4fe7141bbe54a2dc770a4d2c789819bf52d 100644 (file)
@@ -104,8 +104,11 @@ public final class Services {
 
             String serviceName =  ObjectNameAttributeReadingStrategy.checkPrefixAndExtractServiceName(typeElement, prefixNamespace);
 
-            Map<String, String> innerMap = Maps.newHashMap();
-            namespaceToServices.put(serviceName, innerMap);
+            Map<String, String> innerMap = namespaceToServices.get(serviceName);
+            if (innerMap == null) {
+                innerMap = Maps.newHashMap();
+                namespaceToServices.put(serviceName, innerMap);
+            }
 
             List<XmlElement> instances = service.getChildElements(XmlNetconfConstants.INSTANCE_KEY);
             service.checkUnrecognisedElements(instances, typeElement);
index 6ebeeaa07ba86034991ffd584448135bd2ec5b13..d8ceb311038e6f0602832448a32de27db6d3e664 100644 (file)
@@ -8,6 +8,10 @@
 
 package org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig;
 
+import static java.util.Arrays.asList;
+
+import java.util.ArrayList;
+import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
 import javax.management.Attribute;
@@ -30,7 +34,7 @@ public class MergeEditConfigStrategy extends AbstractEditConfigStrategy {
 
     @Override
     void handleMissingInstance(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta,
-            String module, String instance, ServiceRegistryWrapper services) throws NetconfConfigHandlingException {
+                               String module, String instance, ServiceRegistryWrapper services) throws NetconfConfigHandlingException {
         throw new NetconfConfigHandlingException(
                 String.format("Unable to handle missing instance, no missing instances should appear at this point, missing: %s : %s ",
                         module,
@@ -39,6 +43,7 @@ public class MergeEditConfigStrategy extends AbstractEditConfigStrategy {
                 NetconfDocumentedException.ErrorTag.operation_failed,
                 NetconfDocumentedException.ErrorSeverity.error);
     }
+
     @Override
     void executeStrategy(Map<String, AttributeConfigElement> configuration, ConfigTransactionClient ta, ObjectName on, ServiceRegistryWrapper services) throws NetconfConfigHandlingException {
 
@@ -51,10 +56,16 @@ public class MergeEditConfigStrategy extends AbstractEditConfigStrategy {
                     continue;
                 }
 
-                Object value = ace.getResolvedValue().get();
-                ta.setAttribute(on, ace.getJmxName(), new Attribute(ace.getJmxName(), value));
-                logger.debug("Attribute {} set to {} for {}", configAttributeEntry.getKey(), value, on);
+                Object toBeMergedIn = ace.getResolvedValue().get();
+                // Get the existing values so we can merge the new values with them.
+                Attribute currentAttribute = ta.getAttribute(on, ace.getJmxName());
+                Object oldValue = (currentAttribute != null ? currentAttribute.getValue() : null);
+                // Merge value with currentValue
+                toBeMergedIn = merge(oldValue, toBeMergedIn);
+                ta.setAttribute(on, ace.getJmxName(), new Attribute(ace.getJmxName(), toBeMergedIn));
+                logger.debug("Attribute {} set to {} for {}", configAttributeEntry.getKey(), toBeMergedIn, on);
             } catch (Exception e) {
+                logger.error("Error while merging objectnames of {}", on, e);
                 throw new NetconfConfigHandlingException(String.format("Unable to set attributes for %s, Error with attribute %s : %s ",
                         on,
                         configAttributeEntry.getKey(),
@@ -65,4 +76,44 @@ public class MergeEditConfigStrategy extends AbstractEditConfigStrategy {
             }
         }
     }
+
+    /**
+     * Merge value into current value
+     * Currently, this is only implemented for arrays of ObjectNames, but that is the
+     * most common case for which it is needed.
+     */
+    protected Object merge(Object oldValue, Object toBeMergedIn) {
+        if (oldValue instanceof ObjectName[] && toBeMergedIn instanceof ObjectName[]) {
+            toBeMergedIn = mergeObjectNameArrays((ObjectName[]) oldValue, (ObjectName[]) toBeMergedIn);
+        }
+        return toBeMergedIn;
+    }
+
+    /**
+     * Merge value into current values
+     * This implements for arrays of ObjectNames, but that is the
+     * most common case for which it is needed.
+     *
+     * @param oldValue - the new values to be merged into existing values
+     * @param toBeMergedIn - the existing values
+     *
+     * @return an ObjectName[] consisting the elements of currentValue with an elements from values not already present in currentValue added
+     *
+     */
+    protected ObjectName[] mergeObjectNameArrays(ObjectName[] oldValue, ObjectName[] toBeMergedIn) {
+        List<ObjectName> newValueList = new ArrayList<>();
+        newValueList.addAll(asList(oldValue));
+        /*
+         It is guaranteed that old values do not contain transaction name.
+         Since toBeMergedIn is filled using service references translated by ServiceRegistryWrapper, it
+         is also guaranteed that this list will not contain transaction names.
+         Run through the list of values to be merged.  If we don't have them already, add them to the list.
+         */
+        for (ObjectName objName : toBeMergedIn) {
+            if (!newValueList.contains(objName)) {
+                newValueList.add(objName);
+            }
+        }
+        return newValueList.toArray(new ObjectName[newValueList.size()]);
+    }
 }
index 1069858b4777008a321b7021beb172ca951675df..f5fe089d4d80d1b614636b9522e0963ac2d922c9 100644 (file)
@@ -95,8 +95,10 @@ public class NetconfOperationServiceImpl implements NetconfOperationService {
         Set<Capability> capabilities = new HashSet<>();
         // [RFC6241] 8.3.  Candidate Configuration Capability
         capabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:candidate:1.0"));
+
+        // TODO rollback on error not supported EditConfigXmlParser:100
         // [RFC6241] 8.5.  Rollback-on-Error Capability
-        capabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:rollback-on-error:1.0"));
+        // capabilities.add(new BasicCapability("urn:ietf:params:netconf:capability:rollback-on-error:1.0"));
 
         Set<Module> modules = yangStoreSnapshot.getModules();
         for (Module module : modules) {
index 5840c9dbd14d1aa3b3fe050d079e426d8ec21f20..85cdf0335fecc793fc29e0c357f41cf4ee41c1e6 100644 (file)
@@ -9,33 +9,65 @@
 package org.opendaylight.controller.netconf.confignetconfconnector.osgi;
 
 import java.lang.ref.SoftReference;
-import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
+import java.util.concurrent.atomic.AtomicReference;
 
-import javax.annotation.concurrent.GuardedBy;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 public class YangStoreServiceImpl implements YangStoreService {
+    private static final Logger LOG = LoggerFactory.getLogger(YangStoreServiceImpl.class);
+
+    /**
+     * This is a rather interesting locking model. We need to guard against both the
+     * cache expiring from GC and being invalidated by schema context change. The
+     * context can change while we are doing processing, so we do not want to block
+     * it, so no synchronization can happen on the methods.
+     *
+     * So what we are doing is the following:
+     *
+     * We synchronize with GC as usual, using a SoftReference.
+     *
+     * The atomic reference is used to synchronize with {@link #refresh()}, e.g. when
+     * refresh happens, it will push a SoftReference(null), e.g. simulate the GC. Now
+     * that may happen while the getter is already busy acting on the old schema context,
+     * so it needs to understand that a refresh has happened and retry. To do that, it
+     * attempts a CAS operation -- if it fails, in knows that the SoftReference has
+     * been replaced and thus it needs to retry.
+     *
+     * Note that {@link #getYangStoreSnapshot()} will still use synchronize() internally
+     * to stop multiple threads doing the same work.
+     */
+    private final AtomicReference<SoftReference<YangStoreSnapshotImpl>> ref = new AtomicReference<>(new SoftReference<YangStoreSnapshotImpl>(null));
     private final SchemaContextProvider service;
-    @GuardedBy("this")
-    private SoftReference<YangStoreSnapshotImpl> cache = new SoftReference<>(null);
 
-    public YangStoreServiceImpl(SchemaContextProvider service) {
+    public YangStoreServiceImpl(final SchemaContextProvider service) {
         this.service = service;
     }
 
     @Override
     public synchronized YangStoreSnapshotImpl getYangStoreSnapshot() throws YangStoreException {
-        YangStoreSnapshotImpl yangStoreSnapshot = cache.get();
-        if (yangStoreSnapshot == null) {
-            yangStoreSnapshot = new YangStoreSnapshotImpl(service.getSchemaContext());
-            cache = new SoftReference<>(yangStoreSnapshot);
+        SoftReference<YangStoreSnapshotImpl> r = ref.get();
+        YangStoreSnapshotImpl ret = r.get();
+
+        while (ret == null) {
+            // We need to be compute a new value
+            ret = new YangStoreSnapshotImpl(service.getSchemaContext());
+
+            if (!ref.compareAndSet(r, new SoftReference<>(ret))) {
+                LOG.debug("Concurrent refresh detected, recomputing snapshot");
+                r = ref.get();
+                ret = null;
+            }
         }
-        return yangStoreSnapshot;
+
+        return ret;
     }
 
     /**
      * Called when schema context changes, invalidates cache.
      */
-    public synchronized void refresh() {
-        cache.clear();
+    public void refresh() {
+        ref.set(new SoftReference<YangStoreSnapshotImpl>(null));
     }
 }
index 782998067f80d5fc35a1249dedbaa8e0dcf4e37b..827708f31ceb52fbc39bd8c202fa630cf698d225 100644 (file)
@@ -9,6 +9,13 @@
 package org.opendaylight.controller.netconf.confignetconfconnector.osgi;
 
 import com.google.common.collect.Maps;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
 import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
 import org.opendaylight.controller.config.yangjmxgenerator.PackageTranslator;
 import org.opendaylight.controller.config.yangjmxgenerator.ServiceInterfaceEntry;
@@ -21,18 +28,12 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-
 public class YangStoreSnapshotImpl implements YangStoreSnapshot {
     private static final Logger logger = LoggerFactory.getLogger(YangStoreSnapshotImpl.class);
 
 
     private final Map<String /* Namespace from yang file */,
-            Map<String /* Name of module entry from yang file */, ModuleMXBeanEntry>> moduleMXBeanEntryMap;
+    Map<String /* Name of module entry from yang file */, ModuleMXBeanEntry>> moduleMXBeanEntryMap;
 
 
     private final Map<QName, Map<String, ModuleMXBeanEntry>> qNamesToIdentitiesToModuleMXBeanEntries;
@@ -40,7 +41,7 @@ public class YangStoreSnapshotImpl implements YangStoreSnapshot {
     private final SchemaContext schemaContext;
 
 
-    public YangStoreSnapshotImpl(SchemaContext resolveSchemaContext) {
+    public YangStoreSnapshotImpl(final SchemaContext resolveSchemaContext) {
         logger.trace("Resolved modules:{}", resolveSchemaContext.getModules());
         this.schemaContext = resolveSchemaContext;
         // JMX generator
@@ -60,7 +61,7 @@ public class YangStoreSnapshotImpl implements YangStoreSnapshot {
                     qNamesToSIEs.put(sieEntry.getKey(), sieEntry.getValue());
                 } else {
                     throw new IllegalStateException("Cannot add two SIE with same qname "
-                                    + sieEntry.getValue());
+                            + sieEntry.getValue());
                 }
             }
         }
@@ -75,7 +76,7 @@ public class YangStoreSnapshotImpl implements YangStoreSnapshot {
             TypeProviderWrapper typeProviderWrapper = new TypeProviderWrapper(
                     new TypeProviderImpl(resolveSchemaContext));
 
-            QName qName = new QName(module.getNamespace(), module.getRevision(), module.getName());
+            QName qName = QName.create(module.getNamespace(), module.getRevision(), module.getName());
 
             Map<String /* MB identity local name */, ModuleMXBeanEntry> namesToMBEs =
                     Collections.unmodifiableMap(ModuleMXBeanEntry.create(module, qNamesToSIEs, resolveSchemaContext,
@@ -105,7 +106,7 @@ public class YangStoreSnapshotImpl implements YangStoreSnapshot {
     }
 
     @Override
-    public String getModuleSource(org.opendaylight.yangtools.yang.model.api.ModuleIdentifier moduleIdentifier) {
+    public String getModuleSource(final org.opendaylight.yangtools.yang.model.api.ModuleIdentifier moduleIdentifier) {
         return schemaContext.getModuleSource(moduleIdentifier).get();
     }
 
diff --git a/opendaylight/netconf/config-netconf-connector/src/test/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/editconfig/MergeEditConfigStrategyTest.java b/opendaylight/netconf/config-netconf-connector/src/test/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/editconfig/MergeEditConfigStrategyTest.java
new file mode 100644 (file)
index 0000000..b187749
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+
+package org.opendaylight.controller.netconf.confignetconfconnector.operations.editconfig;
+
+import static java.util.Arrays.asList;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.opendaylight.controller.config.api.jmx.ObjectNameUtil.createReadOnlyModuleON;
+
+import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableMap;
+import java.util.List;
+import java.util.Map;
+import javax.management.ObjectName;
+import org.junit.Before;
+import org.junit.Test;
+import org.opendaylight.controller.config.manager.impl.AbstractConfigTest;
+import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
+import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
+import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModule;
+import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleFactory;
+import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleMXBean;
+import org.opendaylight.controller.netconf.confignetconfconnector.mapping.attributes.fromxml.AttributeConfigElement;
+import org.opendaylight.controller.netconf.confignetconfconnector.mapping.config.ServiceRegistryWrapper;
+
+public class MergeEditConfigStrategyTest extends AbstractConfigTest {
+    private static final MultipleDependenciesModuleFactory factory = new MultipleDependenciesModuleFactory();
+    public static final String PARENT = "parent";
+    public static final String D1 = "d1";
+    public static final String D2 = "d2";
+    public static final String D3 = "d3";
+
+    private static final String factoryName = factory.getImplementationName();
+
+    @Before
+    public void setUp() throws Exception {
+        super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, factory));
+
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
+        ObjectName d1 = transaction.createModule(factoryName, D1);
+        ObjectName d2 = transaction.createModule(factoryName, D2);
+        ObjectName parent = transaction.createModule(factoryName, PARENT);
+        MultipleDependenciesModuleMXBean multipleDependenciesModuleMXBean = transaction.newMXBeanProxy(parent,
+                MultipleDependenciesModuleMXBean.class);
+        multipleDependenciesModuleMXBean.setTestingDeps(asList(d1, d2));
+        transaction.createModule(factoryName, D3);
+        transaction.commit();
+    }
+
+    @Test
+    public void testMergingOfObjectNames() throws Exception {
+        MergeEditConfigStrategy strategy = new MergeEditConfigStrategy();
+        ConfigTransactionJMXClient transaction = configRegistryClient.createTransaction();
+
+        // add D3
+
+        AttributeConfigElement attributeConfigElement = mock(AttributeConfigElement.class);
+        doReturn(Optional.of(new ObjectName[] {createReadOnlyModuleON(factoryName, D3)})).when(attributeConfigElement).getResolvedValue();
+        doReturn("mocked").when(attributeConfigElement).toString();
+        String attributeName = MultipleDependenciesModule.testingDepsJmxAttribute.getAttributeName();
+        doReturn(attributeName).when(attributeConfigElement).getJmxName();
+        Map<String, AttributeConfigElement> configuration = ImmutableMap.of(
+                attributeName,
+                attributeConfigElement);
+
+        strategy.executeConfiguration(factoryName, PARENT, configuration, transaction,
+                mock(ServiceRegistryWrapper.class));
+        transaction.commit();
+
+        // parent's attribute should contain d1,d2,d3
+        MultipleDependenciesModuleMXBean proxy = configRegistryClient.newMXBeanProxy(
+                createReadOnlyModuleON(factoryName, PARENT),
+                MultipleDependenciesModuleMXBean.class);
+        List<ObjectName> testingDeps = proxy.getTestingDeps();
+        List<ObjectName> expected = asList(createReadOnlyModuleON(factoryName, D1),
+                createReadOnlyModuleON(factoryName, D2),
+                createReadOnlyModuleON(factoryName, D3));
+        assertEquals(expected, testingDeps);
+    }
+}
index a063f5786a8f4796d95023849fbc6243e873fa01..1e650c08b124a460c7d19f65200c1b0868ccee17 100644 (file)
@@ -8,14 +8,12 @@
 
 package org.opendaylight.controller.netconf.confignetconfconnector.osgi;
 
+import static org.junit.Assert.fail;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+
 import com.google.common.collect.Maps;
 import com.google.common.collect.Sets;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.matchers.JUnitMatchers;
-import org.opendaylight.controller.config.api.LookupRegistry;
-import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
-import org.opendaylight.yangtools.yang.common.QName;
 
 import java.net.URI;
 import java.text.ParseException;
@@ -24,9 +22,12 @@ import java.util.Date;
 import java.util.Map;
 import java.util.Set;
 
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
+import org.junit.Assert;
+import org.junit.Test;
+import org.junit.matchers.JUnitMatchers;
+import org.opendaylight.controller.config.api.LookupRegistry;
+import org.opendaylight.controller.config.yangjmxgenerator.ModuleMXBeanEntry;
+import org.opendaylight.yangtools.yang.common.QName;
 
 public class NetconfOperationServiceImplTest {
 
@@ -72,15 +73,15 @@ public class NetconfOperationServiceImplTest {
             Assert.assertThat(
                     message,
                     JUnitMatchers
-                            .containsString("missing from config subsystem but present in yangstore: [(namespace?revision=1970-01-01)qname2]"));
+                    .containsString("missing from config subsystem but present in yangstore: [(namespace?revision=1970-01-01)qname2]"));
             Assert.assertThat(
                     message,
                     JUnitMatchers
-                            .containsString("All modules present in config: [(namespace?revision=1970-01-01)qname1]"));
+                    .containsString("All modules present in config: [(namespace?revision=1970-01-01)qname1]"));
         }
     }
 
-    private YangStoreSnapshot mockYangStoreSnapshot(String... qnames) {
+    private YangStoreSnapshot mockYangStoreSnapshot(final String... qnames) {
         YangStoreSnapshot mock = mock(YangStoreSnapshot.class);
 
         Map<String, Map<String, ModuleMXBeanEntry>> map = Maps.newHashMap();
@@ -99,18 +100,18 @@ public class NetconfOperationServiceImplTest {
         return mock;
     }
 
-    private ModuleMXBeanEntry mockMBeanEntry(String qname) {
+    private ModuleMXBeanEntry mockMBeanEntry(final String qname) {
         ModuleMXBeanEntry mock = mock(ModuleMXBeanEntry.class);
         QName q = getQName(qname);
         doReturn(q).when(mock).getYangModuleQName();
         return mock;
     }
 
-    private QName getQName(String qname) {
-        return new QName(URI.create("namespace"), date1970_01_01, qname);
+    private QName getQName(final String qname) {
+        return QName.create(URI.create("namespace"), date1970_01_01, qname);
     }
 
-    private LookupRegistry mockJmxClient(String... visibleQNames) {
+    private LookupRegistry mockJmxClient(final String... visibleQNames) {
         LookupRegistry mock = mock(LookupRegistry.class);
         Set<String> qnames = Sets.newHashSet();
         for (String visibleQName : visibleQNames) {
index 8d85a35bc79ad3f77eb516c14cb23b2003974c13..eddad8b4c7c1df593c45a5f829c3c56828339e18 100644 (file)
@@ -8,6 +8,11 @@
 
 package org.opendaylight.controller.netconf.persist.impl;
 
+import static com.google.common.base.Preconditions.checkNotNull;
+
+import com.google.common.base.Function;
+import com.google.common.base.Stopwatch;
+import com.google.common.collect.Collections2;
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.Collection;
@@ -16,11 +21,10 @@ import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map.Entry;
 import java.util.Set;
+import java.util.SortedSet;
 import java.util.TreeMap;
 import java.util.concurrent.TimeUnit;
-
 import javax.annotation.concurrent.Immutable;
-
 import org.opendaylight.controller.config.api.ConflictingVersionException;
 import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
@@ -41,11 +45,6 @@ import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.xml.sax.SAXException;
 
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Stopwatch;
-import com.google.common.collect.Collections2;
-
 @Immutable
 public class ConfigPusher {
     private static final Logger logger = LoggerFactory.getLogger(ConfigPusher.class);
@@ -84,7 +83,11 @@ public class ConfigPusher {
         ConflictingVersionException lastException;
         Stopwatch stopwatch = new Stopwatch().start();
         do {
-            try (NetconfOperationService operationService = getOperationServiceWithRetries(configSnapshotHolder.getCapabilities(), configSnapshotHolder.toString())) {
+            String idForReporting = configSnapshotHolder.toString();
+            SortedSet<String> expectedCapabilities = checkNotNull(configSnapshotHolder.getCapabilities(),
+                    "Expected capabilities must not be null - %s, check %s", idForReporting,
+                    configSnapshotHolder.getClass().getName());
+            try (NetconfOperationService operationService = getOperationServiceWithRetries(expectedCapabilities, idForReporting)) {
                 return pushConfig(configSnapshotHolder, operationService);
             } catch (ConflictingVersionException e) {
                 lastException = e;
@@ -252,7 +255,7 @@ public class ConfigPusher {
     private static NetconfMessage createEditConfigMessage(Element dataElement) throws NetconfDocumentedException {
         String editConfigResourcePath = "/netconfOp/editConfig.xml";
         try (InputStream stream = ConfigPersisterNotificationHandler.class.getResourceAsStream(editConfigResourcePath)) {
-            Preconditions.checkNotNull(stream, "Unable to load resource " + editConfigResourcePath);
+            checkNotNull(stream, "Unable to load resource " + editConfigResourcePath);
 
             Document doc = XmlUtil.readXmlToDocument(stream);
 
@@ -274,7 +277,7 @@ public class ConfigPusher {
     private static NetconfMessage getCommitMessage() {
         String resource = "/netconfOp/commit.xml";
         try (InputStream stream = ConfigPusher.class.getResourceAsStream(resource)) {
-            Preconditions.checkNotNull(stream, "Unable to load resource " + resource);
+            checkNotNull(stream, "Unable to load resource " + resource);
             return new NetconfMessage(XmlUtil.readXmlToDocument(stream));
         } catch (SAXException | IOException e) {
             // error reading the xml file bundled into the jar
index 6fb231d847f2c5ae8c2022a7951460e19199ff70..3f04010015e8291d8dbeb6e47415d6ab8a12ad3f 100644 (file)
@@ -7,20 +7,25 @@
  */
 package org.opendaylight.controller.netconf.persist.impl.osgi;
 
-import org.junit.matchers.JUnitMatchers;
-
 import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertThat;
 import static org.junit.Assert.fail;
 
+import org.junit.matchers.JUnitMatchers;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 final class TestingExceptionHandler implements Thread.UncaughtExceptionHandler {
 
+    private static final Logger logger = LoggerFactory.getLogger(ConfigPersisterTest.class);
+
     private Throwable t;
 
     @Override
     public void uncaughtException(Thread t, Throwable e) {
+        logger.debug("Uncaught exception in thread {}", t, e);
         this.t = e;
     }
 
diff --git a/opendaylight/netconf/netconf-cli/.gitignore b/opendaylight/netconf/netconf-cli/.gitignore
new file mode 100644 (file)
index 0000000..d5de9f2
--- /dev/null
@@ -0,0 +1,2 @@
+*.log
+cache
diff --git a/opendaylight/netconf/netconf-cli/README b/opendaylight/netconf/netconf-cli/README
new file mode 100644 (file)
index 0000000..c6a0af4
--- /dev/null
@@ -0,0 +1,113 @@
+usage: 
+Submit address + port for initial TCP connection (PURE TCP CONNECTIONS ARE NOT SUPPORTED YET)
+Submit username + password in addition to address + port for initial SSH connection
+If no arguments(or unexpected combination) is submitted, cli will be started without initial connection
+To use with ODL controller, run with: java -jar netconf-cli-0.2.5-SNAPSHOT-executable.jar  --server localhost --port 1830 --username admin --password admin
+
+Generic cli for netconf devices
+
+optional arguments:
+  -h, --help             show this help message and exit
+
+TCP:
+  Base arguments to initiate TCP connection right away
+
+  --server SERVER        Netconf device ip-address/domain name
+  --port PORT            Netconf device port
+
+SSH:
+  SSH credentials, if provided, initial connection will be attempted using SSH
+
+  --username USERNAME    Username for SSH connection
+  --password PASSWORD    Password for SSH connection
+------------------------------------------------------------------------
+
+To run the cli execute:
+
+java -jar netconf-cli-0.2.5-SNAPSHOT-executable.jar --username user --password password --server serverIP --port optionalPort
+
+The cli will connect to the remote device automatically.
+The initialization may take a few moments depending on the size of schemas provided by the device.
+To view the progress, one can take a look inside netconfcli.log file (All logs are in this file starting with level TRACE).
+Cli does not print any logging messages to the console, only to the file.
+
+------------------------------------------------------------------------
+
+Correct initialization + connection should display following output:
+
+[maros@localhost target]$ java -jar netconf-cli-0.2.5-SNAPSHOT-executable.jar  --server localhost --port 1830 --username admin --password admin
+Connecting to localhost via SSH. Please wait.
+Cli is up, available commands:
+
+add-flow(sal-flow)                                                                            add-group(sal-group)                                                                          
+add-meter(sal-meter)                                                                          begin-transaction(sal-remote)                                                                 
+cancel-commit(ietf-netconf)                                                                   cancel-toast(toaster)                                                                         
+clear-toasts-made(toaster-provider-impl)                                                      close(netconf-cli)                                                                            
+close-session(ietf-netconf)                                                                   commit(ietf-netconf)                                                                          
+connect(netconf-cli)                                                                          copy-config(ietf-netconf)                                                                     
+create-data-change-event-subscription(sal-remote)                                             create-notification-stream(sal-remote)                                                        
+delete-config(ietf-netconf)                                                                   discard-changes(ietf-netconf)                                                                 
+disconnect(netconf-cli)                                                                       edit-config(ietf-netconf)                                                                     
+finish-transaction(flow-capable-transaction)                                                  get(ietf-netconf)                                                                             
+get-aggregate-flow-statistics-from-flow-table-for-all-flows(opendaylight-flow-statistics)     get-aggregate-flow-statistics-from-flow-table-for-given-match(opendaylight-flow-statistics)   
+get-all-flow-statistics-from-flow-table(opendaylight-flow-statistics)                         get-all-flows-statistics-from-all-flow-tables(opendaylight-flow-statistics)                   
+get-all-group-statistics(opendaylight-group-statistics)                                       get-all-meter-config-statistics(opendaylight-meter-statistics)                                
+get-all-meter-statistics(opendaylight-meter-statistics)                                       get-all-node-connectors-statistics(opendaylight-port-statistics)                              
+get-all-queues-statistics-from-all-ports(opendaylight-queue-statistics)                       get-all-queues-statistics-from-given-port(opendaylight-queue-statistics)                      
+get-config(ietf-netconf)                                                                      get-dead-events-count(threadpool-impl)                                                        
+get-flow-statistics-from-flow-table(opendaylight-flow-statistics)                             get-flow-tables-statistics(opendaylight-flow-table-statistics)                                
+get-group-description(opendaylight-group-statistics)                                          get-group-features(opendaylight-group-statistics)                                             
+get-group-statistics(opendaylight-group-statistics)                                           get-meter-features(opendaylight-meter-statistics)                                             
+get-meter-statistics(opendaylight-meter-statistics)                                           get-next-transaction-id(flow-capable-transaction)                                             
+get-node-connector-statistics(opendaylight-port-statistics)                                   get-queue(sal-queue)                                                                          
+get-queue-statistics-from-given-port(opendaylight-queue-statistics)                           get-schema(ietf-netconf-monitoring)                                                           
+help(netconf-cli)                                                                             kill-session(ietf-netconf)                                                                    
+lock(ietf-netconf)                                                                            make-scrambled-with-wheat(kitchen-service-impl)                                               
+make-toast(toaster)                                                                           remove-flow(sal-flow)                                                                         
+remove-group(sal-group)                                                                       remove-meter(sal-meter)                                                                       
+reset(config-logging)                                                                         restock-toaster(toaster)                                                                      
+shutdown(shutdown-impl)                                                                       solicit-refresh(flow-topology-discovery)                                                      
+transmit-packet(packet-processing)                                                            unlock(ietf-netconf)                                                                          
+update-flow(sal-flow)                                                                         update-group(sal-group)                                                                       
+update-meter(sal-meter)                                                                       update-port(sal-port)                                                                         
+update-table(sal-table)                                                                       validate(ietf-netconf)                                                                        
+
+netconf()>
+
+
+------------------------------------------------------------------------
+
+At this stage, any supported rpc can be invoked. To see all possible rpcs press TAB (serves as autocomplete). The output contains all the commands reported after at start-up
+
+------------------------------------------------------------------------
+
+Example step-by-step execution of get-config rpc:
+
+1. Type get-config, hit TAB, hit enter
+2. Cli will now walk all the input arguments of get-config rpc and ask for value
+3. Cli asks for filter value
+4. Submit filter (using TAB autocomplete) as a schema path or type "skip" (to not add any filter) and hit enter
+5. Cli asks for config source (e.g. which data-store to query)
+6. Use TAB to view options and submit either running or candidate data-store
+7. Cli will display configuration of the remote device e.g. :
+
+data {
+  a {
+    address {
+      last-name a
+      first-name o
+      street aaaaa
+    }
+    address {
+      last-name a
+      first-name t
+    }
+    address {
+      last-name a
+      first-name y
+    }
+  }
+}
+
+
+------------------------------------------------------------------------
diff --git a/opendaylight/netconf/netconf-cli/README_ODL b/opendaylight/netconf/netconf-cli/README_ODL
new file mode 100644 (file)
index 0000000..3a15454
--- /dev/null
@@ -0,0 +1,154 @@
+This file contains ODL controller specific examples:
+
+1A. Connecting to ODL controller automatically:
+    a. Make sure ODL controller is running on your or any other accessible device
+    b. Start the cli using this command (in folder controller/opendaylight/netconf/netconf-cli/target/):
+        java -jar netconf-cli-0.2.5-SNAPSHOT-executable.jar  --server localhost --port 1830 --username admin --password admin
+    c. The cli will start up in aprox. 20 seconds (Schema download might take some time on the first connection, subsequent attempts should take less time)
+    d. You should see the list of commands avaliable in the controller e.g.:
+        add-flow(sal-flow)                                                                            add-group(sal-group)                                                                          
+        add-meter(sal-meter)                                                                          begin-transaction(sal-remote)                                                                 
+        cancel-commit(ietf-netconf)                                                                   cancel-toast(toaster)                                                                         
+        clear-toasts-made(toaster-provider-impl)                                                      close(netconf-cli)                                                                            
+        close-session(ietf-netconf)                                                                   commit(ietf-netconf)                                                                          
+        connect(netconf-cli)                                                                          copy-config(ietf-netconf)                                                                     
+        create-data-change-event-subscription(sal-remote)                                             ....
+
+
+1B. Connecting to ODL from the CLI:
+    a. Make sure ODL controller is running on your or any other accessible device
+    b. Start the cli using this command (in folder controller/opendaylight/netconf/netconf-cli/target/):
+        java -jar netconf-cli-0.2.5-SNAPSHOT-executable.jar
+    c. The cli will start app right away (few seconds)
+    d. You should see only the basic commands e.g. connect, close, help, disconnect 
+    e. Type connect, hit TAB, hit ENTER
+    f. Cli will ask for connect arguments: [address-name, address-port, user-name, user-password]
+    g. Address-name
+        The cli will ask what type of address you want to provide (domain-name or ip-address). This is caused by the yang model for connect command, the address-name is of type ietf-inet-types:host, which is a union of domain-name and ip-address.
+        Submit "domain-name" (TAB can be used for autocompete)
+        Now you need to provide value, submit "localhost" (TAB can be used for autocomplete, as "localhost" is the default value)
+    h. Address-port
+        Submit 1830 (default port for netconf SSH server in ODL)
+    i. User-name
+        Submit "admin"
+    j. User-password
+        Submit "admin"
+    k. The connection will be up in aprox. 20 seconds (Schema download might take some time on the first connection, subsequent attempts should take less time)
+    l. You should see the list of commands available in the controller
+
+
+2.  Disconnecting from ODL in the CLI
+    a. Execute scenario 1A or 1B
+    b. Type "disconn", hit TAB, hit Enter
+    c. You should see the following output:
+        status Connection disconnected
+    d. Use TAB to see available commands, only local commands are present now
+    e. Now you can use the connect command(as in 1B) to connect again
+
+
+3.  Using help command
+    a. Help command can be executed in connected as well as disconnected state
+    b. Type "help", hit TAB, hit Enter
+    c. You should see the help conent containing the list of all available commands with description for each of them e.g.
+        commands  {
+          commands [id=close(netconf-cli)] {
+            id close(netconf-cli)
+            description Close the whole cli
+          }
+          commands [id=help(netconf-cli)] {
+            id help(netconf-cli)
+            description Display help
+          }
+          commands [id=disconnect(netconf-cli)] {
+            id disconnect(netconf-cli)
+            description Disconnect from a netconf device that is currently connected
+          }
+          commands [id=connect(netconf-cli)] {
+            id connect(netconf-cli)
+            description Connect to a remote netconf device, if not connected yet. Connection initialization is blocking and might take some time, depending on amount of yang schemas in remote device.
+          }
+        }
+
+
+4.  Executing get-config command (get-config(ietf-netconf))
+    a. Execute scenario 1A or 1B
+    b. Type "get-config", hit TAB, hit Enter
+    c. Cli will ask for get-config arguments: [filter, source]
+    d. Filter
+        Submit "skip" (This will ignore the filter attribute, ODL does not support filtering at this moment, but will be supported in near future)
+    e. Source
+        You have to choose from candidate, running, startup. Submit running.
+    f. You should see the whole configuration of the ODL e.g.:
+        data {
+          modules {
+            module  {
+              module [name=toaster-provider-impl] {
+                name toaster-provider-impl
+                type (urn:opendaylight:params:xml:ns:yang:controller:config:toaster-provider:impl?revision=2014-01-31)toaster-provider-impl
+                choice configuration (toaster-provider-impl)  {
+                    ...
+
+
+5.  Executing get command (get(ietf-netconf))
+    a. Execute scenario 1A or 1B
+    b. Type "get(", hit TAB, hit Enter
+    c. Cli will ask for get arguments: [filter]
+    d. Filter
+        Submit "skip" (This will ignore the filter attribute, ODL does not support filtering at this moment, but will be supported in near future)
+    f. You should see the whole data-tree of the ODL
+
+
+6.  Executing edit-config command (edit-config(ietf-netconf))
+    a. Execute scenario 1A or 1B
+    b. Type "edit", hit TAB, hit Enter
+    c. Cli will ask for edit-config arguments: [default-operation, edit-content, error-option, target, test-option]
+    d. Config
+        Config contains the data to be edited
+        1. First you have to specify a path pointing to a concrete data node. Use TAB to help with autocomplete.
+        Submit "modules(config)/module(config)/"
+        Module node is of type list and now you have to construct a whole new list entry for the module list.
+        2. The cli will ask for these nodes: [configuration, name, type]
+            Name - Submit any name e.g. newModule
+            Type - For Type you have to pick from available module types in the ODL, hit TAB for hints
+               Submit "threadfactory-naming(threadpool-impl)" to create a new instance of threadfactory in the ODL.
+            Configuration - For configuration you have to pick from available module types again
+               Submit "threadfactory-naming" to match previous module type
+               The cli will now ask for threadfactory-naming specific configuration: [prefix]
+                    Prefix - Submit any string
+        
+        The cli will now if you want to create another module entry.
+        Submit "N".
+    e. Default-operation
+        Submit "skip" to skip or pick from available e.g. merge, replace etc.
+    f. Error-option
+        Submit "skip" to skip option.
+    g. Config-target
+        This is a choice between running and candidate. Submit candidate to edit configuration only in the candidate datastore.
+    h. Test-option
+        Submit "skip" to skip option.
+    i. You should see OK response
+    j. You can check the candidate datastore change by executing get-config command as in scenario 4, but pick candidate as the source.
+    k. You should see this module in the output:
+        module [name=newModule] {
+            name newModule
+            type (urn:opendaylight:params:xml:ns:yang:controller:threadpool:impl?revision=2013-04-05)threadfactory-naming
+            choice configuration (threadfactory-naming)  {
+              name-prefix prefix
+            }
+          }
+
+
+7. Commiting changes from candidate to running datastore
+    a. Execute scenario 6.
+    b. Type commit, hit TAB, hit Enter
+    c. Cli will ask for commit arguments: [confirm-timeout, confirmed, persist, persist-id]. We will skip all these arguments since they are not supported in ODL. Cli should be able to detect this and not ask for them. This is a TODO, by supporting feature/if-feature detection in the CLI.
+    d. Confirm-timeout
+        Skip
+    e. Confirmed
+        N
+    f. Persist
+        Skip
+    g. Persist-id
+        Skip
+    h. You should see OK response
+    i. You can check the candidate datastore change by executing get-config command as in scenario 4.
diff --git a/opendaylight/netconf/netconf-cli/pom.xml b/opendaylight/netconf/netconf-cli/pom.xml
new file mode 100644 (file)
index 0000000..cd7a1aa
--- /dev/null
@@ -0,0 +1,109 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- vi: set et smarttab sw=4 tabstop=4: -->
+<!-- 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-cli</artifactId>
+  <packaging>jar</packaging>
+  <name>${project.artifactId}</name>
+
+  <!--
+  <properties>
+    <checkstyle.skip>true</checkstyle.skip>
+  </properties> -->
+
+  <dependencies>
+    <dependency>
+      <groupId>ch.qos.logback</groupId>
+      <artifactId>logback-classic</artifactId>
+      <!--TODO configure properly -->
+    </dependency>
+    <dependency>
+      <groupId>jline</groupId>
+      <artifactId>jline</artifactId>
+      <version>2.11</version>
+    </dependency>
+    <dependency>
+      <groupId>net.sourceforge.argparse4j</groupId>
+      <artifactId>argparse4j</artifactId>
+      <version>0.4.3</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>sal-core-api</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>sal-netconf-connector</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.yangtools</groupId>
+      <artifactId>mockito-configuration</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.yangtools</groupId>
+      <artifactId>yang-data-impl</artifactId>
+      <!--        <version>0.6.2-SNAPSHOT</version>-->
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.yangtools</groupId>
+      <artifactId>yang-data-json</artifactId>
+      <version>0.6.2-SNAPSHOT</version>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.yangtools</groupId>
+      <artifactId>yang-model-api</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.yangtools</groupId>
+      <artifactId>yang-parser-impl</artifactId>
+    </dependency>
+  </dependencies>
+
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-jar-plugin</artifactId>
+        <configuration>
+          <archive>
+            <manifest>
+              <mainClass>org.opendaylight.controller.netconf.cli.Main</mainClass>
+            </manifest>
+          </archive>
+        </configuration>
+      </plugin>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-shade-plugin</artifactId>
+        <configuration></configuration>
+        <executions>
+          <execution>
+            <goals>
+              <goal>shade</goal>
+            </goals>
+            <phase>package</phase>
+            <configuration>
+              <transformers>
+                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
+                  <mainClass>org.opendaylight.controller.netconf.cli.Main</mainClass>
+                </transformer>
+              </transformers>
+              <shadedArtifactAttached>true</shadedArtifactAttached>
+              <shadedClassifierName>executable</shadedClassifierName>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+    </plugins>
+  </build>
+</project>
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/Cli.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/Cli.java
new file mode 100644 (file)
index 0000000..a49c7b9
--- /dev/null
@@ -0,0 +1,218 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import jline.console.UserInterruptException;
+import jline.console.completer.Completer;
+import jline.console.completer.StringsCompleter;
+import org.opendaylight.controller.netconf.cli.commands.Command;
+import org.opendaylight.controller.netconf.cli.commands.CommandConstants;
+import org.opendaylight.controller.netconf.cli.commands.CommandDispatcher;
+import org.opendaylight.controller.netconf.cli.commands.CommandInvocationException;
+import org.opendaylight.controller.netconf.cli.commands.input.Input;
+import org.opendaylight.controller.netconf.cli.commands.input.InputDefinition;
+import org.opendaylight.controller.netconf.cli.commands.output.Output;
+import org.opendaylight.controller.netconf.cli.commands.output.OutputDefinition;
+import org.opendaylight.controller.netconf.cli.io.ConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.cli.reader.ReadingException;
+import org.opendaylight.controller.netconf.cli.writer.OutFormatter;
+import org.opendaylight.controller.netconf.cli.writer.WriteException;
+import org.opendaylight.controller.netconf.cli.writer.Writer;
+import org.opendaylight.controller.netconf.cli.writer.impl.CompositeNodeWriter;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
+
+/**
+ * The top level cli state that dispatches command executions
+ */
+public class Cli implements Runnable {
+    private final CommandDispatcher commandRegistry;
+    private final CommandArgHandlerRegistry argumentHandlerRegistry;
+    private final SchemaContextRegistry schemaContextRegistry;
+    private final ConsoleIO consoleIO;
+
+    public Cli(final ConsoleIO consoleIO, final CommandDispatcher commandRegistry,
+            final CommandArgHandlerRegistry argumentHandlerRegistry, final SchemaContextRegistry schemaContextRegistry) {
+        this.consoleIO = consoleIO;
+        this.commandRegistry = commandRegistry;
+        this.argumentHandlerRegistry = argumentHandlerRegistry;
+        this.schemaContextRegistry = schemaContextRegistry;
+    }
+
+    @Override
+    public void run() {
+        try {
+            consoleIO.writeLn("Cli is up, available commands:");
+            final RootConsoleContext consoleContext = new RootConsoleContext(commandRegistry);
+            consoleIO.enterContext(consoleContext);
+            consoleIO.complete();
+            consoleIO.writeLn("");
+
+            while (true) {
+                final String commandName = consoleIO.read();
+                final Optional<Command> commandOpt = commandRegistry.getCommand(commandName);
+
+                if (commandOpt.isPresent() == false) {
+                    continue;
+                }
+
+                final Command command = commandOpt.get();
+                try {
+                    consoleIO.enterContext(command.getConsoleContext());
+                    final Output response = command.invoke(handleInput(command.getInputDefinition()));
+                    handleOutput(command, response);
+                } catch (final CommandInvocationException e) {
+                    consoleIO.write(e.getMessage());
+                } catch (final UserInterruptException e) {
+                    consoleIO.writeLn("Command " + command.getCommandId() + " was terminated.");
+                } finally {
+                    consoleIO.leaveContext();
+                }
+
+            }
+        } catch (final IOException e) {
+            throw new RuntimeException("IO failure", e);
+        }
+    }
+
+    private void handleOutput(final Command command, final Output response) {
+        final OutputDefinition outputDefinition = command.getOutputDefinition();
+
+        final Writer<DataSchemaNode> outHandler = argumentHandlerRegistry.getGenericWriter();
+        if (outputDefinition.isEmpty()) {
+            handleEmptyOutput(command, response);
+        } else {
+            handleRegularOutput(response, outputDefinition, outHandler);
+        }
+    }
+
+    private void handleRegularOutput(final Output response, final OutputDefinition outputDefinition,
+            final Writer<DataSchemaNode> outHandler) {
+        final Map<DataSchemaNode, List<Node<?>>> unwrap = response.unwrap(outputDefinition);
+
+        for (final DataSchemaNode schemaNode : unwrap.keySet()) {
+            Preconditions.checkNotNull(schemaNode);
+
+            try {
+
+                // FIXME move custom writer to GenericWriter/Serializers ...
+                // this checks only first level
+                final Optional<Class<? extends Writer<DataSchemaNode>>> customReaderClassOpt = tryGetCustomHandler(schemaNode);
+
+                if (customReaderClassOpt.isPresent()) {
+                    final Writer<DataSchemaNode> customReaderInstance = argumentHandlerRegistry
+                            .getCustomWriter(customReaderClassOpt.get());
+                    Preconditions.checkNotNull(customReaderInstance, "Unknown custom writer: %s",
+                            customReaderClassOpt.get());
+                    customReaderInstance.write(schemaNode, unwrap.get(schemaNode));
+                } else {
+                    outHandler.write(schemaNode, unwrap.get(schemaNode));
+                }
+
+            } catch (final WriteException e) {
+                throw new IllegalStateException("Unable to write value for: " + schemaNode.getQName() + " from: "
+                        + unwrap.get(schemaNode), e);
+            }
+        }
+    }
+
+    private void handleEmptyOutput(final Command command, final Output response) {
+        try {
+            new CompositeNodeWriter(consoleIO, new OutFormatter()).write(null,
+                    Collections.<Node<?>> singletonList(response.getOutput()));
+        } catch (final WriteException e) {
+            throw new IllegalStateException("Unable to write value for: " + response.getOutput().getNodeType()
+                    + " from: " + command.getCommandId(), e);
+        }
+    }
+
+    private Input handleInput(final InputDefinition inputDefinition) {
+        List<Node<?>> allArgs = Collections.emptyList();
+        try {
+            if (!inputDefinition.isEmpty()) {
+                allArgs = argumentHandlerRegistry.getGenericReader(schemaContextRegistry.getLocalSchemaContext()).read(
+                        inputDefinition.getInput());
+            }
+        } catch (final ReadingException e) {
+            throw new IllegalStateException("Unable to read value for: " + inputDefinition.getInput().getQName(), e);
+        }
+
+        return new Input(allArgs);
+    }
+
+    // TODO move tryGet to GenericWriter, GenericReader has the same code
+    private <T> Optional<Class<? extends T>> tryGetCustomHandler(final DataSchemaNode dataSchemaNode) {
+
+        for (final UnknownSchemaNode unknownSchemaNode : dataSchemaNode.getUnknownSchemaNodes()) {
+
+            if (isExtenstionForCustomHandler(unknownSchemaNode)) {
+                final String argumentHandlerClassName = unknownSchemaNode.getNodeParameter();
+                try {
+                    final Class<?> argumentClass = Class.forName(argumentHandlerClassName);
+                    // TODO add check before cast
+                    return Optional.<Class<? extends T>> of((Class<? extends T>) argumentClass);
+                } catch (final ClassNotFoundException e) {
+                    throw new IllegalArgumentException("Unknown custom reader class " + argumentHandlerClassName
+                            + " for: " + dataSchemaNode.getQName());
+                }
+            }
+        }
+
+        return Optional.absent();
+    }
+
+    private boolean isExtenstionForCustomHandler(final UnknownSchemaNode unknownSchemaNode) {
+        final QName qName = unknownSchemaNode.getExtensionDefinition().getQName();
+        return qName.equals(CommandConstants.ARG_HANDLER_EXT_QNAME);
+    }
+
+    private static final class RootConsoleContext implements ConsoleContext {
+
+        private final Completer completer;
+
+        public RootConsoleContext(final CommandDispatcher commandRegistry) {
+            completer = new CommandCompleter(commandRegistry);
+        }
+
+        @Override
+        public Completer getCompleter() {
+            return completer;
+        }
+
+        @Override
+        public Optional<String> getPrompt() {
+            return Optional.absent();
+        }
+
+        private class CommandCompleter extends StringsCompleter {
+
+            private final CommandDispatcher commandRegistry;
+
+            public CommandCompleter(final CommandDispatcher commandRegistry) {
+                this.commandRegistry = commandRegistry;
+            }
+
+            @Override
+            public int complete(final String buffer, final int cursor, final List<CharSequence> candidates) {
+                getStrings().clear();
+                getStrings().addAll(commandRegistry.getCommandIds());
+                return super.complete(buffer, cursor, candidates);
+            }
+        }
+    }
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/CommandArgHandlerRegistry.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/CommandArgHandlerRegistry.java
new file mode 100644 (file)
index 0000000..2eab22a
--- /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.netconf.cli;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Maps;
+import java.util.Map;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.cli.reader.Reader;
+import org.opendaylight.controller.netconf.cli.reader.custom.ConfigReader;
+import org.opendaylight.controller.netconf.cli.reader.custom.EditContentReader;
+import org.opendaylight.controller.netconf.cli.reader.custom.FilterReader;
+import org.opendaylight.controller.netconf.cli.reader.custom.PasswordReader;
+import org.opendaylight.controller.netconf.cli.reader.impl.GenericReader;
+import org.opendaylight.controller.netconf.cli.writer.OutFormatter;
+import org.opendaylight.controller.netconf.cli.writer.Writer;
+import org.opendaylight.controller.netconf.cli.writer.custom.DataWriter;
+import org.opendaylight.controller.netconf.cli.writer.impl.NormalizedNodeWriter;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+/**
+ * Keeps custom and generic input/output arguments handlers. Custom handlers are
+ * constructed lazily, due to remote schema context acquisition.
+ */
+public class CommandArgHandlerRegistry {
+
+    private final ConsoleIO consoleIO;
+    private final SchemaContextRegistry schemaContextRegistry;
+
+    private final Map<Class<? extends Reader<? extends DataSchemaNode>>, ReaderProvider> customReaders = Maps
+            .newHashMap();
+    private final Map<Class<? extends Writer<DataSchemaNode>>, WriterProvider> customWriters = Maps.newHashMap();
+
+    public CommandArgHandlerRegistry(final ConsoleIO consoleIO, final SchemaContextRegistry schemaContextRegistry) {
+        this.consoleIO = consoleIO;
+        this.schemaContextRegistry = schemaContextRegistry;
+
+        setUpReaders();
+        setUpWriters();
+    }
+
+    private void setUpWriters() {
+        customWriters.put(DataWriter.class, new DataWriterProvider());
+    }
+
+    private void setUpReaders() {
+        customReaders.put(PasswordReader.class, new PasswordReaderProvider());
+        customReaders.put(FilterReader.class, new FilterReaderProvider());
+        customReaders.put(ConfigReader.class, new ConfigReaderProvider());
+        customReaders.put(EditContentReader.class, new EditContentReaderProvider());
+    }
+
+    public synchronized Reader<? extends DataSchemaNode> getCustomReader(
+            final Class<? extends Reader<DataSchemaNode>> readerType) {
+        return customReaders.get(readerType).provide(consoleIO, this, schemaContextRegistry);
+    }
+
+    private static SchemaContext getRemoteSchema(final Class<?> handlerType,
+            final SchemaContextRegistry schemaContextRegistry) {
+        final Optional<SchemaContext> remoteSchemaContext = schemaContextRegistry.getRemoteSchemaContext();
+        Preconditions.checkState(remoteSchemaContext.isPresent(),
+                "Remote schema context not acquired yet, cannot get handler %s", handlerType);
+        return remoteSchemaContext.get();
+    }
+
+    public synchronized Reader<DataSchemaNode> getGenericReader(final SchemaContext schemaContext) {
+        return new GenericReader(consoleIO, this, schemaContext);
+    }
+
+    public synchronized Reader<DataSchemaNode> getGenericReader(final SchemaContext schemaContext,
+            final boolean readConfigNode) {
+        return new GenericReader(consoleIO, this, schemaContext, readConfigNode);
+    }
+
+    public synchronized Writer<DataSchemaNode> getCustomWriter(final Class<? extends Writer<DataSchemaNode>> writerType) {
+        return customWriters.get(writerType).provide(consoleIO, getRemoteSchema(writerType, schemaContextRegistry),
+                this);
+    }
+
+    public synchronized Writer<DataSchemaNode> getGenericWriter() {
+        return new NormalizedNodeWriter(consoleIO, new OutFormatter());
+    }
+
+    /**
+     * Reader providers, in order to construct readers lazily
+     */
+    private static interface ReaderProvider {
+        Reader<? extends DataSchemaNode> provide(ConsoleIO consoleIO,
+                final CommandArgHandlerRegistry commandArgHandlerRegistry,
+                final SchemaContextRegistry schemaContextRegistry);
+    }
+
+    private static final class FilterReaderProvider implements ReaderProvider {
+        @Override
+        public Reader<? extends DataSchemaNode> provide(final ConsoleIO consoleIO,
+                final CommandArgHandlerRegistry commandArgHandlerRegistry,
+                final SchemaContextRegistry schemaContextRegistry) {
+            return new FilterReader(consoleIO, getRemoteSchema(FilterReader.class, schemaContextRegistry));
+        }
+    }
+
+    private static final class ConfigReaderProvider implements ReaderProvider {
+        @Override
+        public Reader<? extends DataSchemaNode> provide(final ConsoleIO consoleIO,
+                final CommandArgHandlerRegistry commandArgHandlerRegistry,
+                final SchemaContextRegistry schemaContextRegistry) {
+            return new ConfigReader(consoleIO, getRemoteSchema(ConfigReader.class, schemaContextRegistry),
+                    commandArgHandlerRegistry);
+        }
+    }
+
+    private static final class EditContentReaderProvider implements ReaderProvider {
+        @Override
+        public Reader<? extends DataSchemaNode> provide(final ConsoleIO consoleIO,
+                final CommandArgHandlerRegistry commandArgHandlerRegistry,
+                final SchemaContextRegistry schemaContextRegistry) {
+            return new EditContentReader(consoleIO, commandArgHandlerRegistry, getRemoteSchema(EditContentReader.class,
+                    schemaContextRegistry));
+        }
+    }
+
+    private static final class PasswordReaderProvider implements ReaderProvider {
+        @Override
+        public Reader<? extends DataSchemaNode> provide(final ConsoleIO consoleIO,
+                final CommandArgHandlerRegistry commandArgHandlerRegistry,
+                final SchemaContextRegistry schemaContextRegistry) {
+            return new PasswordReader(consoleIO, schemaContextRegistry.getLocalSchemaContext());
+        }
+    }
+
+    /**
+     * Writer providers, in order to construct readers lazily
+     */
+    private static interface WriterProvider {
+        Writer<DataSchemaNode> provide(ConsoleIO consoleIO, SchemaContext schema,
+                final CommandArgHandlerRegistry commandArgHandlerRegistry);
+    }
+
+    private class DataWriterProvider implements WriterProvider {
+        @Override
+        public Writer<DataSchemaNode> provide(final ConsoleIO consoleIO, final SchemaContext schema,
+                final CommandArgHandlerRegistry commandArgHandlerRegistry) {
+            return new DataWriter(consoleIO, new OutFormatter(), schema);
+        }
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/Main.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/Main.java
new file mode 100644 (file)
index 0000000..8605501
--- /dev/null
@@ -0,0 +1,231 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli;
+
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.UnknownHostException;
+import net.sourceforge.argparse4j.ArgumentParsers;
+import net.sourceforge.argparse4j.inf.ArgumentGroup;
+import net.sourceforge.argparse4j.inf.ArgumentParser;
+import net.sourceforge.argparse4j.inf.ArgumentParserException;
+import net.sourceforge.argparse4j.inf.Namespace;
+import org.opendaylight.controller.netconf.cli.commands.CommandDispatcher;
+import org.opendaylight.controller.netconf.cli.commands.local.Connect;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIOImpl;
+import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
+import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
+import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+/**
+ * Parse arguments, start remote device connection and start CLI after the
+ * connection is fully up
+ */
+public class Main {
+
+    public static void main(final String[] args) {
+        final CliArgumentParser cliArgs = new CliArgumentParser();
+        try {
+            cliArgs.parse(args);
+        } catch (final ArgumentParserException e) {
+            // Just end the cli, exception was handled by the CliArgumentParser
+            return;
+        }
+
+        final ConsoleIO consoleIO;
+        try {
+            consoleIO = new ConsoleIOImpl();
+        } catch (final IOException e) {
+            handleStartupException(e);
+            return;
+        }
+
+        final SchemaContext localSchema = CommandDispatcher.parseSchema(CommandDispatcher.LOCAL_SCHEMA_PATHS);
+        final SchemaContextRegistry schemaContextRegistry = new SchemaContextRegistry(localSchema);
+
+        final CommandDispatcher commandDispatcher = new CommandDispatcher();
+        final CommandArgHandlerRegistry argumentHandlerRegistry = new CommandArgHandlerRegistry(consoleIO,
+                schemaContextRegistry);
+        final NetconfDeviceConnectionManager connectionManager = new NetconfDeviceConnectionManager(commandDispatcher,
+                argumentHandlerRegistry, schemaContextRegistry, consoleIO);
+
+        commandDispatcher.addLocalCommands(connectionManager, localSchema, cliArgs.getConnectionTimeoutMs());
+
+        switch (cliArgs.connectionArgsPresent()) {
+        case TCP: {
+            // FIXME support pure TCP
+            handleRunningException(new UnsupportedOperationException("PURE TCP CONNECTIONS ARE NOT SUPPORTED YET, USE SSH INSTEAD BY PROVIDING USERNAME AND PASSWORD AS WELL"));
+            return;
+        }
+        case SSH: {
+            writeStatus(consoleIO, "Connecting to %s via SSH. Please wait.", cliArgs.getAddress());
+            connectionManager.connectBlocking(cliArgs.getAddress(), getClientSshConfig(cliArgs));
+            break;
+        }
+        case NONE: {/* Do not connect initially */
+            writeStatus(consoleIO, "No initial connection. To connect use the connect command");
+        }
+        }
+
+        try {
+            new Cli(consoleIO, commandDispatcher, argumentHandlerRegistry, schemaContextRegistry).run();
+        } catch (final Exception e) {
+            // TODO Running exceptions have to be handled properly
+            handleRunningException(e);
+            System.exit(0);
+        }
+    }
+
+    private static NetconfClientConfigurationBuilder getClientConfig(final CliArgumentParser cliArgs) {
+        return NetconfClientConfigurationBuilder.create().withAddress(cliArgs.getServerAddress())
+                .withConnectionTimeoutMillis(cliArgs.getConnectionTimeoutMs())
+                .withReconnectStrategy(Connect.getReconnectStrategy())
+                .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.TCP);
+    }
+
+    private static NetconfClientConfigurationBuilder getClientSshConfig(final CliArgumentParser cliArgs) {
+        return NetconfClientConfigurationBuilder.create().withAddress(cliArgs.getServerAddress())
+                .withConnectionTimeoutMillis(cliArgs.getConnectionTimeoutMs())
+                .withReconnectStrategy(Connect.getReconnectStrategy())
+                .withAuthHandler(cliArgs.getCredentials())
+                .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH);
+    }
+
+    private static void handleStartupException(final IOException e) {
+        handleException(e, "Unable to initialize CLI");
+    }
+
+    private static void handleException(final Exception e, final String message) {
+        System.err.println(message);
+        e.printStackTrace(System.err);
+    }
+
+    private static void writeStatus(final ConsoleIO io, final String blueprint, final Object... args) {
+        try {
+            io.formatLn(blueprint, args);
+        } catch (final IOException e) {
+            handleStartupException(e);
+        }
+    }
+
+    private static void handleRunningException(final Exception e) {
+        handleException(e, "Unexpected CLI runtime exception");
+    }
+
+    private static final class CliArgumentParser {
+
+        public static final String USERNAME = "username";
+        public static final String PASSWORD = "password";
+        public static final String SERVER = "server";
+        public static final String PORT = "port";
+
+        public static final String CONNECT_TIMEOUT = "connectionTimeout";
+        public static final int DEFAULT_CONNECTION_TIMEOUT_MS = 50000;
+
+        private final ArgumentParser parser;
+        private Namespace parsed;
+
+        private CliArgumentParser() {
+            parser = ArgumentParsers.newArgumentParser("Netconf cli").defaultHelp(true)
+                    .description("Generic cli for netconf devices")
+                    .usage("Submit address + port for initial TCP connection (PURE TCP CONNECTIONS ARE NOT SUPPORTED YET)\n" +
+                            "Submit username + password in addition to address + port for initial SSH connection\n" +
+                            "If no arguments(or unexpected combination) is submitted, cli will be started without initial connection\n" +
+                            "To use with ODL controller, run with: java -jar netconf-cli-0.2.5-SNAPSHOT-executable.jar  --server localhost --port 1830 --username admin --password admin");
+
+            final ArgumentGroup tcpGroup = parser.addArgumentGroup("TCP")
+                    .description("Base arguments to initiate TCP connection right away");
+
+            tcpGroup.addArgument("--" + SERVER).help("Netconf device ip-address/domain name");
+            tcpGroup.addArgument("--" + PORT).type(Integer.class).help("Netconf device port");
+            tcpGroup.addArgument("--" + CONNECT_TIMEOUT)
+                    .type(Integer.class)
+                    .setDefault(DEFAULT_CONNECTION_TIMEOUT_MS)
+                    .help("Timeout(in ms) for connection to succeed, if the connection is not fully established by the time is up, " +
+                            "connection attempt is considered a failure. This attribute is not working as expected yet");
+
+            final ArgumentGroup sshGroup = parser.addArgumentGroup("SSH")
+                    .description("SSH credentials, if provided, initial connection will be attempted using SSH");
+
+            sshGroup.addArgument("--" + USERNAME).help("Username for SSH connection");
+            sshGroup.addArgument("--" + PASSWORD).help("Password for SSH connection");
+        }
+
+        public void parse(final String[] args) throws ArgumentParserException {
+            try {
+                this.parsed = parser.parseArgs(args);
+            } catch (final ArgumentParserException e) {
+                parser.handleError(e);
+                throw e;
+            }
+        }
+
+        public InetSocketAddress getServerAddress() {
+            try {
+                return new InetSocketAddress(InetAddress.getByName(getAddress()), getPort());
+            } catch (final UnknownHostException e) {
+                throw new IllegalArgumentException(e);
+            }
+        }
+
+        private Integer getPort() {
+            checkParsed();
+            return parsed.getInt(PORT);
+        }
+
+        private String getAddress() {
+            checkParsed();
+            return getString(SERVER);
+        }
+
+        private Integer getConnectionTimeoutMs() {
+            checkParsed();
+            return parsed.getInt(CONNECT_TIMEOUT);
+        }
+
+        private void checkParsed() {
+            Preconditions.checkState(parsed != null, "No arguments were parsed yet");
+        }
+
+        public String getUsername() {
+            checkParsed();
+            return getString(USERNAME);
+        }
+
+        private String getString(final String key) {
+            return parsed.getString(key);
+        }
+
+        public LoginPassword getCredentials() {
+            return new LoginPassword(getUsername(), getPassword());
+        }
+
+        public String getPassword() {
+            checkParsed();
+            return getString(PASSWORD);
+        }
+
+        public InitialConnectionType connectionArgsPresent() {
+            if(getAddress() != null && getPort() != null) {
+                if(getUsername() != null && getPassword() != null) {
+                    return InitialConnectionType.SSH;
+                }
+                return InitialConnectionType.TCP;
+            }
+            return InitialConnectionType.NONE;
+        }
+
+        enum InitialConnectionType {
+            TCP, SSH, NONE
+        }
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/NetconfDeviceConnectionHandler.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/NetconfDeviceConnectionHandler.java
new file mode 100644 (file)
index 0000000..bd092bc
--- /dev/null
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli;
+
+import com.google.common.base.Optional;
+import jline.console.completer.Completer;
+import jline.console.completer.NullCompleter;
+import org.opendaylight.controller.netconf.cli.commands.CommandDispatcher;
+import org.opendaylight.controller.netconf.cli.io.ConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.sal.connect.api.RemoteDeviceHandler;
+import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionCapabilities;
+import org.opendaylight.controller.sal.core.api.RpcImplementation;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
+
+/**
+ * Implementation of RemoteDeviceHandler. Integrates cli with
+ * sal-netconf-connector.
+ */
+public class NetconfDeviceConnectionHandler implements RemoteDeviceHandler<NetconfSessionCapabilities> {
+
+    private final CommandDispatcher commandDispatcher;
+    private final SchemaContextRegistry schemaContextRegistry;
+    private final ConsoleIO console;
+    private final String deviceId;
+
+    private boolean up = false;
+
+    public NetconfDeviceConnectionHandler(final CommandDispatcher commandDispatcher,
+            final SchemaContextRegistry schemaContextRegistry, final ConsoleIO console, final String deviceId) {
+        this.commandDispatcher = commandDispatcher;
+        this.schemaContextRegistry = schemaContextRegistry;
+        this.console = console;
+        this.deviceId = deviceId;
+    }
+
+    @Override
+    public synchronized void onDeviceConnected(final SchemaContextProvider contextProvider,
+            final NetconfSessionCapabilities capabilities, final RpcImplementation rpcImplementation) {
+        console.enterRootContext(new ConsoleContext() {
+
+            @Override
+            public Optional<String> getPrompt() {
+                return Optional.of(deviceId);
+            }
+
+            @Override
+            public Completer getCompleter() {
+                return new NullCompleter();
+            }
+        });
+
+        // TODO Load schemas for base netconf + inet types from remote device if
+        // possible
+        // TODO detect netconf base version
+        // TODO detect inet types version
+        commandDispatcher.addRemoteCommands(rpcImplementation, contextProvider.getSchemaContext());
+        schemaContextRegistry.setRemoteSchemaContext(contextProvider.getSchemaContext());
+        up = true;
+        this.notify();
+    }
+
+    /**
+     * @return true if connection was fully established
+     */
+    public synchronized boolean isUp() {
+        return up;
+    }
+
+    @Override
+    public synchronized void onDeviceDisconnected() {
+        console.leaveRootContext();
+        commandDispatcher.removeRemoteCommands();
+        schemaContextRegistry.setRemoteSchemaContext(null);
+        up = false;
+    }
+
+    @Override
+    public void onNotification(final CompositeNode compositeNode) {
+        // FIXME
+    }
+
+    @Override
+    public void close() {
+        // FIXME
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/NetconfDeviceConnectionManager.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/NetconfDeviceConnectionManager.java
new file mode 100644 (file)
index 0000000..3dd892e
--- /dev/null
@@ -0,0 +1,122 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli;
+
+import com.google.common.base.Preconditions;
+import io.netty.channel.nio.NioEventLoopGroup;
+import io.netty.util.HashedWheelTimer;
+import java.io.Closeable;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Set;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import org.opendaylight.controller.netconf.cli.commands.CommandDispatcher;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
+import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
+import org.opendaylight.controller.sal.connect.netconf.NetconfDevice;
+import org.opendaylight.controller.sal.connect.netconf.listener.NetconfDeviceCommunicator;
+import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
+import org.opendaylight.yangtools.yang.model.util.repo.AbstractCachingSchemaSourceProvider;
+import org.opendaylight.yangtools.yang.model.util.repo.FilesystemSchemaCachingProvider;
+import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProvider;
+import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProviders;
+
+/**
+ * Manages connect/disconnect to 1 remote device
+ */
+public class NetconfDeviceConnectionManager implements Closeable {
+
+    private final CommandDispatcher commandDispatcher;
+    private final SchemaContextRegistry schemaContextRegistry;
+    private final ConsoleIO console;
+
+    private final ExecutorService executor;
+    private final NioEventLoopGroup nettyThreadGroup;
+    private final NetconfClientDispatcherImpl netconfClientDispatcher;
+
+    // Connection
+    private NetconfDeviceConnectionHandler handler;
+    private NetconfDevice device;
+    private NetconfDeviceCommunicator listener;
+
+    public NetconfDeviceConnectionManager(final CommandDispatcher commandDispatcher,
+            final CommandArgHandlerRegistry argumentHandlerRegistry, final SchemaContextRegistry schemaContextRegistry,
+            final ConsoleIO consoleIO) {
+        this.commandDispatcher = commandDispatcher;
+        this.schemaContextRegistry = schemaContextRegistry;
+        this.console = consoleIO;
+
+        executor = Executors.newSingleThreadExecutor();
+        nettyThreadGroup = new NioEventLoopGroup();
+        netconfClientDispatcher = new NetconfClientDispatcherImpl(nettyThreadGroup, nettyThreadGroup,
+                new HashedWheelTimer());
+    }
+
+    // TODO we receive configBuilder in order to add SessionListener, Session
+    // Listener should not be part of config
+    public synchronized void connect(final String name, final NetconfClientConfigurationBuilder configBuilder) {
+        // TODO change IllegalState exceptions to custom ConnectionException
+        Preconditions.checkState(listener == null, "Already connected");
+
+        final RemoteDeviceId deviceId = new RemoteDeviceId(name);
+
+        handler = new NetconfDeviceConnectionHandler(commandDispatcher, schemaContextRegistry,
+                console, name);
+        device = NetconfDevice.createNetconfDevice(deviceId, getGlobalNetconfSchemaProvider(), executor, handler);
+        listener = new NetconfDeviceCommunicator(deviceId, device);
+        configBuilder.withSessionListener(listener);
+        listener.initializeRemoteConnection(netconfClientDispatcher, configBuilder.build());
+    }
+
+    /**
+     * Blocks thread until connection is fully established
+     */
+    public synchronized Set<String> connectBlocking(final String name, final NetconfClientConfigurationBuilder configBuilder) {
+        this.connect(name, configBuilder);
+        synchronized (handler) {
+            while (handler.isUp() == false) {
+                try {
+                    // TODO implement Timeout for unsuccessful connection
+                    handler.wait();
+                } catch (final InterruptedException e) {
+                    Thread.currentThread().interrupt();
+                    throw new IllegalArgumentException(e);
+                }
+            }
+        }
+
+        return commandDispatcher.getRemoteCommandIds();
+    }
+
+    public synchronized void disconnect() {
+        Preconditions.checkState(listener != null, "Not connected yet");
+        Preconditions.checkState(handler.isUp(), "Not connected yet");
+        listener.close();
+        listener = null;
+        device = null;
+        handler.close();
+        handler = null;
+    }
+
+    private static AbstractCachingSchemaSourceProvider<String, InputStream> getGlobalNetconfSchemaProvider() {
+        // FIXME move to args
+        final String storageFile = "cache/schema";
+        final File directory = new File(storageFile);
+        final SchemaSourceProvider<String> defaultProvider = SchemaSourceProviders.noopProvider();
+        return FilesystemSchemaCachingProvider.createFromStringSourceProvider(defaultProvider, directory);
+    }
+
+    @Override
+    public void close() throws IOException {
+        executor.shutdownNow();
+        nettyThreadGroup.shutdownGracefully();
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/SchemaContextRegistry.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/SchemaContextRegistry.java
new file mode 100644 (file)
index 0000000..5c3cfe7
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli;
+
+import com.google.common.base.Optional;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+/**
+ * Contains the local schema context (containing local commands) and remote schema context (remote commands)
+ *
+ * Remote commands are set only after the connection is fully established. So classes using the remote schema context
+ */
+public class SchemaContextRegistry {
+
+    private final SchemaContext localSchemaContext;
+    private SchemaContext remoteSchemaContext;
+
+    public SchemaContextRegistry(final SchemaContext localSchemaContext) {
+        this.localSchemaContext = localSchemaContext;
+    }
+
+    public synchronized Optional<SchemaContext> getRemoteSchemaContext() {
+        return Optional.fromNullable(remoteSchemaContext);
+    }
+
+    public SchemaContext getLocalSchemaContext() {
+        return localSchemaContext;
+    }
+
+    public synchronized void setRemoteSchemaContext(final SchemaContext remoteSchemaContext) {
+        this.remoteSchemaContext = remoteSchemaContext;
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/AbstractCommand.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/AbstractCommand.java
new file mode 100644 (file)
index 0000000..f02ce74
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.commands;
+
+import com.google.common.base.Optional;
+import jline.console.completer.Completer;
+import jline.console.completer.NullCompleter;
+import org.opendaylight.controller.netconf.cli.commands.input.InputDefinition;
+import org.opendaylight.controller.netconf.cli.commands.output.OutputDefinition;
+import org.opendaylight.controller.netconf.cli.io.ConsoleContext;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
+
+public abstract class AbstractCommand implements Command {
+
+    private final QName qName;
+    private final InputDefinition args;
+    private final OutputDefinition output;
+    private final String description;
+
+    public AbstractCommand(final QName qName, final InputDefinition args, final OutputDefinition output,
+            final String description) {
+        this.qName = qName;
+        this.args = args;
+        this.output = output;
+        this.description = description;
+    }
+
+    protected static OutputDefinition getOutputDefinition(final RpcDefinition rpcDefinition) {
+        final ContainerSchemaNode output = rpcDefinition.getOutput();
+        return output != null ? OutputDefinition.fromOutput(output) : OutputDefinition.empty();
+    }
+
+    protected static InputDefinition getInputDefinition(final RpcDefinition rpcDefinition) {
+        final ContainerSchemaNode input = rpcDefinition.getInput();
+        return InputDefinition.fromInput(input);
+    }
+
+    @Override
+    public InputDefinition getInputDefinition() {
+        return args;
+    }
+
+    @Override
+    public OutputDefinition getOutputDefinition() {
+        return output;
+    }
+
+    @Override
+    public QName getCommandId() {
+        return qName;
+    }
+
+    @Override
+    public ConsoleContext getConsoleContext() {
+        return new ConsoleContext() {
+
+            @Override
+            public Completer getCompleter() {
+                return new NullCompleter();
+            }
+
+            @Override
+            public Optional<String> getPrompt() {
+                return Optional.of(qName.getLocalName());
+            }
+        };
+    }
+
+    @Override
+    public Optional<String> getCommandDescription() {
+        return Optional.fromNullable(description);
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/Command.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/Command.java
new file mode 100644 (file)
index 0000000..1435abd
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.commands;
+
+import com.google.common.base.Optional;
+import org.opendaylight.controller.netconf.cli.commands.input.Input;
+import org.opendaylight.controller.netconf.cli.commands.input.InputDefinition;
+import org.opendaylight.controller.netconf.cli.commands.output.Output;
+import org.opendaylight.controller.netconf.cli.commands.output.OutputDefinition;
+import org.opendaylight.controller.netconf.cli.io.ConsoleContext;
+import org.opendaylight.yangtools.yang.common.QName;
+
+/**
+ * Local command e.g. help or remote rpc e.g. get-config must conform to this interface
+ */
+public interface Command {
+
+    Output invoke(Input inputArgs) throws CommandInvocationException;
+
+    InputDefinition getInputDefinition();
+
+    OutputDefinition getOutputDefinition();
+
+    QName getCommandId();
+
+    Optional<String> getCommandDescription();
+
+    ConsoleContext getConsoleContext();
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/CommandConstants.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/CommandConstants.java
new file mode 100644 (file)
index 0000000..7159af5
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.commands;
+
+import java.net.URI;
+import org.opendaylight.controller.netconf.cli.io.IOUtil;
+import org.opendaylight.yangtools.yang.common.QName;
+
+public class CommandConstants {
+
+    // Local command ids are defined here, this links the implementation to the rpc definition in yang
+    // Better way needs to be found to provide this link instead of hardcoded QNames (e.g. yang extension)
+    public static final QName HELP_QNAME = QName.create(URI.create("netconf:cli"), IOUtil.parseDate("2014-05-22"), "help");
+    public static final QName CLOSE_QNAME = QName.create(HELP_QNAME, "close");
+    public static final QName CONNECT_QNAME = QName.create(HELP_QNAME, "connect");
+    public static final QName DISCONNECT_QNAME = QName.create(CONNECT_QNAME, "disconnect");
+
+    public static final QName ARG_HANDLER_EXT_QNAME = QName.create(
+            URI.create("urn:ietf:params:xml:ns:netconf:base:1.0:cli"), IOUtil.parseDate("2014-05-26"),
+            "argument-handler");
+
+    public static final QName NETCONF_BASE_QNAME = QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01",
+            "netconf");
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/CommandDispatcher.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/CommandDispatcher.java
new file mode 100644 (file)
index 0000000..ec7b5b4
--- /dev/null
@@ -0,0 +1,183 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.commands;
+
+import com.google.common.base.Function;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Collections2;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import java.io.InputStream;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.opendaylight.controller.netconf.cli.NetconfDeviceConnectionHandler;
+import org.opendaylight.controller.netconf.cli.NetconfDeviceConnectionManager;
+import org.opendaylight.controller.netconf.cli.commands.local.Close;
+import org.opendaylight.controller.netconf.cli.commands.local.Connect;
+import org.opendaylight.controller.netconf.cli.commands.local.Disconnect;
+import org.opendaylight.controller.netconf.cli.commands.local.Help;
+import org.opendaylight.controller.netconf.cli.commands.remote.RemoteCommand;
+import org.opendaylight.controller.netconf.cli.io.IOUtil;
+import org.opendaylight.controller.sal.core.api.RpcImplementation;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
+
+/**
+ * The registry of available commands local + remote. Created from schema contexts.
+ */
+public class CommandDispatcher {
+
+    // TODO extract interface
+
+    private final Map<QName, Command> localCommands = Maps.newHashMap();
+    private final Map<String, QName> nameToQNameLocal = Maps.newHashMap();
+
+    private final Map<QName, Command> remoteCommands = Maps.newHashMap();
+    private final Map<String, QName> nameToQNameRemote = Maps.newHashMap();
+
+    public synchronized Map<QName, Command> getCommands() {
+        return Collections.unmodifiableMap(mergeCommands());
+    }
+
+    private Map<QName, Command> mergeCommands() {
+        // TODO cache this merged map
+        return mergeMaps(remoteCommands, localCommands);
+    }
+
+    private Map<String, QName> mergeCommandIds() {
+        // TODO cache this merged map
+        return mergeMaps(nameToQNameRemote, nameToQNameLocal);
+    }
+
+    private <K, V> Map<K, V> mergeMaps(final Map<K, V> remoteMap, final Map<K, V> localMap) {
+        final Map<K, V> mergedCommands = Maps.newHashMap();
+        mergedCommands.putAll(remoteMap);
+        mergedCommands.putAll(localMap);
+        return mergedCommands;
+    }
+
+    public synchronized Set<String> getCommandIds() {
+        return mergeCommandIds().keySet();
+    }
+
+    public synchronized Set<String> getRemoteCommandIds() {
+        return nameToQNameRemote.keySet();
+    }
+
+    public synchronized Optional<Command> getCommand(final String nameWithModule) {
+        final QName commandQName = mergeCommandIds().get(nameWithModule);
+        final Map<QName, Command> qNameCommandMap = mergeCommands();
+        if(commandQName == null || qNameCommandMap.containsKey(commandQName) == false) {
+            return Optional.absent();
+        }
+
+        return Optional.of(qNameCommandMap.get(commandQName));
+    }
+
+    public synchronized Optional<Command> getCommand(final QName qName) {
+        return Optional.fromNullable(mergeCommands().get(qName));
+    }
+
+    private static Optional<Command> getCommand(final Map<String, QName> commandNameMap, final Map<QName, Command> commands, final String nameWithModule) {
+        final QName qName = commandNameMap.get(nameWithModule);
+        if(qName == null)
+            return Optional.absent();
+
+        final Command command = commands.get(qName);
+        if(command == null) {
+            return Optional.absent();
+        }
+
+        return Optional.of(command);
+    }
+
+    public static final Collection<String> BASE_NETCONF_SCHEMA_PATHS = Lists.newArrayList("/schema/remote/ietf-netconf.yang",
+            "/schema/common/netconf-cli-ext.yang", "/schema/common/ietf-inet-types.yang");
+
+    public synchronized void addRemoteCommands(final RpcImplementation rpcInvoker, final SchemaContext remoteSchema) {
+        this.addRemoteCommands(rpcInvoker, remoteSchema, parseSchema(BASE_NETCONF_SCHEMA_PATHS));
+    }
+
+    public synchronized void addRemoteCommands(final RpcImplementation rpcInvoker, final SchemaContext remoteSchema, final SchemaContext baseNetconfSchema) {
+        for (final SchemaContext context : Lists.newArrayList(remoteSchema, baseNetconfSchema)) {
+            for (final Module module : context.getModules()) {
+                for (final RpcDefinition rpcDefinition : module.getRpcs()) {
+                    final Command command = RemoteCommand.fromRpc(rpcDefinition, rpcInvoker);
+                    remoteCommands.put(rpcDefinition.getQName(), command);
+                    nameToQNameRemote.put(getCommandName(rpcDefinition, module), rpcDefinition.getQName());
+                }
+            }
+        }
+    }
+
+    public synchronized void removeRemoteCommands() {
+        remoteCommands.clear();
+        nameToQNameRemote.clear();
+    }
+
+    public static final Collection<String> LOCAL_SCHEMA_PATHS = Lists.newArrayList("/schema/local/netconf-cli.yang", "/schema/common/netconf-cli-ext.yang",
+            "/schema/common/ietf-inet-types.yang");
+
+    public synchronized void addLocalCommands(final NetconfDeviceConnectionManager connectionManager, final SchemaContext localSchema, final Integer connectionTimeout) {
+        for (final Module module : localSchema.getModules()) {
+            for (final RpcDefinition rpcDefinition : module.getRpcs()) {
+
+                // FIXME make local commands extensible
+                // e.g. by yang extension defining java class to be instantiated
+                // problem is with command specific resources
+                // e.g. Help would need command registry
+                final Command localCommand;
+                if (rpcDefinition.getQName().equals(CommandConstants.HELP_QNAME)) {
+                    localCommand = Help.create(rpcDefinition, this);
+                } else if (rpcDefinition.getQName().equals(CommandConstants.CLOSE_QNAME)) {
+                    localCommand = Close.create(rpcDefinition);
+                } else if (rpcDefinition.getQName().equals(CommandConstants.CONNECT_QNAME)) {
+                    localCommand = Connect.create(rpcDefinition, connectionManager, connectionTimeout);
+                } else if (rpcDefinition.getQName().equals(CommandConstants.DISCONNECT_QNAME)) {
+                    localCommand = Disconnect.create(rpcDefinition, connectionManager);
+                } else {
+                    throw new IllegalStateException("No command implementation available for local command: " + rpcDefinition.getQName());
+                }
+
+                localCommands.put(localCommand.getCommandId(), localCommand);
+                nameToQNameLocal.put(getCommandName(rpcDefinition, module), localCommand.getCommandId());
+            }
+        }
+    }
+
+    private static String getCommandName(final RpcDefinition rpcDefinition, final Module module) {
+        return IOUtil.qNameToKeyString(rpcDefinition.getQName(), module.getName());
+    }
+
+    public static SchemaContext parseSchema(final Collection<String> yangPath) {
+        final YangParserImpl yangParserImpl = new YangParserImpl();
+        // TODO change deprecated method
+        final Set<Module> modules = yangParserImpl.parseYangModelsFromStreams(loadYangs(yangPath));
+        return yangParserImpl.resolveSchemaContext(modules);
+    }
+
+    private static List<InputStream> loadYangs(final Collection<String> yangPaths) {
+
+        return Lists.newArrayList(Collections2.transform(Lists.newArrayList(yangPaths),
+                new Function<String, InputStream>() {
+                    @Override
+                    public InputStream apply(final String input) {
+                        final InputStream resourceAsStream = NetconfDeviceConnectionHandler.class.getResourceAsStream(input);
+                        Preconditions.checkNotNull(resourceAsStream, "File %s was null", input);
+                        return resourceAsStream;
+                    }
+                }));
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/CommandInvocationException.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/CommandInvocationException.java
new file mode 100644 (file)
index 0000000..e38f45f
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.commands;
+
+import org.opendaylight.yangtools.yang.common.QName;
+
+public class CommandInvocationException extends Exception {
+
+    public CommandInvocationException(final QName qName, final Throwable cause) {
+        this("Command " + qName + " invocation failed: " + cause.getMessage(), cause);
+    }
+
+    protected CommandInvocationException(final String message, final Throwable cause) {
+        super(message, cause);
+    }
+
+    public static class CommandTimeoutException extends CommandInvocationException {
+
+        public CommandTimeoutException(final QName qName, final Throwable e) {
+            super("Command " + qName + " timed out: " + e.getMessage(), e);
+        }
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/input/Input.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/input/Input.java
new file mode 100644 (file)
index 0000000..02173ac
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.commands.input;
+
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
+
+/**
+ * Input arguments for and rpc/command execution
+ */
+public class Input {
+
+    private final List<Node<?>> args;
+
+    private final Map<String, Node<?>> nameToArg = new HashMap<String, Node<?>>();
+
+    public Input(final List<Node<?>> args) {
+        // FIXME empty Input should be constructed from static factory method
+        if(args.isEmpty()) {
+            this.args = Collections.emptyList();
+            return;
+        }
+
+        final Node<?> input = args.iterator().next();
+        Preconditions
+                .checkArgument(input instanceof CompositeNode, "Input container has to be of type composite node.");
+        this.args = ((CompositeNode) input).getValue();
+
+        for (final Node<?> arg : this.args) {
+            nameToArg.put(arg.getNodeType().getLocalName(), arg);
+        }
+    }
+
+    public Node<?> getArg(final String name) {
+        return nameToArg.get(name);
+    }
+
+    public CompositeNode wrap(final QName rpcQName) {
+        return new CompositeNodeTOImpl(rpcQName, null, args);
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/input/InputDefinition.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/input/InputDefinition.java
new file mode 100644 (file)
index 0000000..83e1b19
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.commands.input;
+
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+
+/**
+ * The definition of input arguments represented by schema nodes parsed from
+ * yang rpc definition
+ */
+public class InputDefinition {
+
+    private final ContainerSchemaNode inputContainer;
+
+    public InputDefinition(final ContainerSchemaNode inputContainer) {
+        this.inputContainer = inputContainer;
+    }
+
+    public static InputDefinition fromInput(final ContainerSchemaNode input) {
+        return new InputDefinition(input);
+    }
+
+    public ContainerSchemaNode getInput() {
+        return inputContainer;
+    }
+
+    // FIXME add empty as in output
+    public boolean isEmpty() {
+        return inputContainer == null;
+    }
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/local/Close.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/local/Close.java
new file mode 100644 (file)
index 0000000..c43432d
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.commands.local;
+
+import org.opendaylight.controller.netconf.cli.commands.AbstractCommand;
+import org.opendaylight.controller.netconf.cli.commands.Command;
+import org.opendaylight.controller.netconf.cli.commands.CommandInvocationException;
+import org.opendaylight.controller.netconf.cli.commands.input.Input;
+import org.opendaylight.controller.netconf.cli.commands.input.InputDefinition;
+import org.opendaylight.controller.netconf.cli.commands.output.Output;
+import org.opendaylight.controller.netconf.cli.commands.output.OutputDefinition;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
+
+/**
+ * Local command to shut down the cli
+ */
+public class Close extends AbstractCommand {
+
+    public Close(final QName qName, final InputDefinition args, final OutputDefinition output, final String description) {
+        super(qName, args, output, description);
+    }
+
+    @Override
+    public Output invoke(final Input inputArgs) throws CommandInvocationException {
+        // FIXME clean up, close session and then close
+        System.exit(0);
+        return null;
+    }
+
+    public static Command create(final RpcDefinition rpcDefinition) {
+        return new Close(rpcDefinition.getQName(), getInputDefinition(rpcDefinition),
+                getOutputDefinition(rpcDefinition), rpcDefinition.getDescription());
+    }
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/local/Connect.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/local/Connect.java
new file mode 100644 (file)
index 0000000..f702aa3
--- /dev/null
@@ -0,0 +1,125 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.commands.local;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import io.netty.util.concurrent.GlobalEventExecutor;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Set;
+import org.opendaylight.controller.netconf.cli.NetconfDeviceConnectionManager;
+import org.opendaylight.controller.netconf.cli.commands.AbstractCommand;
+import org.opendaylight.controller.netconf.cli.commands.Command;
+import org.opendaylight.controller.netconf.cli.commands.input.Input;
+import org.opendaylight.controller.netconf.cli.commands.input.InputDefinition;
+import org.opendaylight.controller.netconf.cli.commands.output.Output;
+import org.opendaylight.controller.netconf.cli.commands.output.OutputDefinition;
+import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguration;
+import org.opendaylight.controller.netconf.client.conf.NetconfClientConfigurationBuilder;
+import org.opendaylight.controller.netconf.nettyutil.handler.ssh.authentication.LoginPassword;
+import org.opendaylight.protocol.framework.NeverReconnectStrategy;
+import org.opendaylight.protocol.framework.ReconnectStrategy;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.data.api.SimpleNode;
+import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
+import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
+import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
+
+/**
+ * Local command to connect to a remote device
+ */
+public class Connect extends AbstractCommand {
+
+    private final NetconfDeviceConnectionManager connectManager;
+    private final Integer connectionTimeout;
+
+    private Connect(final QName qName, final InputDefinition args, final OutputDefinition output,
+                    final NetconfDeviceConnectionManager connectManager, final String description, final Integer connectionTimeout) {
+        super(qName, args, output, description);
+        this.connectManager = connectManager;
+        this.connectionTimeout = connectionTimeout;
+    }
+
+    @Override
+    public Output invoke(final Input inputArgs) {
+        final NetconfClientConfigurationBuilder config = getConfig(inputArgs);
+        return invoke(config, getArgument(inputArgs, "address-name", String.class));
+    }
+
+    private Output invoke(final NetconfClientConfigurationBuilder config, final String addressName) {
+        final Set<String> remoteCmds = connectManager.connectBlocking(addressName, config);
+
+        final ArrayList<Node<?>> output = Lists.newArrayList();
+        output.add(new SimpleNodeTOImpl<>(QName.create(getCommandId(), "status"), null, "Connection initiated"));
+
+        for (final String cmdId : remoteCmds) {
+            output.add(new SimpleNodeTOImpl<>(QName.create(getCommandId(), "remote-commands"), null, cmdId));
+        }
+
+        return new Output(new CompositeNodeTOImpl(getCommandId(), null, output));
+    }
+
+    private NetconfClientConfigurationBuilder getConfig(final Input inputArgs) {
+
+        final ReconnectStrategy strategy = getReconnectStrategy();
+
+        final String address = getArgument(inputArgs, "address-name", String.class);
+        final Integer port = getArgument(inputArgs, "address-port", Integer.class);
+        final String username = getArgument(inputArgs, "user-name", String.class);
+        final String passwd = getArgument(inputArgs, "user-password", String.class);
+
+        final InetSocketAddress inetAddress;
+        try {
+            inetAddress = new InetSocketAddress(InetAddress.getByName(address), port);
+        } catch (final UnknownHostException e) {
+            throw new IllegalArgumentException("Unable to use address: " + address, e);
+        }
+
+        return NetconfClientConfigurationBuilder.create().withAddress(inetAddress)
+                .withConnectionTimeoutMillis(connectionTimeout)
+                .withReconnectStrategy(strategy)
+                .withAuthHandler(new LoginPassword(username, passwd))
+                .withProtocol(NetconfClientConfiguration.NetconfClientProtocol.SSH);
+    }
+
+    private <T> Optional<T> getArgumentOpt(final Input inputArgs, final String argName, final Class<T> type) {
+        final QName argQName = QName.create(getCommandId(), argName);
+        final Node<?> argumentNode = inputArgs.getArg(argName);
+        if (argumentNode == null) {
+            return Optional.absent();
+        }
+        Preconditions.checkArgument(argumentNode instanceof SimpleNode, "Only simple type argument supported, %s",
+                argQName);
+
+        final Object value = argumentNode.getValue();
+        Preconditions.checkArgument(type.isInstance(value), "Unexpected instance type: %s for argument: %s",
+                value.getClass(), argQName);
+        return Optional.of(type.cast(value));
+    }
+
+    private <T> T getArgument(final Input inputArgs, final String argName, final Class<T> type) {
+        final Optional<T> argumentOpt = getArgumentOpt(inputArgs, argName, type);
+        Preconditions.checkState(argumentOpt.isPresent(), "Argument: %s is missing but is required", argName);
+        return argumentOpt.get();
+    }
+
+    public static ReconnectStrategy getReconnectStrategy() {
+        // FIXME move to args either start-up args or input nodes for connect or both
+        return new NeverReconnectStrategy(GlobalEventExecutor.INSTANCE, 1000);
+    }
+
+    public static Command create(final RpcDefinition rpcDefinition, final NetconfDeviceConnectionManager connectManager, final Integer connectionTimeout) {
+        return new Connect(rpcDefinition.getQName(), getInputDefinition(rpcDefinition),
+                getOutputDefinition(rpcDefinition), connectManager, rpcDefinition.getDescription(), connectionTimeout);
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/local/Disconnect.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/local/Disconnect.java
new file mode 100644 (file)
index 0000000..723e484
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.commands.local;
+
+import com.google.common.collect.Lists;
+import org.opendaylight.controller.netconf.cli.NetconfDeviceConnectionManager;
+import org.opendaylight.controller.netconf.cli.commands.AbstractCommand;
+import org.opendaylight.controller.netconf.cli.commands.Command;
+import org.opendaylight.controller.netconf.cli.commands.input.Input;
+import org.opendaylight.controller.netconf.cli.commands.input.InputDefinition;
+import org.opendaylight.controller.netconf.cli.commands.output.Output;
+import org.opendaylight.controller.netconf.cli.commands.output.OutputDefinition;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
+import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
+import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
+
+/**
+ * Local disconnect command
+ */
+public class Disconnect extends AbstractCommand {
+
+    private final NetconfDeviceConnectionManager connectionManager;
+
+    public Disconnect(final QName qName, final InputDefinition inputDefinition,
+            final OutputDefinition outputDefinition, final NetconfDeviceConnectionManager connectionManager,
+            final String description) {
+        super(qName, inputDefinition, outputDefinition, description);
+        this.connectionManager = connectionManager;
+    }
+
+    @Override
+    public Output invoke(final Input inputArgs) {
+        connectionManager.disconnect();
+
+        return new Output(new CompositeNodeTOImpl(getCommandId(), null,
+                Lists.<Node<?>> newArrayList(new SimpleNodeTOImpl<>(new QName(getCommandId(), "status"), null,
+                        "Connection disconnected"))));
+    }
+
+    public static Command create(final RpcDefinition rpcDefinition,
+            final NetconfDeviceConnectionManager commandDispatcher) {
+        return new Disconnect(rpcDefinition.getQName(), getInputDefinition(rpcDefinition),
+                getOutputDefinition(rpcDefinition), commandDispatcher, rpcDefinition.getDescription());
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/local/Help.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/local/Help.java
new file mode 100644 (file)
index 0000000..1816469
--- /dev/null
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.commands.local;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import java.util.ArrayList;
+import java.util.List;
+import org.opendaylight.controller.netconf.cli.commands.AbstractCommand;
+import org.opendaylight.controller.netconf.cli.commands.Command;
+import org.opendaylight.controller.netconf.cli.commands.CommandDispatcher;
+import org.opendaylight.controller.netconf.cli.commands.input.Input;
+import org.opendaylight.controller.netconf.cli.commands.input.InputDefinition;
+import org.opendaylight.controller.netconf.cli.commands.output.Output;
+import org.opendaylight.controller.netconf.cli.commands.output.OutputDefinition;
+import org.opendaylight.yangtools.yang.common.QName;
+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.model.api.RpcDefinition;
+
+/**
+ * Local Help command. Displays all commands with description.
+ */
+public class Help extends AbstractCommand {
+
+    private final CommandDispatcher commandDispatcher;
+
+    public Help(final QName qName, final InputDefinition argsDefinition, final OutputDefinition output, final String description, final CommandDispatcher commandDispatcher) {
+        super(qName, argsDefinition, output, description);
+        this.commandDispatcher = commandDispatcher;
+    }
+
+    @Override
+    public Output invoke(final Input inputArgs) {
+        final ArrayList<Node<?>> value = Lists.newArrayList();
+
+        for (final String id : commandDispatcher.getCommandIds()) {
+            final Optional<Command> cmd = commandDispatcher.getCommand(id);
+            Preconditions.checkState(cmd.isPresent(), "Command %s has to be present in command dispatcher", id);
+            final Optional<String> description = cmd.get().getCommandDescription();
+            final List<Node<?>> nameAndDescription = Lists.newArrayList();
+            nameAndDescription.add(NodeFactory.createImmutableSimpleNode(QName.create(getCommandId(), "id"), null, id));
+            if(description.isPresent()) {
+                nameAndDescription.add(NodeFactory.createImmutableSimpleNode(QName.create(getCommandId(), "description"), null, description.get()));
+            }
+            value.add(ImmutableCompositeNode.create(QName.create(getCommandId(), "commands"), nameAndDescription));
+        }
+
+        return new Output(new CompositeNodeTOImpl(getCommandId(), null, value));
+    }
+
+    public static Command create(final RpcDefinition rpcDefinition, final CommandDispatcher commandDispatcher) {
+        return new Help(rpcDefinition.getQName(), getInputDefinition(rpcDefinition), getOutputDefinition(rpcDefinition), rpcDefinition.getDescription(), commandDispatcher);
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/output/Output.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/output/Output.java
new file mode 100644 (file)
index 0000000..c366c89
--- /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.netconf.cli.commands.output;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import java.util.List;
+import java.util.Map;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+
+/**
+ * Output values for and rpc/command execution
+ */
+public class Output {
+
+    private final CompositeNode output;
+
+    public Output(final CompositeNode output) {
+        this.output = output;
+    }
+
+    public Map<DataSchemaNode, List<Node<?>>> unwrap(final OutputDefinition outputDefinition) {
+        Preconditions.checkArgument(outputDefinition.isEmpty() == false);
+
+        final Map<QName, DataSchemaNode> mappedSchemaNodes = mapOutput(outputDefinition);
+        final Map<DataSchemaNode, List<Node<?>>> mappedNodesToSchema = Maps.newHashMap();
+
+        for (final Node<?> node : output.getValue()) {
+            final DataSchemaNode schemaNode = mappedSchemaNodes.get(node.getKey().withoutRevision());
+            final List<Node<?>> list = mappedNodesToSchema.get(schemaNode) == null ? Lists.<Node<?>> newArrayList()
+                    : mappedNodesToSchema.get(schemaNode);
+            list.add(node);
+            mappedNodesToSchema.put(schemaNode, list);
+        }
+
+        return mappedNodesToSchema;
+    }
+
+    public CompositeNode getOutput() {
+        return output;
+    }
+
+    private Map<QName, DataSchemaNode> mapOutput(final OutputDefinition outputDefinition) {
+        final Map<QName, DataSchemaNode> mapped = Maps.newHashMap();
+        for (final DataSchemaNode dataSchemaNode : outputDefinition) {
+            // without revision since data QNames come without revision
+            mapped.put(dataSchemaNode.getQName().withoutRevision(), dataSchemaNode);
+        }
+
+        return mapped;
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/output/OutputDefinition.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/output/OutputDefinition.java
new file mode 100644 (file)
index 0000000..66d0d4d
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.commands.output;
+
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.Set;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+
+/**
+ * The definition of output elements represented by schema nodes parsed from yang rpc definition
+ */
+public class OutputDefinition implements Iterable<DataSchemaNode> {
+
+    public static final OutputDefinition EMPTY_OUTPUT = new OutputDefinition(Collections.<DataSchemaNode>emptySet());
+    private final Set<DataSchemaNode> childNodes;
+
+    public OutputDefinition(final Set<DataSchemaNode> childNodes) {
+        this.childNodes = childNodes;
+    }
+
+    @Override
+    public Iterator<DataSchemaNode> iterator() {
+        return childNodes.iterator();
+    }
+
+    public static OutputDefinition fromOutput(final ContainerSchemaNode output) {
+        Preconditions.checkNotNull(output);
+        return new OutputDefinition(output.getChildNodes());
+    }
+
+    public static OutputDefinition empty() {
+        return EMPTY_OUTPUT;
+    }
+
+    public boolean isEmpty() {
+        return this == EMPTY_OUTPUT;
+    }
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/remote/RemoteCommand.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/commands/remote/RemoteCommand.java
new file mode 100644 (file)
index 0000000..05b9e85
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.commands.remote;
+
+import com.google.common.util.concurrent.ListenableFuture;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import org.opendaylight.controller.netconf.cli.commands.AbstractCommand;
+import org.opendaylight.controller.netconf.cli.commands.Command;
+import org.opendaylight.controller.netconf.cli.commands.CommandInvocationException;
+import org.opendaylight.controller.netconf.cli.commands.input.Input;
+import org.opendaylight.controller.netconf.cli.commands.input.InputDefinition;
+import org.opendaylight.controller.netconf.cli.commands.output.Output;
+import org.opendaylight.controller.netconf.cli.commands.output.OutputDefinition;
+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.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
+
+/**
+ * Generic remote command implementation that sends the rpc xml to the remote device and waits for response
+ * Waiting is limited with TIMEOUT
+ */
+public class RemoteCommand extends AbstractCommand {
+
+    // TODO make this configurable
+    private static final long DEFAULT_TIMEOUT = 10000;
+    private static final TimeUnit DEFAULT_TIMEOUT_UNIT = TimeUnit.MILLISECONDS;
+    private final RpcImplementation rpc;
+
+    public RemoteCommand(final QName qName, final InputDefinition args, final OutputDefinition output, final String description, final RpcImplementation rpc) {
+        super(qName, args, output, description);
+        this.rpc = rpc;
+    }
+
+    @Override
+    public Output invoke(final Input inputArgs) throws CommandInvocationException {
+        final ListenableFuture<RpcResult<CompositeNode>> invokeRpc = rpc.invokeRpc(getCommandId(), inputArgs.wrap(getCommandId()));
+        try {
+            return new Output(invokeRpc.get(DEFAULT_TIMEOUT, DEFAULT_TIMEOUT_UNIT).getResult());
+        } catch (final ExecutionException e) {
+            throw new CommandInvocationException(getCommandId(), e);
+        } catch (final TimeoutException e) {
+            // Request timed out, cancel request
+            invokeRpc.cancel(true);
+            throw new CommandInvocationException.CommandTimeoutException(getCommandId(), e);
+        } catch (final InterruptedException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    public static Command fromRpc(final RpcDefinition rpcDefinition, final RpcImplementation rpcInvoker) {
+        final InputDefinition args = getInputDefinition(rpcDefinition);
+        final OutputDefinition retVal = getOutputDefinition(rpcDefinition);
+
+        return new RemoteCommand(rpcDefinition.getQName(), args, retVal, rpcDefinition.getDescription(), rpcInvoker);
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/io/BaseConsoleContext.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/io/BaseConsoleContext.java
new file mode 100644 (file)
index 0000000..26e46d3
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.io;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import jline.console.completer.AggregateCompleter;
+import jline.console.completer.Completer;
+import jline.console.completer.StringsCompleter;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+
+public class BaseConsoleContext<T extends DataSchemaNode> implements ConsoleContext {
+
+    private static final Completer SKIP_COMPLETER = new StringsCompleter(IOUtil.SKIP);
+
+    private final T dataSchemaNode;
+
+    public BaseConsoleContext(final T dataSchemaNode) {
+        Preconditions.checkNotNull(dataSchemaNode);
+        this.dataSchemaNode = dataSchemaNode;
+    }
+
+    @Override
+    public Completer getCompleter() {
+        final ArrayList<Completer> completers = Lists.newArrayList(SKIP_COMPLETER);
+        completers.addAll(getAdditionalCompleters());
+        return new AggregateCompleter(completers);
+    }
+
+    protected List<Completer> getAdditionalCompleters() {
+        return Collections.emptyList();
+    }
+
+    @Override
+    public Optional<String> getPrompt() {
+        return Optional.of(dataSchemaNode.getQName().getLocalName());
+    }
+
+    protected T getDataSchemaNode() {
+        return dataSchemaNode;
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/io/ConsoleContext.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/io/ConsoleContext.java
new file mode 100644 (file)
index 0000000..f4ebfca
--- /dev/null
@@ -0,0 +1,22 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.io;
+
+import com.google.common.base.Optional;
+import jline.console.completer.Completer;
+
+/**
+ * Context to be set in the IO. Different prompts + completers are required in different contexts of the CLI.
+ */
+public interface ConsoleContext {
+
+    Completer getCompleter();
+
+    Optional<String> getPrompt();
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/io/ConsoleIO.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/io/ConsoleIO.java
new file mode 100644 (file)
index 0000000..6bffeac
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.io;
+
+import java.io.IOException;
+
+/**
+ * Definition of IO interface
+ */
+public interface ConsoleIO {
+
+    String read() throws IOException;
+
+    String read(Character mask) throws IOException;
+
+    void write(CharSequence data) throws IOException;
+
+    void writeLn(CharSequence data) throws IOException;
+
+    void formatLn(String format, Object... args) throws IOException;
+
+    void enterContext(ConsoleContext consoleContext);
+
+    void enterRootContext(ConsoleContext consoleContext);
+
+    void leaveContext();
+
+    void leaveRootContext();
+
+    void complete();
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/io/ConsoleIOImpl.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/io/ConsoleIOImpl.java
new file mode 100644 (file)
index 0000000..5b7374a
--- /dev/null
@@ -0,0 +1,157 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.io;
+
+import static org.opendaylight.controller.netconf.cli.io.IOUtil.PATH_SEPARATOR;
+import static org.opendaylight.controller.netconf.cli.io.IOUtil.PROMPT_SUFIX;
+
+import com.google.common.base.Optional;
+import com.google.common.collect.Lists;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.io.IOException;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.Iterator;
+import jline.console.ConsoleReader;
+import jline.console.completer.Completer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Jline based IO implementation
+ */
+public class ConsoleIOImpl implements ConsoleIO {
+
+    private static final Logger LOG = LoggerFactory.getLogger(ConsoleIOImpl.class);
+
+    private final ConsoleReader console;
+    private final Deque<ConsoleContext> contexts = new ArrayDeque<>();
+
+    public ConsoleIOImpl() throws IOException {
+        console = new ConsoleReader();
+        console.setHandleUserInterrupt(true);
+        console.setPaginationEnabled(true);
+        console.setHistoryEnabled(true);
+
+        // TODO trifferedActions not supported by jline in current version
+        // https://github.com/jline/jline2/issues/149
+        console.addTriggeredAction('?', new QuestionMarkActionListener());
+    }
+
+    @Override
+    public String read() throws IOException {
+        return console.readLine().trim();
+    }
+
+    @Override
+    public String read(final Character mask) throws IOException {
+        return console.readLine(mask).trim();
+    }
+
+    @Override
+    public void write(final CharSequence data) throws IOException {
+        console.print(data);
+        console.flush();
+    }
+
+    @Override
+    public void writeLn(final CharSequence data) throws IOException {
+        console.println(data);
+        console.flush();
+    }
+
+    @Override
+    public void formatLn(final String format, final Object... args) throws IOException {
+        console.println(String.format(format, args));
+        console.flush();
+    }
+
+    @Override
+    public void enterContext(final ConsoleContext consoleContext) {
+        contexts.push(consoleContext);
+        enterCtx(consoleContext);
+    }
+
+
+    @Override
+    public void enterRootContext(final ConsoleContext consoleContext) {
+        contexts.addLast(consoleContext);
+        enterCtx(consoleContext);
+    }
+
+    private void enterCtx(final ConsoleContext consoleContext) {
+        setCompleter(consoleContext.getCompleter());
+        console.setPrompt(buildPrompt());
+    }
+
+    @Override
+    public void leaveContext() {
+        contexts.pollFirst();
+        leaveCtx();
+    }
+
+    @Override
+    public void leaveRootContext() {
+        contexts.pollLast();
+        leaveCtx();
+    }
+
+    private void leaveCtx() {
+        console.setPrompt(buildPrompt());
+        if (contexts.peek() != null) {
+            setCompleter(contexts.peek().getCompleter());
+        }
+    }
+
+    protected String buildPrompt() {
+        final StringBuilder newPrompt = new StringBuilder();
+
+        final Iterator<ConsoleContext> descendingIterator = contexts.descendingIterator();
+        while (descendingIterator.hasNext()) {
+            final ConsoleContext consoleContext = descendingIterator.next();
+            final Optional<String> promptPart = consoleContext.getPrompt();
+            if (promptPart.isPresent()) {
+                newPrompt.append(PATH_SEPARATOR);
+                newPrompt.append(promptPart.get());
+            }
+        }
+        if (newPrompt.length() ==0) {
+            newPrompt.append(PATH_SEPARATOR);
+        }
+
+        newPrompt.append(PROMPT_SUFIX);
+
+        return newPrompt.toString();
+    }
+
+    private void setCompleter(final Completer newCompleter) {
+        for (final Completer concreteCompleter : console.getCompleters()) {
+            console.removeCompleter(concreteCompleter);
+        }
+        console.addCompleter(newCompleter);
+    }
+
+    private class QuestionMarkActionListener implements ActionListener {
+        @Override
+        public void actionPerformed(final ActionEvent e) {
+            ConsoleIOImpl.this.complete();
+        }
+    }
+
+    public void complete() {
+        final ArrayList<CharSequence> candidates = Lists.newArrayList();
+        contexts.peek().getCompleter().complete("", 0, candidates);
+        try {
+            console.getCompletionHandler().complete(console, candidates, 0);
+        } catch (final IOException ex) {
+            throw new IllegalStateException("Unable to write to output", ex);
+        }
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/io/IOUtil.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/io/IOUtil.java
new file mode 100644 (file)
index 0000000..1817cdd
--- /dev/null
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.io;
+
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.Date;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.opendaylight.controller.netconf.cli.reader.ReadingException;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaNode;
+
+public class IOUtil {
+
+    public static final String SKIP = "skip";
+    public static final String PROMPT_SUFIX = ">";
+    public static final String PATH_SEPARATOR = "/";
+
+    private IOUtil() {
+    }
+
+    public static boolean isQName(final String qName) {
+        final Matcher matcher = patternNew.matcher(qName);
+        return matcher.matches();
+    }
+
+    public static Date parseDate(final String revision) {
+        final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
+        try {
+            return formatter.parse(revision);
+        } catch (final ParseException e) {
+            throw new IllegalArgumentException("Date not valid", e);
+        }
+    }
+
+    public static String listType(final SchemaNode schemaNode) {
+        if (schemaNode instanceof LeafListSchemaNode) {
+            return "Leaf-list";
+        } else if (schemaNode instanceof ListSchemaNode) {
+            return "List";
+        } else if (schemaNode instanceof LeafSchemaNode) {
+            return "Leaf";
+        }
+        // FIXME throw exception on unexpected state, not null/emptyString
+        return "";
+    }
+
+    public static String qNameToKeyString(final QName qName, final String moduleName) {
+        return String.format("%s(%s)", qName.getLocalName(), moduleName);
+    }
+
+    // TODO test and check regex + review format of string for QName
+    final static Pattern patternNew = Pattern.compile("([^\\)]+)\\(([^\\)]+)\\)");
+
+    public static QName qNameFromKeyString(final String qName, final Map<String, QName> mappedModules)
+            throws ReadingException {
+        final Matcher matcher = patternNew.matcher(qName);
+        if (!matcher.matches()) {
+            final String message = String.format("QName in wrong format: %s should be: %s", qName, patternNew);
+            throw new ReadingException(message);
+        }
+        final QName base = mappedModules.get(matcher.group(2));
+        if (base == null) {
+            final String message = String.format("Module %s cannot be found", matcher.group(2));
+            throw new ReadingException(message);
+        }
+        return QName.create(base, matcher.group(1));
+    }
+
+    public static boolean isSkipInput(final String rawValue) {
+        return rawValue.equals(SKIP);
+    }
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/AbstractReader.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/AbstractReader.java
new file mode 100644 (file)
index 0000000..6131eef
--- /dev/null
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.reader;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Strings;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+import jline.console.completer.Completer;
+import jline.console.completer.NullCompleter;
+import org.opendaylight.controller.netconf.cli.io.ConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition;
+
+public abstract class AbstractReader<T extends DataSchemaNode> implements Reader<T> {
+
+    public static final NullContext NULL_CONTEXT = new NullContext();
+
+    // TODO make console private add protected getter
+    protected ConsoleIO console;
+    private final SchemaContext context;
+    private boolean readConfigNode = false;
+
+    public AbstractReader(final ConsoleIO console, final SchemaContext context) {
+        this.console = console;
+        this.context = context;
+    }
+
+    public AbstractReader(final ConsoleIO console, final SchemaContext context, final boolean readConfigNode) {
+        this(console, context);
+        this.readConfigNode = readConfigNode;
+    }
+
+    protected SchemaContext getSchemaContext() {
+        return context;
+    }
+
+    protected ConsoleIO getConsole() {
+        return console;
+    }
+
+    protected boolean getReadConfigNode() {
+        return readConfigNode;
+    }
+
+    @Override
+    public List<Node<?>> read(final T schemaNode) throws ReadingException {
+        if (isReadingWanted(schemaNode)) {
+            final ConsoleContext ctx = getContext(schemaNode);
+            console.enterContext(ctx);
+            try {
+                return readWithContext(schemaNode);
+            } catch (final IOException e) {
+                throw new ReadingException("Unable to read data from input for " + schemaNode.getQName(), e);
+            } finally {
+                console.leaveContext();
+            }
+        }
+        return Collections.emptyList();
+    }
+
+    private boolean isReadingWanted(final DataSchemaNode node) {
+        if (readConfigNode && !node.isConfiguration()) {
+            return false;
+        }
+        return true;
+    }
+
+    // TODO javadoc
+
+    protected abstract List<Node<?>> readWithContext(T schemaNode) throws IOException, ReadingException;
+
+    protected abstract ConsoleContext getContext(T schemaNode);
+
+    protected Optional<String> getDefaultValue(final T schemaNode) {
+        String defaultValue = null;
+        if (schemaNode instanceof LeafSchemaNode) {
+            defaultValue = ((LeafSchemaNode) schemaNode).getDefault();
+        } else if (schemaNode instanceof ChoiceNode) {
+            defaultValue = ((ChoiceNode) schemaNode).getDefaultCase();
+        }
+
+        return Optional.fromNullable(defaultValue);
+    }
+
+    protected boolean isEmptyInput(final String rawValue) {
+        return Strings.isNullOrEmpty(rawValue);
+    }
+
+    protected static boolean isEmptyType(final TypeDefinition<?> type) {
+        return type instanceof EmptyTypeDefinition;
+    }
+
+    private static class NullContext implements ConsoleContext {
+        @Override
+        public Completer getCompleter() {
+            return new NullCompleter();
+        }
+
+        @Override
+        public Optional<String> getPrompt() {
+            return Optional.absent();
+        }
+    }
+
+}
@@ -5,20 +5,13 @@
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
-package org.opendaylight.controller.sal.binding.spi.remote;
-
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-
-public interface RemoteRpcRouter {
-
-
-
-
-
-
-    ListenerRegistration<RouteChangeListener> registerRouteChangeListener(RouteChangeListener listener);
-
+package org.opendaylight.controller.netconf.cli.reader;
 
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 
+/**
+ * marker interface to mark reader which can be used with GenericListReader
+ */
+public interface GenericListEntryReader<T extends DataSchemaNode> extends Reader<T> {
 
 }
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/Reader.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/Reader.java
new file mode 100644 (file)
index 0000000..9f27b8f
--- /dev/null
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.reader;
+
+import java.util.List;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+
+/**
+ * Generic provider(reader) of input arguments for commands
+ */
+public interface Reader<T extends DataSchemaNode> {
+
+    List<Node<?>> read(T schemaNode) throws ReadingException;
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/ReadingException.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/ReadingException.java
new file mode 100644 (file)
index 0000000..81915fc
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.reader;
+
+public class ReadingException extends Exception {
+
+    private static final long serialVersionUID = -298382323286156591L;
+
+    public ReadingException(final String msg, final Exception e) {
+        super(msg, e);
+    }
+
+    public ReadingException(final String msg) {
+        super(msg);
+    }
+
+    public static class IncorrectValueException extends ReadingException {
+
+        private static final long serialVersionUID = 164168437058431592L;
+
+        public IncorrectValueException(final String msg) {
+            super(msg);
+        }
+
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/custom/ConfigReader.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/custom/ConfigReader.java
new file mode 100644 (file)
index 0000000..95fc098
--- /dev/null
@@ -0,0 +1,203 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.reader.custom;
+
+import static org.opendaylight.controller.netconf.cli.io.IOUtil.isSkipInput;
+
+import com.google.common.base.Function;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
+import com.google.common.collect.Collections2;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import java.io.IOException;
+import java.net.URI;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.SortedSet;
+import java.util.TreeSet;
+import jline.console.completer.Completer;
+import org.opendaylight.controller.netconf.cli.CommandArgHandlerRegistry;
+import org.opendaylight.controller.netconf.cli.io.BaseConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.cli.io.IOUtil;
+import org.opendaylight.controller.netconf.cli.reader.AbstractReader;
+import org.opendaylight.controller.netconf.cli.reader.ReadingException;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
+import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+/**
+ * Custom reader implementation for filter elements in get/get-config rpcs. This
+ * reader overrides the default anyxml reader and reads filter as a schema path.
+ */
+public class ConfigReader extends AbstractReader<DataSchemaNode> {
+
+    public static final String SEPARATOR = "/";
+
+    private final CommandArgHandlerRegistry commandArgHandlerRegistry;
+    private final Map<String, QName> mappedModules;
+    private final Map<URI, QName> mappedModulesNamespace;
+
+    public ConfigReader(final ConsoleIO console, final SchemaContext remoteSchemaContext,
+            final CommandArgHandlerRegistry commandArgHandlerRegistry) {
+        super(console, remoteSchemaContext);
+        this.commandArgHandlerRegistry = commandArgHandlerRegistry;
+
+        mappedModules = Maps.newHashMap();
+        mappedModulesNamespace = Maps.newHashMap();
+        for (final Module module : remoteSchemaContext.getModules()) {
+            final QName moduleQName = QName.create(module.getNamespace(), module.getRevision(), module.getName());
+            mappedModules.put(moduleQName.getLocalName(), moduleQName);
+            mappedModulesNamespace.put(moduleQName.getNamespace(), moduleQName);
+        }
+    }
+
+    // FIXME refactor + unite common code with FilterReader
+
+    @Override
+    protected List<Node<?>> readWithContext(final DataSchemaNode schemaNode) throws IOException, ReadingException {
+        console.writeLn("Config " + schemaNode.getQName().getLocalName());
+        console.writeLn("Submit path of the data to edit. Use TAB for autocomplete");
+
+        final String rawValue = console.read();
+
+        // FIXME isSkip check should be somewhere in abstractReader
+        if (isSkipInput(rawValue) || Strings.isNullOrEmpty(rawValue)) {
+            return Collections.emptyList();
+        }
+
+        final List<QName> filterPartsQNames = Lists.newArrayList();
+
+        for (final String part : rawValue.split(SEPARATOR)) {
+            final QName qName = IOUtil.qNameFromKeyString(part, mappedModules);
+            filterPartsQNames.add(qName);
+        }
+
+        List<Node<?>> previous = readInnerNode(rawValue);
+
+        for (final QName qName : Lists.reverse(filterPartsQNames).subList(1, filterPartsQNames.size())) {
+            previous = Collections.<Node<?>> singletonList(new CompositeNodeTOImpl(qName, null,
+                    previous == null ? Collections.<Node<?>> emptyList() : previous));
+        }
+
+        final Node<?> newNode = previous == null ? null
+                : new CompositeNodeTOImpl(schemaNode.getQName(), null, previous);
+
+        return Collections.<Node<?>> singletonList(newNode);
+    }
+
+    private List<Node<?>> readInnerNode(final String pathString) throws ReadingException {
+        final Optional<DataSchemaNode> schema = getCurrentNode(getSchemaContext(), pathString);
+        Preconditions.checkState(schema.isPresent(), "Unable to find schema for %s", pathString);
+        return commandArgHandlerRegistry.getGenericReader(getSchemaContext(), true).read(schema.get());
+    }
+
+    @Override
+    protected ConsoleContext getContext(final DataSchemaNode schemaNode) {
+        return new FilterConsoleContext(schemaNode, getSchemaContext());
+    }
+
+    private final class FilterConsoleContext extends BaseConsoleContext<DataSchemaNode> {
+
+        private final SchemaContext remoteSchemaContext;
+
+        public FilterConsoleContext(final DataSchemaNode schemaNode, final SchemaContext remoteSchemaContext) {
+            super(schemaNode);
+            this.remoteSchemaContext = remoteSchemaContext;
+        }
+
+        @Override
+        protected List<Completer> getAdditionalCompleters() {
+            return Collections.<Completer> singletonList(new FilterCompleter(remoteSchemaContext));
+        }
+    }
+
+    private final class FilterCompleter implements Completer {
+
+        private final SchemaContext remoteSchemaContext;
+
+        public FilterCompleter(final SchemaContext remoteSchemaContext) {
+            this.remoteSchemaContext = remoteSchemaContext;
+        }
+
+        @Override
+        public int complete(final String buffer, final int cursor, final List<CharSequence> candidates) {
+            final int idx = buffer.lastIndexOf(SEPARATOR);
+
+            final Optional<DataSchemaNode> currentNode = getCurrentNode(remoteSchemaContext, buffer);
+            if (currentNode.isPresent() && currentNode.get() instanceof DataNodeContainer) {
+                final Collection<DataSchemaNode> childNodes = ((DataNodeContainer) currentNode.get()).getChildNodes();
+                final Collection<String> transformed = Collections2.transform(childNodes,
+                        new Function<DataSchemaNode, String>() {
+                            @Override
+                            public String apply(final DataSchemaNode input) {
+                                return IOUtil.qNameToKeyString(input.getQName(),
+                                        mappedModulesNamespace.get(input.getQName().getNamespace()).getLocalName());
+                            }
+                        });
+
+                fillCandidates(buffer.substring(idx + 1), candidates, transformed);
+            }
+
+            return idx == -1 ? 0 : idx + 1;
+        }
+
+        private void fillCandidates(final String buffer, final List<CharSequence> candidates,
+                final Collection<String> transformed) {
+            final SortedSet<String> strings = new TreeSet<>(transformed);
+
+            if (buffer == null) {
+                candidates.addAll(strings);
+            } else {
+                for (final String match : strings.tailSet(buffer)) {
+                    if (!match.startsWith(buffer)) {
+                        break;
+                    }
+                    candidates.add(match);
+                }
+            }
+
+            if (candidates.size() == 1) {
+                candidates.set(0, candidates.get(0) + SEPARATOR);
+            }
+        }
+
+    }
+
+    private Optional<DataSchemaNode> getCurrentNode(DataSchemaNode parent, final String buffer) {
+        for (final String part : buffer.split(SEPARATOR)) {
+            if (IOUtil.isQName(part) == false) {
+                return Optional.of(parent);
+            }
+
+            final QName qName;
+            try {
+                qName = IOUtil.qNameFromKeyString(part, mappedModules);
+            } catch (final ReadingException e) {
+                return Optional.of(parent);
+            }
+            if (parent instanceof DataNodeContainer) {
+                parent = ((DataNodeContainer) parent).getDataChildByName(qName);
+            } else {
+                // This should check if we are at the end of buffer ?
+                return Optional.of(parent);
+            }
+        }
+        return Optional.of(parent);
+    }
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/custom/EditContentReader.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/custom/EditContentReader.java
new file mode 100644 (file)
index 0000000..af43d37
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.reader.custom;
+
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.util.List;
+import org.opendaylight.controller.netconf.cli.CommandArgHandlerRegistry;
+import org.opendaylight.controller.netconf.cli.commands.CommandConstants;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.cli.reader.ReadingException;
+import org.opendaylight.controller.netconf.cli.reader.impl.ChoiceReader;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+public class EditContentReader extends ChoiceReader {
+
+    public static final QName EDIT_CONTENT_QNAME = QName.create(CommandConstants.NETCONF_BASE_QNAME, "edit-content");
+    public static final QName CONFIG_QNAME = QName.create(EDIT_CONTENT_QNAME, "config");
+
+    // FIXME this could be removed if feature/if-feature are supported
+
+    public EditContentReader(final ConsoleIO console, final CommandArgHandlerRegistry argumentHandlerRegistry, final SchemaContext schemaContext) {
+        super(console, argumentHandlerRegistry, schemaContext);
+    }
+
+    @Override
+    public List<Node<?>> readWithContext(final ChoiceNode choiceNode) throws IOException, ReadingException {
+        Preconditions.checkState(choiceNode.getQName().equals(EDIT_CONTENT_QNAME), "Unexpected choice %s, expected %s", choiceNode, EDIT_CONTENT_QNAME);
+        final ChoiceCaseNode selectedCase = choiceNode.getCaseNodeByName(CONFIG_QNAME);
+        Preconditions.checkNotNull(selectedCase, "Unexpected choice %s, expected %s that contains %s", choiceNode, EDIT_CONTENT_QNAME, CONFIG_QNAME);
+        return readSelectedCase(selectedCase);
+    }
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/custom/FilterReader.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/custom/FilterReader.java
new file mode 100644 (file)
index 0000000..7b37f69
--- /dev/null
@@ -0,0 +1,218 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.reader.custom;
+
+import static org.opendaylight.controller.netconf.cli.io.IOUtil.isSkipInput;
+
+import com.google.common.base.Function;
+import com.google.common.base.Optional;
+import com.google.common.base.Strings;
+import com.google.common.collect.Collections2;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import java.io.IOException;
+import java.net.URI;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.SortedSet;
+import java.util.TreeSet;
+import jline.console.completer.Completer;
+import org.opendaylight.controller.netconf.cli.io.BaseConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.cli.io.IOUtil;
+import org.opendaylight.controller.netconf.cli.reader.AbstractReader;
+import org.opendaylight.controller.netconf.cli.reader.ReadingException;
+import org.opendaylight.yangtools.yang.common.QName;
+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.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Custom reader implementation for filter elements in get/get-config rpcs. This
+ * reader overrides the default anyxml reader and reads filter as a schema path.
+ */
+public class FilterReader extends AbstractReader<DataSchemaNode> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(FilterReader.class);
+
+    public static final String SEPARATOR = "/";
+
+    private final Map<String, QName> mappedModules;
+    private final Map<URI, QName> mappedModulesNamespace;
+
+    public FilterReader(final ConsoleIO console, final SchemaContext remoteSchemaContext) {
+        super(console, remoteSchemaContext);
+
+        mappedModules = Maps.newHashMap();
+        mappedModulesNamespace = Maps.newHashMap();
+        for (final Module module : remoteSchemaContext.getModules()) {
+            final QName moduleQName = QName.create(module.getNamespace(), module.getRevision(), module.getName());
+            mappedModules.put(moduleQName.getLocalName(), moduleQName);
+            mappedModulesNamespace.put(moduleQName.getNamespace(), moduleQName);
+        }
+    }
+
+    // FIXME refactor
+
+    public static final QName FILTER_TYPE_QNAME = QName.create("urn:ietf:params:xml:ns:netconf:base:1.0", "2011-06-01",
+            "type");
+    public static final String FILTER_TYPE_VALUE_DEFAULT = "subtree";
+
+    @Override
+    protected List<Node<?>> readWithContext(final DataSchemaNode schemaNode) throws IOException, ReadingException {
+        boolean redSuccessfuly = false;
+        Node<?> newNode = null;
+        do {
+            console.writeLn("Filter " + schemaNode.getQName().getLocalName());
+            console.writeLn("Submit path of the data to retrieve. Use TAB for autocomplete");
+
+            final String rawValue = console.read();
+
+            // FIXME skip should be somewhere in abstractReader
+            if (isSkipInput(rawValue) || Strings.isNullOrEmpty(rawValue)) {
+                return Collections.emptyList();
+            }
+
+            final List<QName> filterPartsQNames = Lists.newArrayList();
+
+            try {
+                for (final String part : rawValue.split(SEPARATOR)) {
+                    final QName qName = IOUtil.qNameFromKeyString(part, mappedModules);
+                    filterPartsQNames.add(qName);
+                }
+
+                Node<?> previous = null;
+
+                for (final QName qName : Lists.reverse(filterPartsQNames)) {
+                    previous = new CompositeNodeTOImpl(qName, null,
+                            previous == null ? Collections.<Node<?>> emptyList()
+                                    : Collections.<Node<?>> singletonList(previous));
+                }
+
+                final Map<QName, String> attributes = Collections.singletonMap(FILTER_TYPE_QNAME,
+                        FILTER_TYPE_VALUE_DEFAULT);
+                newNode = previous == null ? null : ImmutableCompositeNode.create(schemaNode.getQName(), attributes,
+                        Collections.<Node<?>> singletonList(previous));
+                redSuccessfuly = true;
+            } catch (final ReadingException e) {
+                final String message = "Specified filter path isn't correct.";
+                LOG.error(message, e);
+                console.writeLn(message);
+            }
+        } while (!redSuccessfuly);
+        return Collections.<Node<?>> singletonList(newNode);
+    }
+
+    @Override
+    protected ConsoleContext getContext(final DataSchemaNode schemaNode) {
+        return new FilterConsoleContext(schemaNode, getSchemaContext());
+    }
+
+    private final class FilterConsoleContext extends BaseConsoleContext<DataSchemaNode> {
+
+        private final SchemaContext remoteSchemaContext;
+
+        public FilterConsoleContext(final DataSchemaNode schemaNode, final SchemaContext remoteSchemaContext) {
+            super(schemaNode);
+            this.remoteSchemaContext = remoteSchemaContext;
+        }
+
+        @Override
+        protected List<Completer> getAdditionalCompleters() {
+            return Collections.<Completer> singletonList(new FilterCompleter(remoteSchemaContext));
+        }
+
+    }
+
+    private final class FilterCompleter implements Completer {
+
+        private final SchemaContext remoteSchemaContext;
+
+        // TODO add skip to filter completer, better soulution would be to add
+        // SKIP completer before context completer if possible
+
+        public FilterCompleter(final SchemaContext remoteSchemaContext) {
+            this.remoteSchemaContext = remoteSchemaContext;
+        }
+
+        @Override
+        public int complete(final String buffer, final int cursor, final List<CharSequence> candidates) {
+            final int idx = buffer.lastIndexOf(SEPARATOR);
+
+            final Optional<DataNodeContainer> currentNode = getCurrentNode(remoteSchemaContext, buffer);
+            if (currentNode.isPresent()) {
+
+                final Collection<String> transformed = Collections2.transform(currentNode.get().getChildNodes(),
+                        new Function<DataSchemaNode, String>() {
+                            @Override
+                            public String apply(final DataSchemaNode input) {
+                                return IOUtil.qNameToKeyString(input.getQName(),
+                                        mappedModulesNamespace.get(input.getQName().getNamespace()).getLocalName());
+                            }
+                        });
+
+                fillCandidates(buffer.substring(idx + 1), candidates, transformed);
+            }
+
+            return idx == -1 ? 0 : idx + 1;
+        }
+
+        private void fillCandidates(final String buffer, final List<CharSequence> candidates,
+                final Collection<String> transformed) {
+            final SortedSet<String> strings = new TreeSet<>(transformed);
+
+            if (buffer == null) {
+                candidates.addAll(strings);
+            } else {
+                for (final String match : strings.tailSet(buffer)) {
+                    if (!match.startsWith(buffer)) {
+                        break;
+                    }
+                    candidates.add(match);
+                }
+            }
+
+            if (candidates.size() == 1) {
+                candidates.set(0, candidates.get(0) + SEPARATOR);
+            }
+        }
+
+        private Optional<DataNodeContainer> getCurrentNode(DataNodeContainer parent, final String buffer) {
+            for (final String part : buffer.split(SEPARATOR)) {
+                if (!IOUtil.isQName(part)) {
+                    return Optional.of(parent);
+                }
+
+                QName qName;
+                try {
+                    qName = IOUtil.qNameFromKeyString(part, mappedModules);
+                } catch (final ReadingException e) {
+                    return Optional.of(parent);
+                }
+
+                final DataSchemaNode dataChildByName = parent.getDataChildByName(qName);
+                if (dataChildByName instanceof DataNodeContainer) {
+                    parent = (DataNodeContainer) dataChildByName;
+                } else {
+                    return Optional.absent();
+                }
+            }
+            return Optional.of(parent);
+        }
+    }
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/custom/PasswordReader.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/custom/PasswordReader.java
new file mode 100644 (file)
index 0000000..4804455
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.reader.custom;
+
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import jline.console.completer.Completer;
+import jline.console.completer.NullCompleter;
+import org.opendaylight.controller.netconf.cli.io.BaseConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.cli.reader.impl.BasicDataHolderReader;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+
+public class PasswordReader extends BasicDataHolderReader<DataSchemaNode> {
+
+    private static final char PASSWORD_MASK = '*';
+
+    public PasswordReader(final ConsoleIO console, final SchemaContext schemaContext) {
+        super(console, schemaContext);
+    }
+
+    @Override
+    protected ConsoleContext getContext(final DataSchemaNode schemaNode) {
+        return new BaseConsoleContext<DataSchemaNode>(schemaNode) {
+            @Override
+            public Completer getCompleter() {
+                return new NullCompleter();
+            }
+        };
+    }
+
+    @Override
+    protected TypeDefinition<?> getType(final DataSchemaNode schemaNode) {
+        Preconditions.checkArgument(schemaNode instanceof LeafSchemaNode);
+        return ((LeafSchemaNode)schemaNode).getType();
+    }
+
+    @Override
+    protected String readValue() throws IOException {
+        return console.read(PASSWORD_MASK);
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/AnyXmlReader.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/AnyXmlReader.java
new file mode 100644 (file)
index 0000000..2ce2f64
--- /dev/null
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.reader.impl;
+
+import static org.opendaylight.controller.netconf.cli.io.IOUtil.isSkipInput;
+import static org.opendaylight.controller.netconf.cli.io.IOUtil.listType;
+
+import com.google.common.base.Optional;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import org.opendaylight.controller.netconf.cli.io.BaseConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.cli.reader.AbstractReader;
+import org.opendaylight.controller.netconf.cli.reader.ReadingException;
+import org.opendaylight.controller.netconf.util.xml.XmlUtil;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
+import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
+import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.w3c.dom.Document;
+import org.xml.sax.SAXException;
+
+public class AnyXmlReader extends AbstractReader<AnyXmlSchemaNode> {
+
+    public AnyXmlReader(final ConsoleIO console, final SchemaContext schemaContext) {
+        super(console, schemaContext);
+    }
+
+    public AnyXmlReader(final ConsoleIO console, final SchemaContext schemaContext, final boolean readConfigNode) {
+        super(console, schemaContext, readConfigNode);
+    }
+
+    @Override
+    protected List<Node<?>> readWithContext(final AnyXmlSchemaNode schemaNode) throws IOException, ReadingException {
+        console.writeLn(listType(schemaNode) + " " + schemaNode.getQName().getLocalName());
+
+        final String rawValue = console.read();
+
+        Node<?> newNode = null;
+        if (!isSkipInput(rawValue)) {
+            final Optional<Node<?>> value = tryParse(rawValue);
+
+            if (value.isPresent()) {
+                newNode = NodeFactory.createImmutableCompositeNode(schemaNode.getQName(), null,
+                        Collections.<Node<?>> singletonList(value.get()));
+            } else {
+                newNode = NodeFactory.createImmutableSimpleNode(schemaNode.getQName(), null, rawValue);
+            }
+        }
+
+        final List<Node<?>> newNodes = new ArrayList<>();
+        newNodes.add(newNode);
+        return newNodes;
+    }
+
+    private Optional<Node<?>> tryParse(final String rawValue) {
+        try {
+            final Document dom = XmlUtil.readXmlToDocument(rawValue);
+            return Optional.<Node<?>> of(XmlDocumentUtils.toDomNode(dom));
+        } catch (SAXException | IOException e) {
+            // TODO log
+            return Optional.absent();
+        }
+    }
+
+    @Override
+    protected ConsoleContext getContext(final AnyXmlSchemaNode schemaNode) {
+        return new BaseConsoleContext<>(schemaNode);
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/BasicDataHolderReader.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/BasicDataHolderReader.java
new file mode 100644 (file)
index 0000000..ef41e7f
--- /dev/null
@@ -0,0 +1,255 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.reader.impl;
+
+import static org.opendaylight.controller.netconf.cli.io.IOUtil.isSkipInput;
+import static org.opendaylight.controller.netconf.cli.io.IOUtil.listType;
+
+import com.google.common.base.Function;
+import com.google.common.base.Optional;
+import com.google.common.collect.BiMap;
+import com.google.common.collect.Collections2;
+import com.google.common.collect.HashBiMap;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+import jline.console.completer.Completer;
+import jline.console.completer.StringsCompleter;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.cli.io.IOUtil;
+import org.opendaylight.controller.netconf.cli.reader.AbstractReader;
+import org.opendaylight.controller.netconf.cli.reader.ReadingException;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
+import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.IdentitySchemaNode;
+import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
+import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public abstract class BasicDataHolderReader<T extends DataSchemaNode> extends AbstractReader<T> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(BasicDataHolderReader.class);
+    private DataHolderCompleter currentCompleter;
+
+    public BasicDataHolderReader(final ConsoleIO console, final SchemaContext schemaContext,
+            final boolean readConfigNode) {
+        super(console, schemaContext, readConfigNode);
+    }
+
+    public BasicDataHolderReader(final ConsoleIO console, final SchemaContext schemaContext) {
+        super(console, schemaContext);
+    }
+
+    @Override
+    public List<Node<?>> readWithContext(final T schemaNode) throws IOException, ReadingException {
+        TypeDefinition<?> type = getType(schemaNode);
+        console.formatLn("Submit %s %s(%s)", listType(schemaNode), schemaNode.getQName().getLocalName(), type.getQName().getLocalName());
+
+        while (baseTypeFor(type) instanceof UnionTypeDefinition) {
+            final Optional<TypeDefinition<?>> optionalTypeDef = new UnionTypeReader(console).read(type);
+            if (!optionalTypeDef.isPresent()) {
+                return postSkipOperations(schemaNode);
+            }
+            type = optionalTypeDef.get();
+        }
+
+        if (currentCompleter == null) {
+            currentCompleter = getBaseCompleter(schemaNode);
+        }
+
+        // TODO what if type is leafref, instance-identifier?
+
+        // Handle empty type leaf by question
+        if (isEmptyType(type)) {
+            final Optional<Boolean> shouldAddEmpty = new DecisionReader().read(console, "Add empty type leaf %s ?",
+                    schemaNode.getQName().getLocalName());
+            if (shouldAddEmpty.isPresent()) {
+                if (shouldAddEmpty.get()) {
+                    return wrapValue(schemaNode, "");
+                } else {
+                    return Collections.emptyList();
+                }
+            } else {
+                return postSkipOperations(schemaNode);
+            }
+        }
+
+        final String rawValue = readValue();
+        if (isSkipInput(rawValue)) {
+            return postSkipOperations(schemaNode);
+        }
+
+        final Object resolvedValue = currentCompleter.resolveValue(rawValue);
+
+        // Reset state TODO should be in finally
+        currentCompleter = null;
+        return wrapValue(schemaNode, resolvedValue);
+    }
+
+    private List<Node<?>> postSkipOperations(final DataSchemaNode schemaNode) throws IOException {
+        console.formatLn("Skipping %s", schemaNode.getQName());
+        return Collections.emptyList();
+    }
+
+    private TypeDefinition<?> baseTypeFor(final TypeDefinition<?> type) {
+        if (type.getBaseType() != null) {
+            return baseTypeFor(type.getBaseType());
+        }
+        return type;
+    }
+
+    protected String readValue() throws IOException {
+        return console.read();
+    }
+
+    private List<Node<?>> wrapValue(final T schemaNode, final Object value) {
+        final Node<?> newNode = NodeFactory.createImmutableSimpleNode(schemaNode.getQName(), null, value);
+        return Collections.<Node<?>> singletonList(newNode);
+    }
+
+    protected abstract TypeDefinition<?> getType(final T schemaNode);
+
+    protected final DataHolderCompleter getBaseCompleter(final T schemaNode) {
+        final TypeDefinition<?> type = getType(schemaNode);
+        final DataHolderCompleter currentCompleter;
+
+        // Add enum completer
+        if (type instanceof EnumTypeDefinition) {
+            currentCompleter = new EnumDataHolderCompleter(type);
+        } else if (type instanceof IdentityrefTypeDefinition) {
+            currentCompleter = new IdentityRefDataHolderCompleter(type, getSchemaContext());
+        } else {
+            currentCompleter = new GeneralDataHolderCompleter(type);
+        }
+        this.currentCompleter = currentCompleter;
+        return currentCompleter;
+    }
+
+    private static interface DataHolderCompleter extends Completer {
+
+        Object resolveValue(String rawValue) throws ReadingException;
+    }
+
+    private static class GeneralDataHolderCompleter implements DataHolderCompleter {
+
+        private final Optional<TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>>> codec;
+        private final TypeDefinition<?> type;
+
+        public GeneralDataHolderCompleter(final TypeDefinition<?> type) {
+            this.type = type;
+            codec = getCodecForType(type);
+        }
+
+        protected TypeDefinition<?> getType() {
+            return type;
+        }
+
+        private Optional<TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>>> getCodecForType(
+                final TypeDefinition<?> type) {
+            if (type != null) {
+                return Optional
+                        .<TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>>> fromNullable(TypeDefinitionAwareCodec
+                                .from(type));
+            }
+            return Optional.absent();
+        }
+
+        @Override
+        public Object resolveValue(final String rawValue) throws ReadingException {
+            try {
+                return codec.isPresent() ? codec.get().deserialize(rawValue) : rawValue;
+            } catch (final RuntimeException e) {
+                final String message = "It wasn't possible deserialize value " + rawValue + ".";
+                LOG.error(message, e);
+                throw new ReadingException(message, e);
+            }
+        }
+
+        @Override
+        public int complete(final String buffer, final int cursor, final List<CharSequence> candidates) {
+            return 0;
+        }
+    }
+
+    private static final class EnumDataHolderCompleter extends GeneralDataHolderCompleter {
+
+        public EnumDataHolderCompleter(final TypeDefinition<?> type) {
+            super(type);
+        }
+
+        @Override
+        public Object resolveValue(final String rawValue) throws ReadingException {
+            return super.resolveValue(rawValue);
+        }
+
+        @Override
+        public int complete(final String buffer, final int cursor, final List<CharSequence> candidates) {
+            return new StringsCompleter(Collections2.transform(((EnumTypeDefinition) getType()).getValues(),
+                    new Function<EnumPair, String>() {
+                        @Override
+                        public String apply(final EnumPair input) {
+                            return input.getName();
+                        }
+                    })).complete(buffer, cursor, candidates);
+        }
+    }
+
+    private static final class IdentityRefDataHolderCompleter extends GeneralDataHolderCompleter {
+
+        private final BiMap<String, QName> identityMap;
+
+        public IdentityRefDataHolderCompleter(final TypeDefinition<?> type, final SchemaContext schemaContext) {
+            super(type);
+            this.identityMap = getIdentityMap(schemaContext);
+        }
+
+        private static BiMap<String, QName> getIdentityMap(final SchemaContext schemaContext) {
+            final BiMap<String, QName> identityMap = HashBiMap.create();
+            for (final Module module : schemaContext.getModules()) {
+                for (final IdentitySchemaNode identity : module.getIdentities()) {
+                    identityMap.put(getIdentityName(identity, module), identity.getQName());
+                }
+            }
+            return identityMap;
+        }
+
+        private static String getIdentityName(final IdentitySchemaNode rpcDefinition, final Module module) {
+            return IOUtil.qNameToKeyString(rpcDefinition.getQName(), module.getName());
+        }
+
+        @Override
+        public Object resolveValue(final String rawValue) throws ReadingException {
+            final QName qName = identityMap.get(rawValue);
+            if (qName == null) {
+                throw new ReadingException("No identity found for " + rawValue + " available " + identityMap.keySet());
+            }
+            return qName;
+        }
+
+        @Override
+        public int complete(final String buffer, final int cursor, final List<CharSequence> candidates) {
+
+            return new StringsCompleter(Collections2.transform(((IdentityrefTypeDefinition) getType()).getIdentity()
+                    .getDerivedIdentities(), new Function<IdentitySchemaNode, String>() {
+                @Override
+                public String apply(final IdentitySchemaNode input) {
+                    return identityMap.inverse().get(input.getQName());
+                }
+            })).complete(buffer, cursor, candidates);
+        }
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/ChoiceReader.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/ChoiceReader.java
new file mode 100644 (file)
index 0000000..1e69fbb
--- /dev/null
@@ -0,0 +1,139 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.reader.impl;
+
+import static org.opendaylight.controller.netconf.cli.io.IOUtil.isSkipInput;
+
+import com.google.common.base.Function;
+import com.google.common.collect.Maps;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import jline.console.completer.Completer;
+import jline.console.completer.StringsCompleter;
+import org.opendaylight.controller.netconf.cli.CommandArgHandlerRegistry;
+import org.opendaylight.controller.netconf.cli.io.BaseConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.cli.reader.AbstractReader;
+import org.opendaylight.controller.netconf.cli.reader.ReadingException;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
+import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class ChoiceReader extends AbstractReader<ChoiceNode> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(ChoiceReader.class);
+
+    private final CommandArgHandlerRegistry argumentHandlerRegistry;
+
+    public ChoiceReader(final ConsoleIO console, final CommandArgHandlerRegistry argumentHandlerRegistry,
+            final SchemaContext schemaContext) {
+        super(console, schemaContext);
+        this.argumentHandlerRegistry = argumentHandlerRegistry;
+    }
+
+    public ChoiceReader(final ConsoleIO console, final CommandArgHandlerRegistry argumentHandlerRegistry,
+            final SchemaContext schemaContext, final boolean readConfigNode) {
+        super(console, schemaContext, readConfigNode);
+        this.argumentHandlerRegistry = argumentHandlerRegistry;
+    }
+
+    @Override
+    public List<Node<?>> readWithContext(final ChoiceNode choiceNode) throws IOException, ReadingException {
+        final Map<String, ChoiceCaseNode> availableCases = collectAllCases(choiceNode);
+        console.formatLn("Select case for choice %s from: %s", choiceNode.getQName().getLocalName(),
+                formatSet(availableCases.keySet()));
+
+        ChoiceCaseNode selectedCase = null;
+        final String rawValue = console.read();
+        if (isSkipInput(rawValue)) {
+            return Collections.emptyList();
+        }
+
+        selectedCase = availableCases.get(rawValue);
+        if (selectedCase == null) {
+            final String message = String.format("Incorrect value (%s) for choice %s was selected.", rawValue,
+                    choiceNode.getQName().getLocalName());
+            LOG.error(message);
+            throw new ReadingException(message);
+        }
+
+        return readSelectedCase(selectedCase);
+    }
+
+    protected List<Node<?>> readSelectedCase(final ChoiceCaseNode selectedCase) throws ReadingException {
+        // IF there is a case that contains only one Empty type leaf, create the
+        // leaf without question, since the case was selected
+        if (containsOnlyOneEmptyLeaf(selectedCase)) {
+            final Node<?> newNode = NodeFactory.createImmutableSimpleNode(selectedCase.getChildNodes().iterator()
+                    .next().getQName(), null, null);
+            return Collections.<Node<?>> singletonList(newNode);
+        }
+
+        final List<Node<?>> newNodes = new ArrayList<>();
+        for (final DataSchemaNode schemaNode : selectedCase.getChildNodes()) {
+            newNodes.addAll(argumentHandlerRegistry.getGenericReader(getSchemaContext(), getReadConfigNode()).read(
+                    schemaNode));
+        }
+        return newNodes;
+    }
+
+    private Object formatSet(final Set<String> values) {
+        final StringBuilder formatedValues = new StringBuilder();
+        for (final String value : values) {
+            formatedValues.append("\n  ");
+            formatedValues.append(value);
+        }
+        return formatedValues.toString();
+    }
+
+    private boolean containsOnlyOneEmptyLeaf(final ChoiceCaseNode selectedCase) {
+        if (selectedCase.getChildNodes().size() != 1) {
+            return false;
+        }
+        final DataSchemaNode next = selectedCase.getChildNodes().iterator().next();
+        if (next instanceof LeafSchemaNode) {
+            final TypeDefinition<?> type = ((LeafSchemaNode) next).getType();
+            if (isEmptyType(type)) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    private Map<String, ChoiceCaseNode> collectAllCases(final ChoiceNode schemaNode) {
+        return Maps.uniqueIndex(schemaNode.getCases(), new Function<ChoiceCaseNode, String>() {
+            @Override
+            public String apply(final ChoiceCaseNode input) {
+                return input.getQName().getLocalName();
+            }
+        });
+    }
+
+    @Override
+    protected ConsoleContext getContext(final ChoiceNode schemaNode) {
+        return new BaseConsoleContext<ChoiceNode>(schemaNode) {
+            @Override
+            public List<Completer> getAdditionalCompleters() {
+                return Collections
+                        .<Completer> singletonList(new StringsCompleter(collectAllCases(schemaNode).keySet()));
+            }
+        };
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/ContainerReader.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/ContainerReader.java
new file mode 100644 (file)
index 0000000..8e9a29e
--- /dev/null
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.reader.impl;
+
+import com.google.common.base.Function;
+import com.google.common.collect.Collections2;
+import com.google.common.collect.Lists;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Set;
+import org.opendaylight.controller.netconf.cli.CommandArgHandlerRegistry;
+import org.opendaylight.controller.netconf.cli.io.BaseConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.cli.reader.AbstractReader;
+import org.opendaylight.controller.netconf.cli.reader.ReadingException;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
+import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+public class ContainerReader extends AbstractReader<ContainerSchemaNode> {
+
+    private final CommandArgHandlerRegistry argumentHandlerRegistry;
+    private static final InputArgsLocalNameComparator CONTAINER_CHILDS_SORTER = new InputArgsLocalNameComparator();
+
+    public ContainerReader(final ConsoleIO console, final CommandArgHandlerRegistry argumentHandlerRegistry,
+            final SchemaContext schemaContext) {
+        super(console, schemaContext);
+        this.argumentHandlerRegistry = argumentHandlerRegistry;
+    }
+
+    public ContainerReader(final ConsoleIO console, final CommandArgHandlerRegistry argumentHandlerRegistry,
+            final SchemaContext schemaContext, final boolean readConfigNode) {
+        super(console, schemaContext, readConfigNode);
+        this.argumentHandlerRegistry = argumentHandlerRegistry;
+    }
+
+    @Override
+    public List<Node<?>> readWithContext(final ContainerSchemaNode containerNode) throws IOException, ReadingException {
+        console.formatLn("Submit child nodes for container: %s, %s", containerNode.getQName().getLocalName(),
+                Collections2.transform(containerNode.getChildNodes(), new Function<DataSchemaNode, String>() {
+                    @Override
+                    public String apply(final DataSchemaNode input) {
+                        return input.getQName().getLocalName();
+                    }
+                }));
+
+        final CompositeNodeBuilder<ImmutableCompositeNode> compositeNodeBuilder = ImmutableCompositeNode.builder();
+        compositeNodeBuilder.setQName(containerNode.getQName());
+        final SeparatedNodes separatedNodes = SeparatedNodes.separateNodes(containerNode, getReadConfigNode());
+        for (final DataSchemaNode childNode : sortChildren(separatedNodes.getMandatoryNotKey())) {
+            final List<Node<?>> redNodes = argumentHandlerRegistry.getGenericReader(getSchemaContext(),
+                    getReadConfigNode()).read(childNode);
+            if (redNodes.isEmpty()) {
+                console.formatLn("No data specified for mandatory element %s.", childNode.getQName().getLocalName());
+                return Collections.emptyList();
+            } else {
+                compositeNodeBuilder.addAll(redNodes);
+            }
+        }
+
+        for (final DataSchemaNode childNode : sortChildren(separatedNodes.getOthers())) {
+            compositeNodeBuilder.addAll(argumentHandlerRegistry.getGenericReader(getSchemaContext(),
+                    getReadConfigNode()).read(childNode));
+        }
+        return Collections.<Node<?>> singletonList(compositeNodeBuilder.toInstance());
+    }
+
+    private List<DataSchemaNode> sortChildren(final Set<DataSchemaNode> unsortedNodes) {
+        final List<DataSchemaNode> childNodes = Lists.newArrayList(unsortedNodes);
+        Collections.sort(childNodes, CONTAINER_CHILDS_SORTER);
+        return childNodes;
+    }
+
+    @Override
+    protected ConsoleContext getContext(final ContainerSchemaNode schemaNode) {
+        return new BaseConsoleContext<>(schemaNode);
+    }
+
+    private static class InputArgsLocalNameComparator implements Comparator<DataSchemaNode> {
+        @Override
+        public int compare(final DataSchemaNode o1, final DataSchemaNode o2) {
+            return o1.getQName().getLocalName().compareTo(o2.getQName().getLocalName());
+        }
+    }
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/DecisionReader.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/DecisionReader.java
new file mode 100644 (file)
index 0000000..b1e9a43
--- /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.netconf.cli.reader.impl;
+
+import static org.opendaylight.controller.netconf.cli.io.IOUtil.SKIP;
+
+import com.google.common.base.Optional;
+import java.io.IOException;
+import jline.console.completer.AggregateCompleter;
+import jline.console.completer.Completer;
+import jline.console.completer.StringsCompleter;
+import jline.internal.Log;
+import org.opendaylight.controller.netconf.cli.io.ConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.cli.io.IOUtil;
+import org.opendaylight.controller.netconf.cli.reader.ReadingException;
+
+public class DecisionReader {
+
+    private static final String YES = "Y";
+    private static final String NO = "N";
+    public static final Completer YES_NO_COMPLETER = new StringsCompleter(YES, NO);
+
+    public Optional<Boolean> read(final ConsoleIO console, final String questionMessageBlueprint,
+            final Object... questionMessageArgs) throws IOException, ReadingException {
+        final ConsoleContext ctx = getContext();
+        console.enterContext(ctx);
+        try {
+            console.formatLn(questionMessageBlueprint, questionMessageArgs);
+            final String rawValue = console.read();
+            if (YES.equals(rawValue.toUpperCase())) {
+                return Optional.of(Boolean.TRUE);
+            } else if (NO.equals(rawValue.toUpperCase())) {
+                return Optional.of(Boolean.FALSE);
+            } else if (SKIP.equals(rawValue)) {
+                return Optional.absent();
+            } else {
+                final String message = String.format("Incorrect possibility (%s) was selected", rawValue);
+                Log.error(message);
+                throw new ReadingException(message);
+            }
+        } finally {
+            console.leaveContext();
+        }
+    }
+
+    private static ConsoleContext getContext() {
+        return new ConsoleContext() {
+
+            @Override
+            public Optional<String> getPrompt() {
+                return Optional.absent();
+            }
+
+            @Override
+            public Completer getCompleter() {
+                return new AggregateCompleter(YES_NO_COMPLETER, new StringsCompleter(IOUtil.SKIP));
+            }
+
+        };
+    }
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/GenericListReader.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/GenericListReader.java
new file mode 100644 (file)
index 0000000..6cf8eb2
--- /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.netconf.cli.reader.impl;
+
+import static org.opendaylight.controller.netconf.cli.io.IOUtil.listType;
+
+import com.google.common.base.Optional;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import org.opendaylight.controller.netconf.cli.io.BaseConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.cli.reader.AbstractReader;
+import org.opendaylight.controller.netconf.cli.reader.GenericListEntryReader;
+import org.opendaylight.controller.netconf.cli.reader.ReadingException;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class GenericListReader<T extends DataSchemaNode> extends AbstractReader<T> {
+    private static final Logger LOG = LoggerFactory.getLogger(GenericListReader.class);
+
+    private final GenericListEntryReader<T> concreteListEntryReader;
+
+    public GenericListReader(final ConsoleIO console, final GenericListEntryReader<T> concreteListEntryReader,
+            final SchemaContext schemaContext) {
+        super(console, schemaContext);
+        this.concreteListEntryReader = concreteListEntryReader;
+    }
+
+    public GenericListReader(final ConsoleIO console, final GenericListEntryReader<T> concreteListEntryReader,
+            final SchemaContext schemaContext, final boolean readConfigNode) {
+        super(console, schemaContext, readConfigNode);
+        this.concreteListEntryReader = concreteListEntryReader;
+    }
+
+    @Override
+    public List<Node<?>> readWithContext(final T schemaNode) throws IOException, ReadingException {
+        final List<Node<?>> newNodes = new ArrayList<>();
+        Optional<Boolean> readNextListEntry = Optional.of(Boolean.TRUE);
+        console.formatLn("Reading collection type argument: %s", schemaNode.getQName().getLocalName());
+        while (readNextListEntry.isPresent() && readNextListEntry.get()) {
+            try {
+                newNodes.addAll(concreteListEntryReader.read(schemaNode));
+            } catch (final ReadingException e) {
+                console.writeLn(e.getMessage());
+            }
+            readNextListEntry = new DecisionReader().read(console, "Add other entry to " + listType(schemaNode) + " "
+                    + schemaNode.getQName().getLocalName() + " " + " [Y|N]?");
+        }
+        console.formatLn("Collection type argument: %s read finished", schemaNode.getQName().getLocalName());
+
+        return newNodes;
+    }
+
+    @Override
+    protected ConsoleContext getContext(final T schemaNode) {
+        return new BaseConsoleContext<>(schemaNode);
+    }
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/GenericReader.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/GenericReader.java
new file mode 100644 (file)
index 0000000..8fbfbb7
--- /dev/null
@@ -0,0 +1,134 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.reader.impl;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import org.opendaylight.controller.netconf.cli.CommandArgHandlerRegistry;
+import org.opendaylight.controller.netconf.cli.commands.CommandConstants;
+import org.opendaylight.controller.netconf.cli.io.ConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.cli.reader.AbstractReader;
+import org.opendaylight.controller.netconf.cli.reader.GenericListEntryReader;
+import org.opendaylight.controller.netconf.cli.reader.Reader;
+import org.opendaylight.controller.netconf.cli.reader.ReadingException;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
+
+public class GenericReader extends AbstractReader<DataSchemaNode> {
+
+    private final CommandArgHandlerRegistry argumentHandlerRegistry;
+
+    public GenericReader(final ConsoleIO console, final CommandArgHandlerRegistry argumentHandlerRegistry,
+            final SchemaContext schemaContext) {
+        super(console, schemaContext);
+        this.argumentHandlerRegistry = argumentHandlerRegistry;
+    }
+
+    public GenericReader(final ConsoleIO console, final CommandArgHandlerRegistry argumentHandlerRegistry,
+            final SchemaContext schemaContext, final boolean readConfigNode) {
+        super(console, schemaContext, readConfigNode);
+        this.argumentHandlerRegistry = argumentHandlerRegistry;
+    }
+
+    @Override
+    protected List<Node<?>> readWithContext(final DataSchemaNode schemaNode) throws IOException, ReadingException {
+        final Optional<Class<? extends Reader<DataSchemaNode>>> customReaderClassOpt = tryGetCustomHandler(schemaNode);
+
+        if (customReaderClassOpt.isPresent()) {
+            // TODO resolve class cast of generic custom readers
+            final Reader<DataSchemaNode> customReaderInstance = (Reader<DataSchemaNode>) argumentHandlerRegistry
+                    .getCustomReader(customReaderClassOpt.get());
+            Preconditions.checkNotNull(customReaderInstance, "Unknown custom reader: %s", customReaderClassOpt.get());
+            return customReaderInstance.read(schemaNode);
+        } else {
+            return readGeneric(schemaNode);
+        }
+
+        // TODO reuse instances
+    }
+
+    private List<Node<?>> readGeneric(final DataSchemaNode schemaNode) throws ReadingException, IOException {
+        final List<Node<?>> newNodes = new ArrayList<>();
+        boolean isRedCorrectly = false;
+        do {
+            try {
+                if (schemaNode instanceof LeafSchemaNode) {
+                    return new LeafReader(console, getSchemaContext(), getReadConfigNode())
+                            .read((LeafSchemaNode) schemaNode);
+                } else if (schemaNode instanceof ContainerSchemaNode) {
+                    return new ContainerReader(console, argumentHandlerRegistry, getSchemaContext(),
+                            getReadConfigNode()).read((ContainerSchemaNode) schemaNode);
+                } else if (schemaNode instanceof ListSchemaNode) {
+                    final GenericListEntryReader<ListSchemaNode> entryReader = new ListEntryReader(console,
+                            argumentHandlerRegistry, getSchemaContext(), getReadConfigNode());
+                    return new GenericListReader<>(console, entryReader, getSchemaContext(), getReadConfigNode())
+                            .read((ListSchemaNode) schemaNode);
+                } else if (schemaNode instanceof LeafListSchemaNode) {
+                    final GenericListEntryReader<LeafListSchemaNode> entryReader = new LeafListEntryReader(console,
+                            getSchemaContext(), getReadConfigNode());
+                    return new GenericListReader<>(console, entryReader, getSchemaContext(), getReadConfigNode())
+                            .read((LeafListSchemaNode) schemaNode);
+                } else if (schemaNode instanceof ChoiceNode) {
+                    return new ChoiceReader(console, argumentHandlerRegistry, getSchemaContext(), getReadConfigNode())
+                            .read((ChoiceNode) schemaNode);
+                } else if (schemaNode instanceof AnyXmlSchemaNode) {
+                    return new AnyXmlReader(console, getSchemaContext(), getReadConfigNode())
+                            .read((AnyXmlSchemaNode) schemaNode);
+                }
+                isRedCorrectly = true;
+            } catch (final ReadingException e) {
+                console.writeLn(e.getMessage());
+            }
+        } while (!isRedCorrectly);
+        return newNodes;
+    }
+
+    @Override
+    protected ConsoleContext getContext(final DataSchemaNode schemaNode) {
+        // return null context, leave context to specific implementations
+        return NULL_CONTEXT;
+    }
+
+    private <T> Optional<Class<? extends T>> tryGetCustomHandler(final DataSchemaNode dataSchemaNode) {
+
+        for (final UnknownSchemaNode unknownSchemaNode : dataSchemaNode.getUnknownSchemaNodes()) {
+
+            if (isExtenstionForCustomHandler(unknownSchemaNode)) {
+                final String argumentHandlerClassName = unknownSchemaNode.getNodeParameter();
+                try {
+                    final Class<?> argumentClass = Class.forName(argumentHandlerClassName);
+                    // TODO add check before cast
+                    return Optional.<Class<? extends T>> of((Class<? extends T>) argumentClass);
+                } catch (final ClassNotFoundException e) {
+                    throw new IllegalArgumentException("Unknown custom reader class " + argumentHandlerClassName
+                            + " for: " + dataSchemaNode.getQName());
+                }
+            }
+        }
+
+        return Optional.absent();
+    }
+
+    private boolean isExtenstionForCustomHandler(final UnknownSchemaNode unknownSchemaNode) {
+        final QName qName = unknownSchemaNode.getExtensionDefinition().getQName();
+        return qName.equals(CommandConstants.ARG_HANDLER_EXT_QNAME);
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/LeafListEntryReader.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/LeafListEntryReader.java
new file mode 100644 (file)
index 0000000..4ba3478
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.reader.impl;
+
+import com.google.common.base.Optional;
+import com.google.common.collect.Lists;
+import java.util.List;
+import jline.console.completer.Completer;
+import org.opendaylight.controller.netconf.cli.io.BaseConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.cli.reader.GenericListEntryReader;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+
+class LeafListEntryReader extends BasicDataHolderReader<LeafListSchemaNode> implements
+        GenericListEntryReader<LeafListSchemaNode> {
+
+    public LeafListEntryReader(final ConsoleIO console, final SchemaContext schemaContext) {
+        super(console, schemaContext);
+    }
+
+    public LeafListEntryReader(final ConsoleIO console, final SchemaContext schemaContext, final boolean readConfigNode) {
+        super(console, schemaContext, readConfigNode);
+    }
+
+    @Override
+    protected TypeDefinition<?> getType(final LeafListSchemaNode schemaNode) {
+        return schemaNode.getType();
+    }
+
+    @Override
+    protected ConsoleContext getContext(final LeafListSchemaNode schemaNode) {
+        return new BaseConsoleContext<LeafListSchemaNode>(schemaNode) {
+
+            @Override
+            public Optional<String> getPrompt() {
+                return Optional.of("[entry]");
+            }
+
+            @Override
+            protected List<Completer> getAdditionalCompleters() {
+                return Lists.<Completer> newArrayList(getBaseCompleter(getDataSchemaNode()));
+            }
+        };
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/LeafReader.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/LeafReader.java
new file mode 100644 (file)
index 0000000..9a847f6
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.reader.impl;
+
+import com.google.common.base.Optional;
+import com.google.common.collect.Lists;
+import java.util.List;
+import jline.console.completer.Completer;
+import jline.console.completer.StringsCompleter;
+import org.opendaylight.controller.netconf.cli.io.BaseConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+
+public class LeafReader extends BasicDataHolderReader<LeafSchemaNode> {
+
+    public LeafReader(final ConsoleIO console, final SchemaContext schemaContext) {
+        super(console, schemaContext);
+    }
+
+    public LeafReader(final ConsoleIO console, final SchemaContext schemaContext, final boolean readConfigNode) {
+        super(console, schemaContext, readConfigNode);
+    }
+
+    @Override
+    protected TypeDefinition<?> getType(final LeafSchemaNode schemaNode) {
+        return schemaNode.getType();
+    }
+
+    @Override
+    protected ConsoleContext getContext(final LeafSchemaNode schemaNode) {
+        return new BaseConsoleContext<LeafSchemaNode>(schemaNode) {
+            @Override
+            public List<Completer> getAdditionalCompleters() {
+                final List<Completer> completers = Lists.<Completer> newArrayList(getBaseCompleter(schemaNode));
+                final Optional<String> defaultValue = getDefaultValue(schemaNode);
+                if (defaultValue.isPresent()) {
+                    completers.add(new StringsCompleter(defaultValue.get()));
+                }
+                return completers;
+            }
+        };
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/ListEntryReader.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/ListEntryReader.java
new file mode 100644 (file)
index 0000000..97f7694
--- /dev/null
@@ -0,0 +1,143 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.reader.impl;
+
+import com.google.common.base.Function;
+import com.google.common.base.Optional;
+import com.google.common.collect.Collections2;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import org.opendaylight.controller.netconf.cli.CommandArgHandlerRegistry;
+import org.opendaylight.controller.netconf.cli.io.BaseConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.cli.reader.AbstractReader;
+import org.opendaylight.controller.netconf.cli.reader.GenericListEntryReader;
+import org.opendaylight.controller.netconf.cli.reader.ReadingException;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
+import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+class ListEntryReader extends AbstractReader<ListSchemaNode> implements GenericListEntryReader<ListSchemaNode> {
+    private static final Logger LOG = LoggerFactory.getLogger(ListEntryReader.class);
+
+    private final CommandArgHandlerRegistry argumentHandlerRegistry;
+
+    public ListEntryReader(final ConsoleIO console, final CommandArgHandlerRegistry argumentHandlerRegistry,
+            final SchemaContext schemaContext) {
+        super(console, schemaContext);
+        this.argumentHandlerRegistry = argumentHandlerRegistry;
+    }
+
+    public ListEntryReader(final ConsoleIO console, final CommandArgHandlerRegistry argumentHandlerRegistry,
+            final SchemaContext schemaContext, final boolean readConfigNode) {
+        super(console, schemaContext, readConfigNode);
+        this.argumentHandlerRegistry = argumentHandlerRegistry;
+    }
+
+    @Override
+    public List<Node<?>> readWithContext(final ListSchemaNode listNode) throws IOException, ReadingException {
+        console.formatLn("Submit child nodes for list entry: %s, %s", listNode.getQName().getLocalName(),
+                Collections2.transform(listNode.getChildNodes(), new Function<DataSchemaNode, String>() {
+                    @Override
+                    public String apply(final DataSchemaNode input) {
+                        return input.getQName().getLocalName();
+                    }
+                }));
+
+        final String listName = listNode.getQName().getLocalName();
+        final CompositeNodeBuilder<ImmutableCompositeNode> compositeNodeBuilder = ImmutableCompositeNode.builder();
+        compositeNodeBuilder.setQName(listNode.getQName());
+
+        final SeparatedNodes separatedChildNodes = SeparatedNodes.separateNodes(listNode, getReadConfigNode());
+
+        final List<Node<?>> nodes = readKeys(separatedChildNodes.getKeyNodes());
+        nodes.addAll(readMandatoryNotKeys(separatedChildNodes.getMandatoryNotKey()));
+        if (!separatedChildNodes.getOthers().isEmpty()) {
+            final Optional<Boolean> readNodesWhichAreNotKey = new DecisionReader().read(console,
+                    "Add non-key, non-mandatory nodes to list %s? [Y|N]", listName);
+            if (readNodesWhichAreNotKey.isPresent() && readNodesWhichAreNotKey.get()) {
+                nodes.addAll(readNotKeys(separatedChildNodes.getOthers()));
+            }
+        }
+
+        if (!nodes.isEmpty()) {
+            compositeNodeBuilder.addAll(nodes);
+            return Collections.<Node<?>> singletonList(compositeNodeBuilder.toInstance());
+        } else {
+            return Collections.emptyList();
+        }
+    }
+
+    private List<Node<?>> readKeys(final Set<DataSchemaNode> keys) throws ReadingException, IOException {
+        final List<Node<?>> newNodes = new ArrayList<>();
+        console.writeLn("Reading keys:");
+        for (final DataSchemaNode key : keys) {
+            final List<Node<?>> readKey = new LeafReader(console, getSchemaContext(), getReadConfigNode())
+                    .read((LeafSchemaNode) key);
+            if (readKey.size() != 1) {
+                final String message = String.format(
+                        "Value for key element %s has to be set. Creation of this entry is canceled.", key.getQName()
+                                .getLocalName());
+                LOG.error(message);
+                throw new ReadingException(message);
+            }
+            newNodes.addAll(readKey);
+        }
+        return newNodes;
+    }
+
+    private List<Node<?>> readMandatoryNotKeys(final Set<DataSchemaNode> mandatoryNotKeys) throws ReadingException,
+            IOException {
+        final List<Node<?>> newNodes = new ArrayList<>();
+        console.writeLn("Reading mandatory not keys nodes:");
+
+        for (final DataSchemaNode mandatoryNode : mandatoryNotKeys) {
+            final List<Node<?>> redValue = argumentHandlerRegistry.getGenericReader(getSchemaContext(),
+                    getReadConfigNode()).read(mandatoryNode);
+            if (redValue.isEmpty()) {
+                final String message = String.format(
+                        "Value for mandatory element %s has to be set. Creation of this entry is canceled.",
+                        mandatoryNode.getQName().getLocalName());
+                LOG.error(message);
+                throw new ReadingException(message);
+            }
+            newNodes.addAll(redValue);
+        }
+        return newNodes;
+    }
+
+    private List<Node<?>> readNotKeys(final Set<DataSchemaNode> notKeys) throws ReadingException {
+        final List<Node<?>> newNodes = new ArrayList<>();
+        for (final DataSchemaNode notKey : notKeys) {
+            newNodes.addAll(argumentHandlerRegistry.getGenericReader(getSchemaContext(), getReadConfigNode()).read(
+                    notKey));
+        }
+        return newNodes;
+    }
+
+    @Override
+    protected ConsoleContext getContext(final ListSchemaNode schemaNode) {
+        return new BaseConsoleContext<ListSchemaNode>(schemaNode) {
+            @Override
+            public Optional<String> getPrompt() {
+                return Optional.of("[entry]");
+            }
+        };
+    }
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/SeparatedNodes.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/SeparatedNodes.java
new file mode 100644 (file)
index 0000000..e05f786
--- /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.netconf.cli.reader.impl;
+
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+class SeparatedNodes {
+    private final Set<DataSchemaNode> keyNodes;
+    private final Set<DataSchemaNode> mandatoryNotKey;
+    private final Set<DataSchemaNode> otherNodes;
+
+    public SeparatedNodes(final Set<DataSchemaNode> keyNodes, final Set<DataSchemaNode> mandatoryNotKey,
+            final Set<DataSchemaNode> otherNodes) {
+        this.keyNodes = keyNodes;
+        this.mandatoryNotKey = mandatoryNotKey;
+        this.otherNodes = otherNodes;
+    }
+
+    public Set<DataSchemaNode> getKeyNodes() {
+        return keyNodes;
+    }
+
+    public Set<DataSchemaNode> getMandatoryNotKey() {
+        return mandatoryNotKey;
+    }
+
+    public Set<DataSchemaNode> getOthers() {
+        return otherNodes;
+    }
+
+    static SeparatedNodes separateNodes(final DataNodeContainer dataNodeContainer) {
+        return separateNodes(dataNodeContainer, false);
+    }
+
+    static SeparatedNodes separateNodes(final DataNodeContainer dataNodeContainer, final boolean removeConfigFalseNodes) {
+        final Set<DataSchemaNode> keys = new HashSet<>();
+        final Set<DataSchemaNode> mandatoryNotKeys = new HashSet<>();
+        final Set<DataSchemaNode> others = new HashSet<>();
+
+        List<QName> keyQNames = Collections.emptyList();
+        if (dataNodeContainer instanceof ListSchemaNode) {
+            keyQNames = ((ListSchemaNode) dataNodeContainer).getKeyDefinition();
+        }
+
+        for (final DataSchemaNode dataSchemaNode : dataNodeContainer.getChildNodes()) {
+            if (removeConfigFalseNodes) {
+                if (!dataSchemaNode.isConfiguration()) {
+                    continue;
+                }
+            }
+            if (keyQNames.contains(dataSchemaNode.getQName())) {
+                Preconditions.checkArgument(dataSchemaNode instanceof LeafSchemaNode);
+                keys.add(dataSchemaNode);
+            } else if (dataSchemaNode.getConstraints().isMandatory()) {
+                mandatoryNotKeys.add(dataSchemaNode);
+            } else {
+                others.add(dataSchemaNode);
+            }
+        }
+
+        return new SeparatedNodes(keys, mandatoryNotKeys, others);
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/UnionTypeReader.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/reader/impl/UnionTypeReader.java
new file mode 100644 (file)
index 0000000..e2d186b
--- /dev/null
@@ -0,0 +1,126 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.reader.impl;
+
+import static org.opendaylight.controller.netconf.cli.io.IOUtil.isSkipInput;
+
+import com.google.common.base.Optional;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import jline.console.completer.AggregateCompleter;
+import jline.console.completer.Completer;
+import jline.console.completer.StringsCompleter;
+import org.opendaylight.controller.netconf.cli.io.ConsoleContext;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.cli.io.IOUtil;
+import org.opendaylight.controller.netconf.cli.reader.ReadingException;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+class UnionTypeReader {
+    private static final Logger LOG = LoggerFactory.getLogger(UnionTypeReader.class);
+
+    private final ConsoleIO console;
+
+    public UnionTypeReader(final ConsoleIO console) {
+        this.console = console;
+    }
+
+    public Optional<TypeDefinition<?>> read(final TypeDefinition<?> unionTypeDefinition) throws IOException,
+            ReadingException {
+        final ConsoleContext context = getContext(unionTypeDefinition);
+        console.enterContext(context);
+        try {
+            final Map<String, TypeDefinition<?>> mapping = ((UnionConsoleContext) context).getMenuItemMapping();
+            console.formatLn("The element is of type union. Choose concrete type from: %s", mapping.keySet());
+
+            final String rawValue = console.read();
+            if (isSkipInput(rawValue)) {
+                return Optional.absent();
+            }
+            final TypeDefinition<?> value = mapping.get(rawValue);
+            if (value != null) {
+                return Optional.<TypeDefinition<?>> of(value);
+            } else {
+                final String message = String.format("Incorrect type (%s) was specified for union type definition", rawValue);
+                LOG.error(message);
+                throw new ReadingException(message);
+            }
+        } finally {
+            console.leaveContext();
+        }
+    }
+
+    private UnionConsoleContext getContext(final TypeDefinition<?> typeDefinition) {
+        return new UnionConsoleContext(typeDefinition);
+    }
+
+    private class UnionConsoleContext implements ConsoleContext {
+
+        private final TypeDefinition<?> typeDef;
+        private final Map<String, TypeDefinition<?>> menuItemsToTypeDefinitions = new HashMap<>();
+
+        public UnionConsoleContext(final TypeDefinition<?> typeDef) {
+            this.typeDef = typeDef;
+        }
+
+        @Override
+        public Optional<String> getPrompt() {
+            return Optional.of("type[" + typeDef.getQName().getLocalName()  + "]");
+        }
+
+        @Override
+        public Completer getCompleter() {
+            List<TypeDefinition<?>> subtypesForMenu = resolveSubtypesFrom(typeDef);
+            if (subtypesForMenu.isEmpty()) {
+                subtypesForMenu = Collections.<TypeDefinition<?>> singletonList(typeDef);
+            }
+            final Collection<String> menuItems = toMenuItem(subtypesForMenu);
+            return new AggregateCompleter(new StringsCompleter(menuItems), new StringsCompleter(IOUtil.SKIP));
+        }
+
+        public Map<String, TypeDefinition<?>> getMenuItemMapping() {
+            return menuItemsToTypeDefinitions;
+        }
+
+        private Collection<String> toMenuItem(final List<TypeDefinition<?>> allTypesBehindUnion) {
+            final List<String> result = new ArrayList<String>();
+            for (final TypeDefinition<?> type : allTypesBehindUnion) {
+                final String menuItem = type.getQName().getLocalName();
+                menuItemsToTypeDefinitions.put(menuItem, type);
+                result.add(menuItem);
+            }
+            return result;
+        }
+
+        /**
+         *
+         * If union type is found in potentialEndTypeCandidate as subtype then
+         * it these subtypes become candidates.
+         *
+         * @param potentialEndTypeCandidate
+         *            candidate to node which has no union subtype
+         */
+        private List<TypeDefinition<?>> resolveSubtypesFrom(final TypeDefinition<?> potentialEndTypeCandidate) {
+            if (potentialEndTypeCandidate instanceof UnionTypeDefinition) {
+                return ((UnionTypeDefinition) potentialEndTypeCandidate).getTypes();
+            }
+            if (potentialEndTypeCandidate.getBaseType() == null) {
+                return Collections.emptyList();
+            }
+            return resolveSubtypesFrom(potentialEndTypeCandidate.getBaseType());
+        }
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/OutFormatter.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/OutFormatter.java
new file mode 100644 (file)
index 0000000..bed27b4
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.writer;
+
+public class OutFormatter {
+
+    public static final String INDENT_STEP = "  ";
+    public static final String COMPOSITE_OPEN_NODE = " {";
+    public static final String COMPOSITE_CLOSE_NODE = "}";
+    public static final String NEW_LINE = "\n";
+
+    int indentLevel = -1;
+    private String currentIndent = "";
+
+    public OutFormatter indent(final StringBuilder buffer) {
+        buffer.append(currentIndent);
+        return this;
+    }
+
+    public OutFormatter openComposite(final StringBuilder buffer) {
+        buffer.append(COMPOSITE_OPEN_NODE);
+        return this;
+    }
+
+    public OutFormatter closeCompositeWithIndent(final StringBuilder buffer) {
+        buffer.append(currentIndent);
+        buffer.append(COMPOSITE_CLOSE_NODE);
+        return this;
+    }
+
+    public OutFormatter newLine(final StringBuilder buffer) {
+        buffer.append(NEW_LINE);
+        return this;
+    }
+
+    private void prepareIndent() {
+        final StringBuilder output = new StringBuilder();
+        for (int i = 0; i < indentLevel; i++) {
+            output.append(INDENT_STEP);
+        }
+        currentIndent = output.toString();
+    }
+
+    public OutFormatter increaseIndent() {
+        indentLevel++;
+        prepareIndent();
+        return this;
+    }
+
+    public OutFormatter decreaseIndent() {
+        indentLevel--;
+        prepareIndent();
+        return this;
+    }
+
+    public OutFormatter addStringWithIndent(final StringBuilder buffer, final String value) {
+        indent(buffer);
+        buffer.append(value);
+        return this;
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/WriteException.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/WriteException.java
new file mode 100644 (file)
index 0000000..b2cc456
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.writer;
+
+public class WriteException extends Exception {
+
+    private static final long serialVersionUID = 8401242676753560336L;
+
+    public WriteException(final String msg, final Exception e) {
+        super(msg, e);
+    }
+
+    public WriteException(final String msg) {
+        super(msg);
+    }
+
+    public static class IncorrectNumberOfNodes extends WriteException {
+        private static final long serialVersionUID = 8910285140705622920L;
+
+        public IncorrectNumberOfNodes(final String msg) {
+            super(msg);
+        }
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/Writer.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/Writer.java
new file mode 100644 (file)
index 0000000..ba3d876
--- /dev/null
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.writer;
+
+import java.util.List;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+
+/**
+ * Generic handler(writer) of output elements for commands
+ */
+public interface Writer<T extends DataSchemaNode> {
+
+    void write(T dataSchemaNode, List<Node<?>> dataNodes) throws WriteException;
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/custom/DataWriter.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/custom/DataWriter.java
new file mode 100644 (file)
index 0000000..3724ecb
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.writer.custom;
+
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.cli.writer.OutFormatter;
+import org.opendaylight.controller.netconf.cli.writer.WriteException;
+import org.opendaylight.controller.netconf.cli.writer.impl.AbstractWriter;
+import org.opendaylight.controller.netconf.cli.writer.impl.NormalizedNodeWriter;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+public class DataWriter extends AbstractWriter<DataSchemaNode> {
+
+    private final OutFormatter out;
+    private final SchemaContext remoteSchemaContext;
+
+    public DataWriter(final ConsoleIO console, final OutFormatter out, final SchemaContext remoteSchemaContext) {
+        super(console);
+        this.out = out;
+        this.remoteSchemaContext = remoteSchemaContext;
+    }
+
+    @Override
+    protected void writeInner(final DataSchemaNode dataSchemaNode, final List<Node<?>> dataNodes) throws IOException, WriteException {
+        Preconditions.checkArgument(dataNodes.size() == 1, "Expected only 1 element for data node");
+        final Node<?> dataNode = dataNodes.get(0);
+        Preconditions.checkArgument(dataNode instanceof CompositeNode, "Unexpected node type: %s, should be %s", dataNode, CompositeNode.class);
+
+        StringBuilder output = new StringBuilder();
+        out.increaseIndent().addStringWithIndent(output, dataSchemaNode.getQName().getLocalName()).openComposite(output);
+        console.writeLn(output.toString());
+
+        for (final Node<?> childNode : ((CompositeNode) dataNode).getValue()) {
+            final Optional<DataSchemaNode> schemaNode = XmlDocumentUtils.findFirstSchema(childNode.getNodeType(), remoteSchemaContext.getDataDefinitions());
+            Preconditions.checkState(schemaNode.isPresent(), "Unknown data node %s, not defined in schema", childNode.getNodeType());
+            new NormalizedNodeWriter(console, out).write(schemaNode.get(), Collections.<Node<?>>singletonList(childNode));
+        }
+
+        output = new StringBuilder();
+        out.decreaseIndent().closeCompositeWithIndent(output);
+        console.writeLn(output.toString());
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/AbstractWriter.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/AbstractWriter.java
new file mode 100644 (file)
index 0000000..f9c4e84
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.writer.impl;
+
+import java.io.IOException;
+import java.util.List;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.cli.writer.WriteException;
+import org.opendaylight.controller.netconf.cli.writer.Writer;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+
+public abstract class AbstractWriter<T extends DataSchemaNode> implements Writer<T> {
+
+    protected ConsoleIO console;
+
+    public AbstractWriter(final ConsoleIO console) {
+        this.console = console;
+    }
+
+    @Override
+    public void write(final T dataSchemaNode, final List<Node<?>> dataNodes) throws WriteException {
+        try {
+            writeInner(dataSchemaNode, dataNodes);
+        } catch (final IOException e) {
+            throw new WriteException("Unable to write data to output for " + dataSchemaNode.getQName(), e);
+        }
+    }
+
+    protected abstract void writeInner(final T dataSchemaNode, final List<Node<?>> dataNodes) throws IOException,
+            WriteException;
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/AugmentationNodeCliSerializer.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/AugmentationNodeCliSerializer.java
new file mode 100644 (file)
index 0000000..626bc4e
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.writer.impl;
+
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import org.opendaylight.controller.netconf.cli.writer.OutFormatter;
+import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.AugmentationNodeBaseSerializer;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+final class AugmentationNodeCliSerializer extends AugmentationNodeBaseSerializer<String> {
+
+    private final NodeSerializerDispatcher<String> dispatcher;
+    private final OutFormatter out;
+
+    AugmentationNodeCliSerializer(final OutFormatter out, final NodeSerializerDispatcher<String> dispatcher) {
+        this.out = Preconditions.checkNotNull(out);
+        this.dispatcher = Preconditions.checkNotNull(dispatcher);
+    }
+
+    @Override
+    public Iterable<String> serialize(final AugmentationSchema schema, final AugmentationNode node) {
+        final StringBuilder output = new StringBuilder();
+        out.increaseIndent();
+        out.addStringWithIndent(output, "augment");
+        out.openComposite(output);
+        out.newLine(output);
+
+        for (final String childOutput : super.serialize(schema, node)) {
+            output.append(childOutput);
+            out.newLine(output);
+        }
+
+        out.closeCompositeWithIndent(output);
+        out.decreaseIndent();
+        return Collections.singletonList(output.toString());
+    }
+
+    @Override
+    protected NodeSerializerDispatcher<String> getNodeDispatcher() {
+        return dispatcher;
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/ChoiceNodeCliSerializer.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/ChoiceNodeCliSerializer.java
new file mode 100644 (file)
index 0000000..62845ad
--- /dev/null
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.writer.impl;
+
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import org.opendaylight.controller.netconf.cli.writer.OutFormatter;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.ChoiceNodeBaseSerializer;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
+import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+
+final class ChoiceNodeCliSerializer extends ChoiceNodeBaseSerializer<String> {
+    private final NodeSerializerDispatcher<String> dispatcher;
+    private final OutFormatter out;
+
+    ChoiceNodeCliSerializer(final OutFormatter out, final NodeSerializerDispatcher<String> dispatcher) {
+        this.out = Preconditions.checkNotNull(out);
+        this.dispatcher = Preconditions.checkNotNull(dispatcher);
+    }
+
+    @Override
+    public Iterable<String> serialize(final ChoiceNode schema, final org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode node) {
+        final StringBuilder output = new StringBuilder();
+        out.increaseIndent();
+        out.addStringWithIndent(output, "choice ");
+        output.append(schema.getQName().getLocalName());
+        output.append(" (");
+        output.append(detectCase(schema, node));
+        output.append(") ");
+        out.openComposite(output);
+        out.newLine(output);
+
+        for (final String childOutput : super.serialize(schema, node)) {
+            output.append(childOutput);
+            out.newLine(output);
+        }
+
+        out.closeCompositeWithIndent(output);
+        out.decreaseIndent();
+        return Collections.singletonList(output.toString());
+    }
+
+    private String detectCase(final ChoiceNode schema, final org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode node) {
+        for (final DataContainerChild<? extends PathArgument, ?> caseChild : node.getValue()) {
+            final QName presentChildQName = caseChild.getNodeType();
+            for (final ChoiceCaseNode choiceCaseNode : schema.getCases()) {
+                if (choiceCaseNode.getDataChildByName(presentChildQName) != null) {
+                    // Pick the first case that contains first child node
+                    return choiceCaseNode.getQName().getLocalName();
+                }
+            }
+        }
+
+        // Should not happen, nodes should come from one of the cases
+        throw new IllegalStateException("Choice node " + node + " does not conform to choice schema " + schema);
+    }
+
+    @Override
+    protected NodeSerializerDispatcher<String> getNodeDispatcher() {
+        return dispatcher;
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/CliOutputFromNormalizedNodeSerializerFactory.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/CliOutputFromNormalizedNodeSerializerFactory.java
new file mode 100644 (file)
index 0000000..cab07af
--- /dev/null
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.writer.impl;
+
+import org.opendaylight.controller.netconf.cli.writer.OutFormatter;
+import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
+import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
+import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
+import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
+import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlCodecProvider;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializer;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializerFactory;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+public final class CliOutputFromNormalizedNodeSerializerFactory implements FromNormalizedNodeSerializerFactory<String> {
+    private final ContainerNodeCliSerializer containerSerializer;
+    private final ChoiceNodeCliSerializer choiceSerializer;
+    private final AugmentationNodeCliSerializer augmentSerializer;
+    private final LeafNodeCliSerializer leafNodeSerializer;
+    private final LeafSetNodeCliSerializer leafSetSerializer;
+    private final MapNodeCliSerializer mapNodeSerializer;
+    private final LeafSetEntryNodeCliSerializer leafSetEntryNodeSerializer;
+    private final MapEntryNodeCliSerializer mapEntryNodeSerializer;
+    final NodeSerializerDispatcher<String> dispatcher = new NodeCliSerializerDispatcher(this);
+
+    private CliOutputFromNormalizedNodeSerializerFactory(final OutFormatter out, final XmlCodecProvider codecProvider) {
+
+        containerSerializer = new ContainerNodeCliSerializer(out, dispatcher);
+        choiceSerializer = new ChoiceNodeCliSerializer(out, dispatcher);
+        augmentSerializer = new AugmentationNodeCliSerializer(out, dispatcher);
+        leafNodeSerializer = new LeafNodeCliSerializer(out);
+
+        leafSetEntryNodeSerializer = new LeafSetEntryNodeCliSerializer(out);
+        leafSetSerializer = new LeafSetNodeCliSerializer(out, leafSetEntryNodeSerializer);
+
+        mapEntryNodeSerializer = new MapEntryNodeCliSerializer(out, dispatcher);
+        mapNodeSerializer = new MapNodeCliSerializer(out, mapEntryNodeSerializer);
+    }
+
+    public NodeSerializerDispatcher<String> getDispatcher() {
+        return dispatcher;
+    }
+
+    public static CliOutputFromNormalizedNodeSerializerFactory getInstance(final OutFormatter out,
+            final XmlCodecProvider codecProvider) {
+        return new CliOutputFromNormalizedNodeSerializerFactory(out, codecProvider);
+    }
+
+    @Override
+    public FromNormalizedNodeSerializer<String, AugmentationNode, AugmentationSchema> getAugmentationNodeSerializer() {
+        return augmentSerializer;
+    }
+
+    @Override
+    public FromNormalizedNodeSerializer<String, ChoiceNode, org.opendaylight.yangtools.yang.model.api.ChoiceNode> getChoiceNodeSerializer() {
+        return choiceSerializer;
+    }
+
+    @Override
+    public FromNormalizedNodeSerializer<String, ContainerNode, ContainerSchemaNode> getContainerNodeSerializer() {
+        return containerSerializer;
+    }
+
+    @Override
+    public FromNormalizedNodeSerializer<String, LeafNode<?>, LeafSchemaNode> getLeafNodeSerializer() {
+        return leafNodeSerializer;
+    }
+
+    @Override
+    public FromNormalizedNodeSerializer<String, LeafSetEntryNode<?>, LeafListSchemaNode> getLeafSetEntryNodeSerializer() {
+        return leafSetEntryNodeSerializer;
+    }
+
+    @Override
+    public FromNormalizedNodeSerializer<String, LeafSetNode<?>, LeafListSchemaNode> getLeafSetNodeSerializer() {
+        return leafSetSerializer;
+    }
+
+    @Override
+    public FromNormalizedNodeSerializer<String, MapEntryNode, ListSchemaNode> getMapEntryNodeSerializer() {
+        return mapEntryNodeSerializer;
+    }
+
+    @Override
+    public FromNormalizedNodeSerializer<String, MapNode, ListSchemaNode> getMapNodeSerializer() {
+        return mapNodeSerializer;
+    }
+
+}
\ No newline at end of file
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/CompositeNodeWriter.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/CompositeNodeWriter.java
new file mode 100644 (file)
index 0000000..57d8f57
--- /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.netconf.cli.writer.impl;
+
+import java.io.IOException;
+import java.util.List;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.cli.writer.OutFormatter;
+import org.opendaylight.controller.netconf.cli.writer.WriteException;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.data.api.SimpleNode;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+
+public class CompositeNodeWriter extends AbstractWriter<DataSchemaNode> {
+
+    private final OutFormatter outFormatter;
+
+    public CompositeNodeWriter(final ConsoleIO console, final OutFormatter outFormatter) {
+        super(console);
+        this.outFormatter = outFormatter;
+    }
+
+    @Override
+    protected void writeInner(final DataSchemaNode dataSchemaNode, final List<Node<?>> dataNodes) throws IOException, WriteException {
+        final StringBuilder output = new StringBuilder();
+        writeNode(dataNodes, output);
+        console.writeLn(output);
+    }
+
+    private void writeNode(final List<Node<?>> dataNodes, final StringBuilder output) throws IOException, WriteException {
+        for (final Node<?> dataNode : dataNodes) {
+            outFormatter.increaseIndent();
+            outFormatter.addStringWithIndent(output, dataNode.getNodeType().getLocalName());
+            if (dataNode instanceof CompositeNode) {
+                outFormatter.openComposite(output);
+                outFormatter.newLine(output);
+                writeNode(((CompositeNode) dataNode).getValue(), output);
+                outFormatter.closeCompositeWithIndent(output);
+                outFormatter.newLine(output);
+            } else if (dataNode instanceof SimpleNode<?>) {
+                final SimpleNode<?> simpleNode = (SimpleNode<?>) dataNode;
+                output.append(" ");
+                output.append(simpleNode.getValue());
+                outFormatter.newLine(output);
+            }
+            outFormatter.decreaseIndent();
+        }
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/ContainerNodeCliSerializer.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/ContainerNodeCliSerializer.java
new file mode 100644 (file)
index 0000000..62b995e
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.writer.impl;
+
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import org.opendaylight.controller.netconf.cli.writer.OutFormatter;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.ContainerNodeBaseSerializer;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+
+final class ContainerNodeCliSerializer extends ContainerNodeBaseSerializer<String> {
+
+    private final NodeSerializerDispatcher<String> dispatcher;
+    private final OutFormatter out;
+
+    ContainerNodeCliSerializer(final OutFormatter out, final NodeSerializerDispatcher<String> dispatcher) {
+        this.out = Preconditions.checkNotNull(out);
+        this.dispatcher = Preconditions.checkNotNull(dispatcher);
+    }
+
+    @Override
+    public Iterable<String> serialize(final ContainerSchemaNode schema, final ContainerNode containerNode) {
+        final StringBuilder output = new StringBuilder();
+        out.increaseIndent();
+        out.addStringWithIndent(output, containerNode.getNodeType().getLocalName());
+        out.openComposite(output);
+        out.newLine(output);
+
+        for (final String childOutput : super.serialize(schema, containerNode)) {
+            output.append(childOutput);
+            out.newLine(output);
+        }
+
+        out.closeCompositeWithIndent(output);
+        out.decreaseIndent();
+        return Collections.singletonList(output.toString());
+    }
+
+    @Override
+    protected NodeSerializerDispatcher<String> getNodeDispatcher() {
+        return dispatcher;
+    }
+
+}
\ No newline at end of file
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/LeafNodeCliSerializer.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/LeafNodeCliSerializer.java
new file mode 100644 (file)
index 0000000..d3216c2
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.writer.impl;
+
+import com.google.common.base.Preconditions;
+import org.opendaylight.controller.netconf.cli.writer.OutFormatter;
+import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.LeafNodeBaseSerializer;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+
+final class LeafNodeCliSerializer extends LeafNodeBaseSerializer<String> {
+    private final OutFormatter out;
+
+    LeafNodeCliSerializer(final OutFormatter out) {
+        this.out = Preconditions.checkNotNull(out);
+    }
+
+    @Override
+    public String serializeLeaf(final LeafSchemaNode schema, final LeafNode<?> node) {
+        final StringBuilder output = new StringBuilder();
+        out.increaseIndent();
+        out.addStringWithIndent(output, node.getNodeType().getLocalName());
+        output.append(" ");
+        output.append(node.getValue());
+        out.decreaseIndent();
+        return output.toString();
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/LeafSetEntryNodeCliSerializer.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/LeafSetEntryNodeCliSerializer.java
new file mode 100644 (file)
index 0000000..4937432
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.writer.impl;
+
+import org.opendaylight.controller.netconf.cli.writer.OutFormatter;
+import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.LeafSetEntryNodeBaseSerializer;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+
+final class LeafSetEntryNodeCliSerializer extends LeafSetEntryNodeBaseSerializer<String> {
+
+    private final OutFormatter out;
+
+    public LeafSetEntryNodeCliSerializer(final OutFormatter out) {
+        this.out = out;
+    }
+
+    @Override
+    protected String serializeLeaf(final LeafListSchemaNode schema, final LeafSetEntryNode<?> node) {
+        final StringBuilder output = new StringBuilder();
+        out.increaseIndent();
+        out.addStringWithIndent(output, node.getValue().toString());
+        out.decreaseIndent();
+        return output.toString();
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/LeafSetNodeCliSerializer.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/LeafSetNodeCliSerializer.java
new file mode 100644 (file)
index 0000000..8d618e8
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.writer.impl;
+
+import java.util.Collections;
+import org.opendaylight.controller.netconf.cli.writer.OutFormatter;
+import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializer;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+
+final class LeafSetNodeCliSerializer implements
+        FromNormalizedNodeSerializer<String, LeafSetNode<?>, LeafListSchemaNode> {
+    private final LeafSetEntryNodeCliSerializer leafSetEntryNodeSerializer;
+    private final OutFormatter out;
+
+    LeafSetNodeCliSerializer(final OutFormatter out, final LeafSetEntryNodeCliSerializer leafSetEntryNodeSerializer) {
+        this.out = out;
+        this.leafSetEntryNodeSerializer = leafSetEntryNodeSerializer;
+    }
+
+    @Override
+    public Iterable<String> serialize(final LeafListSchemaNode schema, final LeafSetNode<?> node) {
+        final StringBuilder output = new StringBuilder();
+        out.increaseIndent();
+        out.addStringWithIndent(output, node.getNodeType().getLocalName());
+        out.openComposite(output);
+        out.newLine(output);
+        for (final LeafSetEntryNode<?> leafEntryNode : node.getValue()) {
+            final Iterable<String> valueFromLeafSetEntry = leafSetEntryNodeSerializer.serialize(schema, leafEntryNode);
+            output.append(valueFromLeafSetEntry.iterator().next());
+            out.newLine(output);
+        }
+        out.closeCompositeWithIndent(output);
+        out.decreaseIndent();
+        return Collections.singletonList(output.toString());
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/MapEntryNodeCliSerializer.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/MapEntryNodeCliSerializer.java
new file mode 100644 (file)
index 0000000..15f86a7
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.writer.impl;
+
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Map.Entry;
+import org.opendaylight.controller.netconf.cli.writer.OutFormatter;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.MapEntryNodeBaseSerializer;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+final class MapEntryNodeCliSerializer extends MapEntryNodeBaseSerializer<String> {
+
+    private final NodeSerializerDispatcher<String> dispatcher;
+    private final OutFormatter out;
+
+    MapEntryNodeCliSerializer(final OutFormatter out, final NodeSerializerDispatcher<String> dispatcher) {
+        this.out = Preconditions.checkNotNull(out);
+        this.dispatcher = Preconditions.checkNotNull(dispatcher);
+    }
+
+    @Override
+    public Iterable<String> serialize(final ListSchemaNode schema, final MapEntryNode node) {
+        final StringBuilder output = new StringBuilder();
+        out.increaseIndent();
+        out.addStringWithIndent(output, node.getNodeType().getLocalName());
+        serializeKeysIfPresent(node, output);
+
+        out.openComposite(output);
+        out.newLine(output);
+
+        for (final String childOutput : super.serialize(schema, node)) {
+            output.append(childOutput);
+            out.newLine(output);
+        }
+
+        out.closeCompositeWithIndent(output);
+        out.newLine(output);
+        out.decreaseIndent();
+        return Collections.singletonList(output.toString());
+    }
+
+    private void serializeKeysIfPresent(final MapEntryNode node, final StringBuilder output) {
+        final Map<QName, Object> keyValues = node.getIdentifier().getKeyValues();
+        if (keyValues.isEmpty()) {
+            return;
+        }
+
+        int i = 0;
+        output.append(" [");
+        for (final Entry<QName, Object> qNameObjectEntry : keyValues.entrySet()) {
+            output.append(qNameObjectEntry.getKey().getLocalName());
+            output.append("=");
+            output.append(qNameObjectEntry.getValue().toString());
+            if (++i != keyValues.size()) {
+                output.append(", ");
+            }
+        }
+        output.append("]");
+    }
+
+    @Override
+    protected NodeSerializerDispatcher<String> getNodeDispatcher() {
+        return dispatcher;
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/MapNodeCliSerializer.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/MapNodeCliSerializer.java
new file mode 100644 (file)
index 0000000..b08acbf
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.writer.impl;
+
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import org.opendaylight.controller.netconf.cli.writer.OutFormatter;
+import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializer;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+final class MapNodeCliSerializer implements FromNormalizedNodeSerializer<String, MapNode, ListSchemaNode> {
+
+    private final FromNormalizedNodeSerializer<String, MapEntryNode, ListSchemaNode> mapEntrySerializer;
+    private final OutFormatter out;
+
+    MapNodeCliSerializer(final OutFormatter out, final MapEntryNodeCliSerializer mapEntrySerializer) {
+        this.out = Preconditions.checkNotNull(out);
+        this.mapEntrySerializer = mapEntrySerializer;
+    }
+
+    @Override
+    public Iterable<String> serialize(final ListSchemaNode schema, final MapNode node) {
+        final StringBuilder output = new StringBuilder();
+
+        out.increaseIndent();
+        out.addStringWithIndent(output, node.getNodeType().getLocalName());
+        output.append(" ");
+        out.openComposite(output);
+        out.newLine(output);
+
+        for (final MapEntryNode mapEntryNode : node.getValue()) {
+            final Iterable<String> valueFromLeafSetEntry = mapEntrySerializer.serialize(schema, mapEntryNode);
+            output.append(valueFromLeafSetEntry.iterator().next());
+        }
+
+        out.closeCompositeWithIndent(output);
+        out.decreaseIndent();
+
+        return Collections.singletonList(output.toString());
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/NodeCliSerializerDispatcher.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/NodeCliSerializerDispatcher.java
new file mode 100644 (file)
index 0000000..08abd47
--- /dev/null
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.writer.impl;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Iterables;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
+import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
+import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
+import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
+import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
+import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
+import org.opendaylight.yangtools.yang.data.api.schema.MixinNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializerFactory;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+public class NodeCliSerializerDispatcher implements NodeSerializerDispatcher<String> {
+    private final FromNormalizedNodeSerializerFactory<String> factory;
+
+    public NodeCliSerializerDispatcher(final FromNormalizedNodeSerializerFactory<String> factory) {
+        this.factory = Preconditions.checkNotNull(factory);
+    }
+
+    @Override
+    public final Iterable<String> dispatchChildElement(final Object childSchema,
+            final DataContainerChild<? extends InstanceIdentifier.PathArgument, ?> dataContainerChild) {
+        if (dataContainerChild instanceof ContainerNode) {
+            return onContainerNode(childSchema, dataContainerChild);
+        } else if (dataContainerChild instanceof LeafNode<?>) {
+            return onLeafNode(childSchema, dataContainerChild);
+        } else if (dataContainerChild instanceof MixinNode) {
+            if (dataContainerChild instanceof LeafSetNode<?>) {
+                return onLeafListNode(childSchema, dataContainerChild);
+            } else if (dataContainerChild instanceof MapNode) {
+                return onListNode(childSchema, dataContainerChild);
+            } else if (dataContainerChild instanceof ChoiceNode) {
+                return onChoiceNode(childSchema, dataContainerChild);
+            } else if (dataContainerChild instanceof AugmentationNode) {
+                return onAugmentationSchema(childSchema, dataContainerChild);
+            }
+        }
+        throw new IllegalArgumentException("Unable to serialize " + childSchema);
+    }
+
+    private Iterable<String> onAugmentationSchema(final Object childSchema,
+            final DataContainerChild<? extends InstanceIdentifier.PathArgument, ?> dataContainerChild) {
+        checkSchemaCompatibility(childSchema, AugmentationSchema.class, dataContainerChild);
+        return factory.getAugmentationNodeSerializer().serialize((AugmentationSchema) childSchema,
+                (AugmentationNode) dataContainerChild);
+    }
+
+    private Iterable<String> onChoiceNode(final Object childSchema,
+            final DataContainerChild<? extends InstanceIdentifier.PathArgument, ?> dataContainerChild) {
+        checkSchemaCompatibility(childSchema, org.opendaylight.yangtools.yang.model.api.ChoiceNode.class,
+                dataContainerChild);
+        return factory.getChoiceNodeSerializer().serialize(
+                (org.opendaylight.yangtools.yang.model.api.ChoiceNode) childSchema, (ChoiceNode) dataContainerChild);
+    }
+
+    private Iterable<String> onListNode(final Object childSchema,
+            final DataContainerChild<? extends InstanceIdentifier.PathArgument, ?> dataContainerChild) {
+        checkSchemaCompatibility(childSchema, ListSchemaNode.class, dataContainerChild);
+        return factory.getMapNodeSerializer().serialize((ListSchemaNode) childSchema, (MapNode) dataContainerChild);
+    }
+
+    private Iterable<String> onLeafListNode(final Object childSchema,
+            final DataContainerChild<? extends InstanceIdentifier.PathArgument, ?> dataContainerChild) {
+        checkSchemaCompatibility(childSchema, LeafListSchemaNode.class, dataContainerChild);
+        return factory.getLeafSetNodeSerializer().serialize((LeafListSchemaNode) childSchema,
+                (LeafSetNode<?>) dataContainerChild);
+    }
+
+    private Iterable<String> onLeafNode(final Object childSchema,
+            final DataContainerChild<? extends InstanceIdentifier.PathArgument, ?> dataContainerChild) {
+        checkSchemaCompatibility(childSchema, LeafSchemaNode.class, dataContainerChild);
+        final Iterable<String> elements = factory.getLeafNodeSerializer().serialize((LeafSchemaNode) childSchema,
+                (LeafNode<?>) dataContainerChild);
+        checkOnlyOneSerializedElement(elements, dataContainerChild);
+        return elements;
+    }
+
+    private static void checkOnlyOneSerializedElement(final Iterable<?> elements,
+            final DataContainerChild<? extends InstanceIdentifier.PathArgument, ?> dataContainerChild) {
+        final int size = Iterables.size(elements);
+        Preconditions.checkArgument(size == 1,
+                "Unexpected count of elements for entry serialized from: %s, should be 1, was: %s", dataContainerChild,
+                size);
+    }
+
+    private Iterable<String> onContainerNode(final Object childSchema,
+            final DataContainerChild<? extends InstanceIdentifier.PathArgument, ?> dataContainerChild) {
+        checkSchemaCompatibility(childSchema, ContainerSchemaNode.class, dataContainerChild);
+
+        final Iterable<String> elements = factory.getContainerNodeSerializer().serialize(
+                (ContainerSchemaNode) childSchema, (ContainerNode) dataContainerChild);
+        checkOnlyOneSerializedElement(elements, dataContainerChild);
+        return elements;
+    }
+
+    private static void checkSchemaCompatibility(final Object childSchema, final Class<?> containerSchemaNodeClass,
+            final DataContainerChild<? extends InstanceIdentifier.PathArgument, ?> dataContainerChild) {
+        Preconditions.checkArgument(containerSchemaNodeClass.isAssignableFrom(childSchema.getClass()),
+                "Incompatible schema: %s with node: %s, expected: %s", childSchema, dataContainerChild,
+                containerSchemaNodeClass);
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/NormalizedNodeWriter.java b/opendaylight/netconf/netconf-cli/src/main/java/org/opendaylight/controller/netconf/cli/writer/impl/NormalizedNodeWriter.java
new file mode 100644 (file)
index 0000000..eef9a39
--- /dev/null
@@ -0,0 +1,94 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.writer.impl;
+
+import java.io.IOException;
+import java.util.Iterator;
+import java.util.List;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIO;
+import org.opendaylight.controller.netconf.cli.writer.OutFormatter;
+import org.opendaylight.controller.netconf.cli.writer.WriteException;
+import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils;
+import org.opendaylight.yangtools.yang.data.json.schema.cnsn.parser.CnSnToNormalizedNodeParserFactory;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class NormalizedNodeWriter extends AbstractWriter<DataSchemaNode> {
+
+    private static final Logger LOG = LoggerFactory.getLogger(NormalizedNodeWriter.class);
+    private final OutFormatter out;
+
+    public NormalizedNodeWriter(final ConsoleIO console, final OutFormatter out) {
+        super(console);
+        this.out = out;
+    }
+
+    public void writeInner(final DataSchemaNode dataSchemaNode, final List<Node<?>> dataNodes) throws WriteException,
+            IOException {
+
+        // TODO - add getDispatcher method to CnSnToNormalizedNodeParserFactory
+        // to be able call dispatchChildElement
+        final DataContainerChild<? extends PathArgument, ?> dataContainerChild = parseToNormalizedNode(dataNodes,
+                dataSchemaNode);
+
+        if (dataContainerChild != null) {
+            console.writeLn(serializeToCliOutput(dataContainerChild, dataSchemaNode));
+        }
+
+    }
+
+    private String serializeToCliOutput(final DataContainerChild<? extends PathArgument, ?> dataContainerChild,
+            final DataSchemaNode childSchema) {
+        final CliOutputFromNormalizedNodeSerializerFactory factorySerialization = CliOutputFromNormalizedNodeSerializerFactory
+                .getInstance(out, DomUtils.defaultValueCodecProvider());
+        final NodeSerializerDispatcher<String> dispatcher = factorySerialization.getDispatcher();
+        final Iterable<String> result = dispatcher.dispatchChildElement(childSchema, dataContainerChild);
+
+        if (result == null) {
+            return "";
+        }
+
+        final Iterator<String> output = result.iterator();
+        if (!output.hasNext()) {
+            return "";
+        }
+
+        return output.next();
+    }
+
+    private DataContainerChild<? extends PathArgument, ?> parseToNormalizedNode(final List<Node<?>> dataNodes,
+            final DataSchemaNode dataSchemaNode) {
+        final CnSnToNormalizedNodeParserFactory factoryParsing = CnSnToNormalizedNodeParserFactory.getInstance();
+        if (dataSchemaNode instanceof ContainerSchemaNode) {
+            return factoryParsing.getContainerNodeParser().parse(dataNodes, (ContainerSchemaNode) dataSchemaNode);
+        } else if (dataSchemaNode instanceof LeafSchemaNode) {
+            return factoryParsing.getLeafNodeParser().parse(dataNodes, (LeafSchemaNode) dataSchemaNode);
+        } else if (dataSchemaNode instanceof LeafListSchemaNode) {
+            return factoryParsing.getLeafSetNodeParser().parse(dataNodes, (LeafListSchemaNode) dataSchemaNode);
+        } else if (dataSchemaNode instanceof ListSchemaNode) {
+            return factoryParsing.getMapNodeParser().parse(dataNodes, (ListSchemaNode) dataSchemaNode);
+        } else if (dataSchemaNode instanceof ChoiceNode) {
+            return factoryParsing.getChoiceNodeParser().parse(dataNodes, (ChoiceNode) dataSchemaNode);
+        } else if (dataSchemaNode instanceof AugmentationSchema) {
+            return factoryParsing.getAugmentationNodeParser().parse(dataNodes, (AugmentationSchema) dataSchemaNode);
+        }
+        return null;
+    }
+
+}
\ No newline at end of file
diff --git a/opendaylight/netconf/netconf-cli/src/main/resources/logback.xml b/opendaylight/netconf/netconf-cli/src/main/resources/logback.xml
new file mode 100644 (file)
index 0000000..55eedc5
--- /dev/null
@@ -0,0 +1,31 @@
+
+<configuration scan="true">
+  <appender name="netconfcli.log" class="ch.qos.logback.core.FileAppender">
+    <file>netconfcli.log</file>
+
+    <encoder>
+      <pattern>%date{"yyyy-MM-dd HH:mm:ss.SSS z"} [%thread] %-5level
+        %logger{35} - %msg%n</pattern>
+    </encoder>
+
+  </appender>
+
+  <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+    <!-- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder
+      by default -->
+    <encoder>
+      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+      </pattern>
+    </encoder>
+  </appender>
+
+
+
+  <root level="trace">
+    <appender-ref ref="netconfcli.log" />
+    <!-- <appender-ref ref="STDOUT" /> -->
+  </root>
+
+  <!-- <logger name="org.opendaylight.yangtools.yang.model.api" level="TRACE"
+    additivity="false"> <appender-ref ref="netconfcli.log" /> </logger> -->
+</configuration>
diff --git a/opendaylight/netconf/netconf-cli/src/main/resources/schema/common/ietf-inet-types.yang b/opendaylight/netconf/netconf-cli/src/main/resources/schema/common/ietf-inet-types.yang
new file mode 100644 (file)
index 0000000..edd285d
--- /dev/null
@@ -0,0 +1,427 @@
+module ietf-inet-types {
+
+  namespace "urn:ietf:params:xml:ns:yang:ietf-inet-types";
+  prefix "inet";
+
+  organization
+   "IETF NETMOD (NETCONF Data Modeling Language) Working Group";
+
+  contact
+   "WG Web:   <http://tools.ietf.org/wg/netmod/>
+    WG List:  <mailto:netmod@ietf.org>
+
+    WG Chair: David Partain
+              <mailto:david.partain@ericsson.com>
+
+    WG Chair: David Kessens
+              <mailto:david.kessens@nsn.com>
+
+    Editor:   Juergen Schoenwaelder
+              <mailto:j.schoenwaelder@jacobs-university.de>";
+
+  description
+   "This module contains a collection of generally useful derived
+    YANG data types for Internet addresses and related things.
+
+    Copyright (c) 2010 IETF Trust and the persons identified as
+    authors of the code.  All rights reserved.
+
+
+
+    Redistribution and use in source and binary forms, with or without
+    modification, is permitted pursuant to, and subject to the license
+    terms contained in, the Simplified BSD License set forth in Section
+    4.c of the IETF Trust's Legal Provisions Relating to IETF Documents
+    (http://trustee.ietf.org/license-info).
+
+    This version of this YANG module is part of RFC 6021; see
+    the RFC itself for full legal notices.";
+
+  revision 2010-09-24 {
+    description
+     "Initial revision.";
+    reference
+     "RFC 6021: Common YANG Data Types";
+  }
+
+  /*** collection of protocol field related types ***/
+
+  typedef ip-version {
+    type enumeration {
+      enum unknown {
+        value "0";
+        description
+         "An unknown or unspecified version of the Internet protocol.";
+      }
+      enum ipv4 {
+        value "1";
+        description
+         "The IPv4 protocol as defined in RFC 791.";
+      }
+      enum ipv6 {
+        value "2";
+        description
+         "The IPv6 protocol as defined in RFC 2460.";
+      }
+    }
+    description
+     "This value represents the version of the IP protocol.
+
+      In the value set and its semantics, this type is equivalent
+      to the InetVersion textual convention of the SMIv2.";
+    reference
+     "RFC  791: Internet Protocol
+      RFC 2460: Internet Protocol, Version 6 (IPv6) Specification
+      RFC 4001: Textual Conventions for Internet Network Addresses";
+  }
+
+  typedef dscp {
+    type uint8 {
+      range "0..63";
+    }
+    description
+     "The dscp type represents a Differentiated Services Code-Point
+      that may be used for marking packets in a traffic stream.
+
+      In the value set and its semantics, this type is equivalent
+      to the Dscp textual convention of the SMIv2.";
+    reference
+     "RFC 3289: Management Information Base for the Differentiated
+                Services Architecture
+      RFC 2474: Definition of the Differentiated Services Field
+                (DS Field) in the IPv4 and IPv6 Headers
+      RFC 2780: IANA Allocation Guidelines For Values In
+                the Internet Protocol and Related Headers";
+  }
+
+  typedef ipv6-flow-label {
+    type uint32 {
+      range "0..1048575";
+    }
+    description
+     "The flow-label type represents flow identifier or Flow Label
+      in an IPv6 packet header that may be used to discriminate
+      traffic flows.
+
+      In the value set and its semantics, this type is equivalent
+      to the IPv6FlowLabel textual convention of the SMIv2.";
+    reference
+     "RFC 3595: Textual Conventions for IPv6 Flow Label
+      RFC 2460: Internet Protocol, Version 6 (IPv6) Specification";
+  }
+
+  typedef port-number {
+    type uint16 {
+      range "0..65535";
+    }
+    description
+     "The port-number type represents a 16-bit port number of an
+      Internet transport layer protocol such as UDP, TCP, DCCP, or
+      SCTP.  Port numbers are assigned by IANA.  A current list of
+      all assignments is available from <http://www.iana.org/>.
+
+      Note that the port number value zero is reserved by IANA.  In
+      situations where the value zero does not make sense, it can
+      be excluded by subtyping the port-number type.
+
+      In the value set and its semantics, this type is equivalent
+      to the InetPortNumber textual convention of the SMIv2.";
+    reference
+     "RFC  768: User Datagram Protocol
+      RFC  793: Transmission Control Protocol
+      RFC 4960: Stream Control Transmission Protocol
+      RFC 4340: Datagram Congestion Control Protocol (DCCP)
+      RFC 4001: Textual Conventions for Internet Network Addresses";
+  }
+
+  /*** collection of autonomous system related types ***/
+
+  typedef as-number {
+    type uint32;
+    description
+     "The as-number type represents autonomous system numbers
+      which identify an Autonomous System (AS).  An AS is a set
+      of routers under a single technical administration, using
+      an interior gateway protocol and common metrics to route
+      packets within the AS, and using an exterior gateway
+      protocol to route packets to other ASs'.  IANA maintains
+      the AS number space and has delegated large parts to the
+      regional registries.
+
+      Autonomous system numbers were originally limited to 16
+      bits.  BGP extensions have enlarged the autonomous system
+      number space to 32 bits.  This type therefore uses an uint32
+      base type without a range restriction in order to support
+      a larger autonomous system number space.
+
+      In the value set and its semantics, this type is equivalent
+      to the InetAutonomousSystemNumber textual convention of
+      the SMIv2.";
+    reference
+     "RFC 1930: Guidelines for creation, selection, and registration
+                of an Autonomous System (AS)
+      RFC 4271: A Border Gateway Protocol 4 (BGP-4)
+      RFC 4893: BGP Support for Four-octet AS Number Space
+      RFC 4001: Textual Conventions for Internet Network Addresses";
+  }
+
+  /*** collection of IP address and hostname related types ***/
+
+  typedef ip-address {
+    type union {
+      type inet:ipv4-address;
+      type inet:ipv6-address;
+    }
+    description
+     "The ip-address type represents an IP address and is IP
+      version neutral.  The format of the textual representations
+      implies the IP version.";
+  }
+
+  typedef ipv4-address {
+    type string {
+      pattern
+        '(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
+      +  '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
+      + '(%[\p{N}\p{L}]+)?';
+    }
+    description
+      "The ipv4-address type represents an IPv4 address in
+       dotted-quad notation.  The IPv4 address may include a zone
+       index, separated by a % sign.
+
+       The zone index is used to disambiguate identical address
+       values.  For link-local addresses, the zone index will
+       typically be the interface index number or the name of an
+       interface.  If the zone index is not present, the default
+       zone of the device will be used.
+
+       The canonical format for the zone index is the numerical
+       format";
+  }
+
+  typedef ipv6-address {
+    type string {
+      pattern '((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}'
+            + '((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|'
+            + '(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}'
+            + '(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))'
+            + '(%[\p{N}\p{L}]+)?';
+      pattern '(([^:]+:){6}(([^:]+:[^:]+)|(.*\..*)))|'
+            + '((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)'
+            + '(%.+)?';
+    }
+    description
+     "The ipv6-address type represents an IPv6 address in full,
+      mixed, shortened, and shortened-mixed notation.  The IPv6
+      address may include a zone index, separated by a % sign.
+
+
+
+
+
+      The zone index is used to disambiguate identical address
+      values.  For link-local addresses, the zone index will
+      typically be the interface index number or the name of an
+      interface.  If the zone index is not present, the default
+      zone of the device will be used.
+
+      The canonical format of IPv6 addresses uses the compressed
+      format described in RFC 4291, Section 2.2, item 2 with the
+      following additional rules: the :: substitution must be
+      applied to the longest sequence of all-zero 16-bit chunks
+      in an IPv6 address.  If there is a tie, the first sequence
+      of all-zero 16-bit chunks is replaced by ::.  Single
+      all-zero 16-bit chunks are not compressed.  The canonical
+      format uses lowercase characters and leading zeros are
+      not allowed.  The canonical format for the zone index is
+      the numerical format as described in RFC 4007, Section
+      11.2.";
+    reference
+     "RFC 4291: IP Version 6 Addressing Architecture
+      RFC 4007: IPv6 Scoped Address Architecture
+      RFC 5952: A Recommendation for IPv6 Address Text Representation";
+  }
+
+  typedef ip-prefix {
+    type union {
+      type inet:ipv4-prefix;
+      type inet:ipv6-prefix;
+    }
+    description
+     "The ip-prefix type represents an IP prefix and is IP
+      version neutral.  The format of the textual representations
+      implies the IP version.";
+  }
+
+  typedef ipv4-prefix {
+    type string {
+      pattern
+         '(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
+       +  '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
+       + '/(([0-9])|([1-2][0-9])|(3[0-2]))';
+    }
+    description
+     "The ipv4-prefix type represents an IPv4 address prefix.
+      The prefix length is given by the number following the
+      slash character and must be less than or equal to 32.
+
+
+
+      A prefix length value of n corresponds to an IP address
+      mask that has n contiguous 1-bits from the most
+      significant bit (MSB) and all other bits set to 0.
+
+      The canonical format of an IPv4 prefix has all bits of
+      the IPv4 address set to zero that are not part of the
+      IPv4 prefix.";
+  }
+
+  typedef ipv6-prefix {
+    type string {
+      pattern '((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}'
+            + '((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|'
+            + '(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}'
+            + '(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))'
+            + '(/(([0-9])|([0-9]{2})|(1[0-1][0-9])|(12[0-8])))';
+      pattern '(([^:]+:){6}(([^:]+:[^:]+)|(.*\..*)))|'
+            + '((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)'
+            + '(/.+)';
+    }
+    description
+     "The ipv6-prefix type represents an IPv6 address prefix.
+      The prefix length is given by the number following the
+      slash character and must be less than or equal 128.
+
+      A prefix length value of n corresponds to an IP address
+      mask that has n contiguous 1-bits from the most
+      significant bit (MSB) and all other bits set to 0.
+
+      The IPv6 address should have all bits that do not belong
+      to the prefix set to zero.
+
+      The canonical format of an IPv6 prefix has all bits of
+      the IPv6 address set to zero that are not part of the
+      IPv6 prefix.  Furthermore, IPv6 address is represented
+      in the compressed format described in RFC 4291, Section
+      2.2, item 2 with the following additional rules: the ::
+      substitution must be applied to the longest sequence of
+      all-zero 16-bit chunks in an IPv6 address.  If there is
+      a tie, the first sequence of all-zero 16-bit chunks is
+      replaced by ::.  Single all-zero 16-bit chunks are not
+      compressed.  The canonical format uses lowercase
+      characters and leading zeros are not allowed.";
+    reference
+     "RFC 4291: IP Version 6 Addressing Architecture";
+  }
+
+
+  /*** collection of domain name and URI types ***/
+
+  typedef domain-name {
+    type string {
+      pattern '((([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.)*'
+           +  '([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.?)'
+           +  '|\.';
+      length "1..253";
+    }
+    description
+     "The domain-name type represents a DNS domain name.  The
+      name SHOULD be fully qualified whenever possible.
+
+      Internet domain names are only loosely specified.  Section
+      3.5 of RFC 1034 recommends a syntax (modified in Section
+      2.1 of RFC 1123).  The pattern above is intended to allow
+      for current practice in domain name use, and some possible
+      future expansion.  It is designed to hold various types of
+      domain names, including names used for A or AAAA records
+      (host names) and other records, such as SRV records.  Note
+      that Internet host names have a stricter syntax (described
+      in RFC 952) than the DNS recommendations in RFCs 1034 and
+      1123, and that systems that want to store host names in
+      schema nodes using the domain-name type are recommended to
+      adhere to this stricter standard to ensure interoperability.
+
+      The encoding of DNS names in the DNS protocol is limited
+      to 255 characters.  Since the encoding consists of labels
+      prefixed by a length bytes and there is a trailing NULL
+      byte, only 253 characters can appear in the textual dotted
+      notation.
+
+      The description clause of schema nodes using the domain-name
+      type MUST describe when and how these names are resolved to
+      IP addresses.  Note that the resolution of a domain-name value
+      may require to query multiple DNS records (e.g., A for IPv4
+      and AAAA for IPv6).  The order of the resolution process and
+      which DNS record takes precedence can either be defined
+      explicitely or it may depend on the configuration of the
+      resolver.
+
+      Domain-name values use the US-ASCII encoding.  Their canonical
+      format uses lowercase US-ASCII characters.  Internationalized
+      domain names MUST be encoded in punycode as described in RFC
+      3492";
+    reference
+     "RFC  952: DoD Internet Host Table Specification
+      RFC 1034: Domain Names - Concepts and Facilities
+      RFC 1123: Requirements for Internet Hosts -- Application
+                and Support
+      RFC 2782: A DNS RR for specifying the location of services
+                (DNS SRV)
+      RFC 3492: Punycode: A Bootstring encoding of Unicode for
+                Internationalized Domain Names in Applications
+                (IDNA)
+      RFC 5891: Internationalizing Domain Names in Applications
+                (IDNA): Protocol";
+  }
+
+  typedef host {
+    type union {
+      type inet:ip-address;
+      type inet:domain-name;
+    }
+    description
+     "The host type represents either an IP address or a DNS
+      domain name.";
+  }
+
+  typedef uri {
+    type string;
+    description
+     "The uri type represents a Uniform Resource Identifier
+      (URI) as defined by STD 66.
+
+      Objects using the uri type MUST be in US-ASCII encoding,
+      and MUST be normalized as described by RFC 3986 Sections
+      6.2.1, 6.2.2.1, and 6.2.2.2.  All unnecessary
+      percent-encoding is removed, and all case-insensitive
+      characters are set to lowercase except for hexadecimal
+      digits, which are normalized to uppercase as described in
+      Section 6.2.2.1.
+
+      The purpose of this normalization is to help provide
+      unique URIs.  Note that this normalization is not
+      sufficient to provide uniqueness.  Two URIs that are
+      textually distinct after this normalization may still be
+      equivalent.
+
+      Objects using the uri type may restrict the schemes that
+      they permit.  For example, 'data:' and 'urn:' schemes
+      might not be appropriate.
+
+      A zero-length URI is not a valid URI.  This can be used to
+      express 'URI absent' where required.
+
+      In the value set and its semantics, this type is equivalent
+      to the Uri SMIv2 textual convention defined in RFC 5017.";
+    reference
+     "RFC 3986: Uniform Resource Identifier (URI): Generic Syntax
+      RFC 3305: Report from the Joint W3C/IETF URI Planning Interest
+                Group: Uniform Resource Identifiers (URIs), URLs,
+                and Uniform Resource Names (URNs): Clarifications
+                and Recommendations
+      RFC 5017: MIB Textual Conventions for Uniform Resource
+                Identifiers (URIs)";
+  }
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/resources/schema/common/netconf-cli-ext.yang b/opendaylight/netconf/netconf-cli/src/main/resources/schema/common/netconf-cli-ext.yang
new file mode 100644 (file)
index 0000000..139778a
--- /dev/null
@@ -0,0 +1,18 @@
+module netconf-cli-ext {
+
+  namespace "urn:ietf:params:xml:ns:netconf:base:1.0:cli";
+
+  prefix cliext;
+
+    revision 2014-05-26 {
+      description
+        "Initial revision";
+    }
+
+  extension argument-handler {
+    description
+        "Links custom argument reader to an input argument";
+    argument "name";
+  }
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/resources/schema/local/netconf-cli.yang b/opendaylight/netconf/netconf-cli/src/main/resources/schema/local/netconf-cli.yang
new file mode 100644 (file)
index 0000000..52f7b97
--- /dev/null
@@ -0,0 +1,97 @@
+module netconf-cli {
+
+  namespace "netconf:cli";
+  prefix ncli;
+
+  import ietf-inet-types { prefix inet; revision-date 2010-09-24; }
+  import netconf-cli-ext { prefix cliext; revision-date 2014-05-26; }
+
+
+    revision 2014-05-22 {
+      description
+       "Initial revision.";
+    }
+
+  extension java-class {
+      description
+          "This could be used to link between rpc yang definition and custom command implementation";
+
+      argument "name";
+  }
+
+  rpc help {
+    description
+        "Display help";
+
+    output {
+      list commands {
+
+        key "id";
+        leaf id {
+            type string;
+        }
+        leaf description {
+            type string;
+        }
+      }
+    }
+  }
+
+  rpc close {
+      description
+          "Close the whole cli";
+  }
+
+  rpc connect {
+
+        description
+            "Connect to a remote netconf device, if not connected yet. Connection initialization is blocking and might take some time, depending on amount of yang schemas in remote device.";
+
+      input {
+
+         // TODO yangtools keep input arguments unordered so the ordering in cli is random
+         leaf address-name {
+           type inet:host;
+           default localhost;
+         }
+
+         leaf address-port {
+           type inet:port-number;
+           default 830;
+         }
+
+          leaf user-name {
+           type string;
+         }
+
+        leaf user-password {
+            cliext:argument-handler org.opendaylight.controller.netconf.cli.reader.custom.PasswordReader;
+            type string;
+        }
+      }
+
+      output {
+        leaf status {
+            type string;
+        }
+
+        leaf-list remote-commands {
+            type string;
+        }
+      }
+  }
+
+
+  rpc disconnect {
+
+      description
+          "Disconnect from a netconf device that is currently connected";
+
+      output {
+        leaf status {
+            type string;
+        }
+      }
+    }
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/main/resources/schema/remote/ietf-netconf.yang b/opendaylight/netconf/netconf-cli/src/main/resources/schema/remote/ietf-netconf.yang
new file mode 100644 (file)
index 0000000..d41c2e3
--- /dev/null
@@ -0,0 +1,943 @@
+module ietf-netconf {
+
+  // the namespace for NETCONF XML definitions is unchanged
+  // from RFC 4741, which this document replaces
+  namespace "urn:ietf:params:xml:ns:netconf:base:1.0";
+
+  prefix nc;
+
+  import ietf-inet-types {
+    prefix inet;
+  }
+
+  import netconf-cli-ext { prefix cliext; revision-date 2014-05-26; }
+
+
+  organization
+    "IETF NETCONF (Network Configuration) Working Group";
+
+  contact
+    "WG Web:   <http://tools.ietf.org/wg/netconf/>
+     WG List:  <netconf@ietf.org>
+
+     WG Chair: Bert Wijnen
+               <bertietf@bwijnen.net>
+
+     WG Chair: Mehmet Ersue
+               <mehmet.ersue@nsn.com>
+
+     Editor:   Martin Bjorklund
+               <mbj@tail-f.com>
+
+     Editor:   Juergen Schoenwaelder
+               <j.schoenwaelder@jacobs-university.de>
+
+     Editor:   Andy Bierman
+               <andy.bierman@brocade.com>";
+  description
+    "NETCONF Protocol Data Types and Protocol Operations.
+
+     Copyright (c) 2011 IETF Trust and the persons identified as
+     the document authors.  All rights reserved.
+
+     Redistribution and use in source and binary forms, with or
+     without modification, is permitted pursuant to, and subject
+     to the license terms contained in, the Simplified BSD License
+     set forth in Section 4.c of the IETF Trust's Legal Provisions
+     Relating to IETF Documents
+     (http://trustee.ietf.org/license-info).
+
+     This version of this YANG module is part of RFC 6241; see
+     the RFC itself for full legal notices.";
+  revision 2011-06-01 {
+    description
+      "Initial revision";
+    reference
+      "RFC 6241: Network Configuration Protocol";
+  }
+
+  extension get-filter-element-attributes {
+    description
+      "If this extension is present within an 'anyxml'
+       statement named 'filter', which must be conceptually
+       defined within the RPC input section for the <get>
+       and <get-config> protocol operations, then the
+       following unqualified XML attribute is supported
+       within the <filter> element, within a <get> or
+       <get-config> protocol operation:
+
+         type : optional attribute with allowed
+                value strings 'subtree' and 'xpath'.
+                If missing, the default value is 'subtree'.
+
+       If the 'xpath' feature is supported, then the
+       following unqualified XML attribute is
+       also supported:
+
+         select: optional attribute containing a
+                 string representing an XPath expression.
+                 The 'type' attribute must be equal to 'xpath'
+                 if this attribute is present.";
+  }
+
+  // NETCONF capabilities defined as features
+  feature writable-running {
+    description
+      "NETCONF :writable-running capability;
+       If the server advertises the :writable-running
+       capability for a session, then this feature must
+       also be enabled for that session.  Otherwise,
+       this feature must not be enabled.";
+    reference "RFC 6241, Section 8.2";
+  }
+
+  feature candidate {
+    description
+      "NETCONF :candidate capability;
+       If the server advertises the :candidate
+       capability for a session, then this feature must
+       also be enabled for that session.  Otherwise,
+       this feature must not be enabled.";
+    reference "RFC 6241, Section 8.3";
+  }
+
+  feature confirmed-commit {
+    if-feature candidate;
+    description
+      "NETCONF :confirmed-commit:1.1 capability;
+       If the server advertises the :confirmed-commit:1.1
+       capability for a session, then this feature must
+       also be enabled for that session.  Otherwise,
+       this feature must not be enabled.";
+
+    reference "RFC 6241, Section 8.4";
+  }
+
+  feature rollback-on-error {
+    description
+      "NETCONF :rollback-on-error capability;
+       If the server advertises the :rollback-on-error
+       capability for a session, then this feature must
+       also be enabled for that session.  Otherwise,
+       this feature must not be enabled.";
+    reference "RFC 6241, Section 8.5";
+  }
+
+  feature validate {
+    description
+      "NETCONF :validate:1.1 capability;
+       If the server advertises the :validate:1.1
+       capability for a session, then this feature must
+       also be enabled for that session.  Otherwise,
+       this feature must not be enabled.";
+    reference "RFC 6241, Section 8.6";
+  }
+
+  feature startup {
+    description
+      "NETCONF :startup capability;
+       If the server advertises the :startup
+       capability for a session, then this feature must
+       also be enabled for that session.  Otherwise,
+       this feature must not be enabled.";
+    reference "RFC 6241, Section 8.7";
+  }
+
+  feature url {
+    description
+      "NETCONF :url capability;
+       If the server advertises the :url
+       capability for a session, then this feature must
+       also be enabled for that session.  Otherwise,
+       this feature must not be enabled.";
+    reference "RFC 6241, Section 8.8";
+  }
+
+  feature xpath {
+    description
+      "NETCONF :xpath capability;
+       If the server advertises the :xpath
+       capability for a session, then this feature must
+       also be enabled for that session.  Otherwise,
+       this feature must not be enabled.";
+    reference "RFC 6241, Section 8.9";
+  }
+
+  // NETCONF Simple Types
+
+  typedef session-id-type {
+    type uint32 {
+      range "1..max";
+    }
+    description
+      "NETCONF Session Id";
+  }
+
+  typedef session-id-or-zero-type {
+    type uint32;
+    description
+      "NETCONF Session Id or Zero to indicate none";
+  }
+  typedef error-tag-type {
+    type enumeration {
+       enum in-use {
+         description
+           "The request requires a resource that
+            already is in use.";
+       }
+       enum invalid-value {
+         description
+           "The request specifies an unacceptable value for one
+            or more parameters.";
+       }
+       enum too-big {
+         description
+           "The request or response (that would be generated) is
+            too large for the implementation to handle.";
+       }
+       enum missing-attribute {
+         description
+           "An expected attribute is missing.";
+       }
+       enum bad-attribute {
+         description
+           "An attribute value is not correct; e.g., wrong type,
+            out of range, pattern mismatch.";
+       }
+       enum unknown-attribute {
+         description
+           "An unexpected attribute is present.";
+       }
+       enum missing-element {
+         description
+           "An expected element is missing.";
+       }
+       enum bad-element {
+         description
+           "An element value is not correct; e.g., wrong type,
+            out of range, pattern mismatch.";
+       }
+       enum unknown-element {
+         description
+           "An unexpected element is present.";
+       }
+       enum unknown-namespace {
+         description
+           "An unexpected namespace is present.";
+       }
+       enum access-denied {
+         description
+           "Access to the requested protocol operation or
+            data model is denied because authorization failed.";
+       }
+       enum lock-denied {
+         description
+           "Access to the requested lock is denied because the
+            lock is currently held by another entity.";
+       }
+       enum resource-denied {
+         description
+           "Request could not be completed because of
+            insufficient resources.";
+       }
+       enum rollback-failed {
+         description
+           "Request to roll back some configuration change (via
+            rollback-on-error or <discard-changes> operations)
+            was not completed for some reason.";
+
+       }
+       enum data-exists {
+         description
+           "Request could not be completed because the relevant
+            data model content already exists.  For example,
+            a 'create' operation was attempted on data that
+            already exists.";
+       }
+       enum data-missing {
+         description
+           "Request could not be completed because the relevant
+            data model content does not exist.  For example,
+            a 'delete' operation was attempted on
+            data that does not exist.";
+       }
+       enum operation-not-supported {
+         description
+           "Request could not be completed because the requested
+            operation is not supported by this implementation.";
+       }
+       enum operation-failed {
+         description
+           "Request could not be completed because the requested
+            operation failed for some reason not covered by
+            any other error condition.";
+       }
+       enum partial-operation {
+         description
+           "This error-tag is obsolete, and SHOULD NOT be sent
+            by servers conforming to this document.";
+       }
+       enum malformed-message {
+         description
+           "A message could not be handled because it failed to
+            be parsed correctly.  For example, the message is not
+            well-formed XML or it uses an invalid character set.";
+       }
+     }
+     description "NETCONF Error Tag";
+     reference "RFC 6241, Appendix A";
+  }
+
+  typedef error-severity-type {
+    type enumeration {
+      enum error {
+        description "Error severity";
+      }
+      enum warning {
+        description "Warning severity";
+      }
+    }
+    description "NETCONF Error Severity";
+    reference "RFC 6241, Section 4.3";
+  }
+
+  typedef edit-operation-type {
+    type enumeration {
+      enum merge {
+        description
+          "The configuration data identified by the
+           element containing this attribute is merged
+           with the configuration at the corresponding
+           level in the configuration datastore identified
+           by the target parameter.";
+      }
+      enum replace {
+        description
+          "The configuration data identified by the element
+           containing this attribute replaces any related
+           configuration in the configuration datastore
+           identified by the target parameter.  If no such
+           configuration data exists in the configuration
+           datastore, it is created.  Unlike a
+           <copy-config> operation, which replaces the
+           entire target configuration, only the configuration
+           actually present in the config parameter is affected.";
+      }
+      enum create {
+        description
+          "The configuration data identified by the element
+           containing this attribute is added to the
+           configuration if and only if the configuration
+           data does not already exist in the configuration
+           datastore.  If the configuration data exists, an
+           <rpc-error> element is returned with an
+           <error-tag> value of 'data-exists'.";
+      }
+      enum delete {
+        description
+          "The configuration data identified by the element
+           containing this attribute is deleted from the
+           configuration if and only if the configuration
+           data currently exists in the configuration
+           datastore.  If the configuration data does not
+           exist, an <rpc-error> element is returned with
+           an <error-tag> value of 'data-missing'.";
+      }
+      enum remove {
+        description
+          "The configuration data identified by the element
+           containing this attribute is deleted from the
+           configuration if the configuration
+           data currently exists in the configuration
+           datastore.  If the configuration data does not
+           exist, the 'remove' operation is silently ignored
+           by the server.";
+      }
+    }
+    default "merge";
+    description "NETCONF 'operation' attribute values";
+    reference "RFC 6241, Section 7.2";
+  }
+
+  // NETCONF Standard Protocol Operations
+
+  rpc get-config {
+    description
+      "Retrieve all or part of a specified configuration.";
+
+    reference "RFC 6241, Section 7.1";
+
+    input {
+      container source {
+        description
+          "Particular configuration to retrieve.";
+
+        choice config-source {
+          mandatory true;
+          description
+            "The configuration to retrieve.";
+          leaf candidate {
+            if-feature candidate;
+            type empty;
+            description
+              "The candidate configuration is the config source.";
+          }
+          leaf running {
+            type empty;
+            description
+              "The running configuration is the config source.";
+          }
+          leaf startup {
+            if-feature startup;
+            type empty;
+            description
+              "The startup configuration is the config source.
+               This is optional-to-implement on the server because
+               not all servers will support filtering for this
+               datastore.";
+          }
+        }
+      }
+
+      anyxml filter {
+        description
+          "Subtree or XPath filter to use.";
+        nc:get-filter-element-attributes;
+        // TODO this extension should be augmented (anyxml nodes cannot be augmented)
+        // or we can identify custom input/output arguments by schemaPath defined for custom handlers
+        cliext:argument-handler org.opendaylight.controller.netconf.cli.reader.custom.FilterReader;
+      }
+    }
+
+    output {
+      anyxml data {
+        description
+          "Copy of the source datastore subset that matched
+           the filter criteria (if any).  An empty data container
+           indicates that the request did not produce any results.";
+       cliext:argument-handler org.opendaylight.controller.netconf.cli.writer.custom.DataWriter;
+     }
+    }
+  }
+
+  rpc edit-config {
+    description
+      "The <edit-config> operation loads all or part of a specified
+       configuration to the specified target configuration.";
+
+    reference "RFC 6241, Section 7.2";
+
+    input {
+      container target {
+        description
+          "Particular configuration to edit.";
+
+        choice config-target {
+          mandatory true;
+          description
+            "The configuration target.";
+
+          leaf candidate {
+            if-feature candidate;
+            type empty;
+            description
+              "The candidate configuration is the config target.";
+          }
+          leaf running {
+            if-feature writable-running;
+            type empty;
+            description
+              "The running configuration is the config source.";
+          }
+        }
+      }
+
+      leaf default-operation {
+        type enumeration {
+          enum merge {
+            description
+              "The default operation is merge.";
+          }
+          enum replace {
+            description
+              "The default operation is replace.";
+          }
+          enum none {
+            description
+              "There is no default operation.";
+          }
+        }
+        default "merge";
+        description
+          "The default operation to use.";
+      }
+
+      leaf test-option {
+        if-feature validate;
+        type enumeration {
+          enum test-then-set {
+            description
+              "The server will test and then set if no errors.";
+          }
+          enum set {
+            description
+              "The server will set without a test first.";
+          }
+
+          enum test-only {
+            description
+              "The server will only test and not set, even
+               if there are no errors.";
+          }
+        }
+        default "test-then-set";
+        description
+          "The test option to use.";
+      }
+
+      leaf error-option {
+        type enumeration {
+          enum stop-on-error {
+            description
+              "The server will stop on errors.";
+          }
+          enum continue-on-error {
+            description
+              "The server may continue on errors.";
+          }
+          enum rollback-on-error {
+            description
+              "The server will roll back on errors.
+               This value can only be used if the 'rollback-on-error'
+               feature is supported.";
+          }
+        }
+        default "stop-on-error";
+        description
+          "The error option to use.";
+      }
+
+      choice edit-content {
+        mandatory true;
+        description
+          "The content for the edit operation.";
+
+        cliext:argument-handler org.opendaylight.controller.netconf.cli.reader.custom.EditContentReader;
+
+        anyxml config {
+          description
+            "Inline Config content.";
+          cliext:argument-handler org.opendaylight.controller.netconf.cli.reader.custom.ConfigReader;
+        }
+
+        leaf url {
+          if-feature url;
+          type inet:uri;
+          description
+            "URL-based config content.";
+        }
+      }
+    }
+  }
+
+  rpc copy-config {
+    description
+      "Create or replace an entire configuration datastore with the
+       contents of another complete configuration datastore.";
+
+    reference "RFC 6241, Section 7.3";
+
+    input {
+      container target {
+        description
+          "Particular configuration to copy to.";
+
+        choice config-target {
+          mandatory true;
+          description
+            "The configuration target of the copy operation.";
+
+          leaf candidate {
+            if-feature candidate;
+            type empty;
+            description
+              "The candidate configuration is the config target.";
+          }
+          leaf running {
+            if-feature writable-running;
+            type empty;
+            description
+              "The running configuration is the config target.
+               This is optional-to-implement on the server.";
+          }
+          leaf startup {
+            if-feature startup;
+            type empty;
+            description
+              "The startup configuration is the config target.";
+          }
+          leaf url {
+            if-feature url;
+            type inet:uri;
+            description
+              "The URL-based configuration is the config target.";
+          }
+        }
+      }
+
+      container source {
+        description
+          "Particular configuration to copy from.";
+
+        choice config-source {
+          mandatory true;
+          description
+            "The configuration source for the copy operation.";
+
+          leaf candidate {
+            if-feature candidate;
+            type empty;
+            description
+              "The candidate configuration is the config source.";
+          }
+          leaf running {
+            type empty;
+            description
+              "The running configuration is the config source.";
+          }
+          leaf startup {
+            if-feature startup;
+            type empty;
+            description
+              "The startup configuration is the config source.";
+          }
+          leaf url {
+            if-feature url;
+            type inet:uri;
+            description
+              "The URL-based configuration is the config source.";
+          }
+          anyxml config {
+            description
+              "Inline Config content: <config> element.  Represents
+               an entire configuration datastore, not
+               a subset of the running datastore.";
+          }
+        }
+      }
+    }
+  }
+
+  rpc delete-config {
+    description
+      "Delete a configuration datastore.";
+
+    reference "RFC 6241, Section 7.4";
+
+    input {
+      container target {
+        description
+          "Particular configuration to delete.";
+
+        choice config-target {
+          mandatory true;
+          description
+            "The configuration target to delete.";
+
+          leaf startup {
+            if-feature startup;
+            type empty;
+            description
+              "The startup configuration is the config target.";
+          }
+          leaf url {
+            if-feature url;
+            type inet:uri;
+            description
+              "The URL-based configuration is the config target.";
+          }
+        }
+      }
+    }
+  }
+
+  rpc lock {
+    description
+      "The lock operation allows the client to lock the configuration
+       system of a device.";
+
+    reference "RFC 6241, Section 7.5";
+
+    input {
+      container target {
+        description
+          "Particular configuration to lock.";
+
+        choice config-target {
+          mandatory true;
+          description
+            "The configuration target to lock.";
+
+          leaf candidate {
+            if-feature candidate;
+            type empty;
+            description
+              "The candidate configuration is the config target.";
+          }
+          leaf running {
+            type empty;
+            description
+              "The running configuration is the config target.";
+          }
+          leaf startup {
+            if-feature startup;
+            type empty;
+            description
+              "The startup configuration is the config target.";
+          }
+        }
+      }
+    }
+  }
+
+  rpc unlock {
+    description
+      "The unlock operation is used to release a configuration lock,
+       previously obtained with the 'lock' operation.";
+
+    reference "RFC 6241, Section 7.6";
+
+    input {
+      container target {
+        description
+          "Particular configuration to unlock.";
+
+        choice config-target {
+          mandatory true;
+          description
+            "The configuration target to unlock.";
+
+          leaf candidate {
+            if-feature candidate;
+            type empty;
+            description
+              "The candidate configuration is the config target.";
+          }
+          leaf running {
+            type empty;
+            description
+              "The running configuration is the config target.";
+          }
+          leaf startup {
+            if-feature startup;
+            type empty;
+            description
+              "The startup configuration is the config target.";
+          }
+        }
+      }
+    }
+  }
+
+  rpc get {
+    description
+      "Retrieve running configuration and device state information.";
+
+    reference "RFC 6241, Section 7.7";
+
+    input {
+      anyxml filter {
+        description
+          "This parameter specifies the portion of the system
+           configuration and state data to retrieve.";
+        nc:get-filter-element-attributes;
+        // TODO this extension should be augmented (anyxml nodes cannot be augmented)
+        cliext:argument-handler org.opendaylight.controller.netconf.cli.reader.custom.FilterReader;
+      }
+    }
+
+    output {
+      anyxml data {
+        description
+          "Copy of the running datastore subset and/or state
+           data that matched the filter criteria (if any).
+           An empty data container indicates that the request did not
+           produce any results.";
+
+       cliext:argument-handler org.opendaylight.controller.netconf.cli.writer.custom.DataWriter;
+
+      }
+    }
+  }
+
+  rpc close-session {
+    description
+      "Request graceful termination of a NETCONF session.";
+
+    reference "RFC 6241, Section 7.8";
+  }
+
+  rpc kill-session {
+    description
+      "Force the termination of a NETCONF session.";
+
+    reference "RFC 6241, Section 7.9";
+
+    input {
+      leaf session-id {
+        type session-id-type;
+        mandatory true;
+        description
+          "Particular session to kill.";
+      }
+    }
+  }
+
+  rpc commit {
+    if-feature candidate;
+
+    description
+      "Commit the candidate configuration as the device's new
+       current configuration.";
+
+    reference "RFC 6241, Section 8.3.4.1";
+
+    input {
+      leaf confirmed {
+        if-feature confirmed-commit;
+        type empty;
+        description
+          "Requests a confirmed commit.";
+        reference "RFC 6241, Section 8.3.4.1";
+      }
+
+      leaf confirm-timeout {
+        if-feature confirmed-commit;
+        type uint32 {
+          range "1..max";
+        }
+        units "seconds";
+        default "600";   // 10 minutes
+        description
+          "The timeout interval for a confirmed commit.";
+        reference "RFC 6241, Section 8.3.4.1";
+      }
+
+      leaf persist {
+        if-feature confirmed-commit;
+        type string;
+        description
+          "This parameter is used to make a confirmed commit
+           persistent.  A persistent confirmed commit is not aborted
+           if the NETCONF session terminates.  The only way to abort
+           a persistent confirmed commit is to let the timer expire,
+           or to use the <cancel-commit> operation.
+
+           The value of this parameter is a token that must be given
+           in the 'persist-id' parameter of <commit> or
+           <cancel-commit> operations in order to confirm or cancel
+           the persistent confirmed commit.
+
+           The token should be a random string.";
+        reference "RFC 6241, Section 8.3.4.1";
+      }
+
+      leaf persist-id {
+        if-feature confirmed-commit;
+        type string;
+        description
+          "This parameter is given in order to commit a persistent
+           confirmed commit.  The value must be equal to the value
+           given in the 'persist' parameter to the <commit> operation.
+           If it does not match, the operation fails with an
+          'invalid-value' error.";
+        reference "RFC 6241, Section 8.3.4.1";
+      }
+
+    }
+  }
+
+  rpc discard-changes {
+    if-feature candidate;
+
+    description
+      "Revert the candidate configuration to the current
+       running configuration.";
+    reference "RFC 6241, Section 8.3.4.2";
+  }
+
+  rpc cancel-commit {
+    if-feature confirmed-commit;
+    description
+      "This operation is used to cancel an ongoing confirmed commit.
+       If the confirmed commit is persistent, the parameter
+       'persist-id' must be given, and it must match the value of the
+       'persist' parameter.";
+    reference "RFC 6241, Section 8.4.4.1";
+
+    input {
+      leaf persist-id {
+        type string;
+        description
+          "This parameter is given in order to cancel a persistent
+           confirmed commit.  The value must be equal to the value
+           given in the 'persist' parameter to the <commit> operation.
+           If it does not match, the operation fails with an
+          'invalid-value' error.";
+      }
+    }
+  }
+
+  rpc validate {
+    if-feature validate;
+
+    description
+      "Validates the contents of the specified configuration.";
+
+    reference "RFC 6241, Section 8.6.4.1";
+
+    input {
+      container source {
+        description
+          "Particular configuration to validate.";
+
+        choice config-source {
+          mandatory true;
+          description
+            "The configuration source to validate.";
+
+          leaf candidate {
+            if-feature candidate;
+            type empty;
+            description
+              "The candidate configuration is the config source.";
+          }
+          leaf running {
+            type empty;
+            description
+              "The running configuration is the config source.";
+          }
+          leaf startup {
+            if-feature startup;
+            type empty;
+            description
+              "The startup configuration is the config source.";
+          }
+          leaf url {
+            if-feature url;
+            type inet:uri;
+            description
+              "The URL-based configuration is the config source.";
+          }
+          anyxml config {
+            description
+              "Inline Config content: <config> element.  Represents
+               an entire configuration datastore, not
+               a subset of the running datastore.";
+          }
+        }
+      }
+    }
+  }
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/test/java/org/opendaylight/controller/netconf/cli/ConsoleIOTestImpl.java b/opendaylight/netconf/netconf-cli/src/test/java/org/opendaylight/controller/netconf/cli/ConsoleIOTestImpl.java
new file mode 100644 (file)
index 0000000..29d7abd
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli;
+
+import java.io.IOException;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.opendaylight.controller.netconf.cli.io.ConsoleIOImpl;
+
+public class ConsoleIOTestImpl extends ConsoleIOImpl {
+
+    Map<String, Deque<String>> inputValues = new HashMap<>();
+    String lastMessage;
+    private final List<ValueForMessage> valuesForMessages;
+
+    public ConsoleIOTestImpl(final Map<String, Deque<String>> inputValues, final List<ValueForMessage> valuesForMessages)
+            throws IOException {
+        super();
+        this.inputValues = inputValues;
+        this.valuesForMessages = valuesForMessages;
+    }
+
+    StringBuilder output = new StringBuilder();
+
+    @Override
+    public String read() throws IOException {
+        final String prompt = buildPrompt();
+        output.append(prompt);
+        System.out.print(prompt);
+
+        String value = inputValues.get(prompt).pollFirst();
+        if (value == null) {
+            value = getValueForLastMessage();
+        }
+
+        value = value != null ? value : "****NO VALUE****";
+
+        output.append(value + "\n");
+        System.out.print(value + "\n");
+        return value;
+    }
+
+    private String getValueForLastMessage() {
+        for (final ValueForMessage valueForMessage : valuesForMessages) {
+            if (containsLastMessageKeyWords(valueForMessage.getKeyWords())) {
+                return valueForMessage.getValue();
+            }
+        }
+        return null;
+    }
+
+    private boolean containsLastMessageKeyWords(final List<String> keyWords) {
+        for (final String keyWord : keyWords) {
+            if (!lastMessage.contains(keyWord)) {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    @Override
+    public void write(final CharSequence data) throws IOException {
+        output.append(data);
+        lastMessage = (String) data;
+        System.out.print(data);
+    }
+
+    @Override
+    public void writeLn(final CharSequence data) throws IOException {
+        write(data);
+        output.append("\n");
+        System.out.print("\n");
+    }
+
+    public String getConsoleOutput() {
+        return output.toString();
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/test/java/org/opendaylight/controller/netconf/cli/NetconfCliTest.java b/opendaylight/netconf/netconf-cli/src/test/java/org/opendaylight/controller/netconf/cli/NetconfCliTest.java
new file mode 100644 (file)
index 0000000..7d85aa4
--- /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.netconf.cli;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.opendaylight.controller.netconf.cli.io.IOUtil.PROMPT_SUFIX;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.opendaylight.controller.netconf.cli.reader.ReadingException;
+import org.opendaylight.controller.netconf.cli.reader.impl.GenericReader;
+import org.opendaylight.controller.netconf.cli.writer.OutFormatter;
+import org.opendaylight.controller.netconf.cli.writer.WriteException;
+import org.opendaylight.controller.netconf.cli.writer.impl.NormalizedNodeWriter;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.CompositeNode;
+import org.opendaylight.yangtools.yang.data.api.Node;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser;
+import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
+
+@Ignore
+public class NetconfCliTest {
+
+    private final static YangContextParser parser = new YangParserImpl();
+
+    private static SchemaContext loadSchemaContext(final String resourceDirectory) throws IOException,
+            URISyntaxException {
+        final URI uri = NetconfCliTest.class.getResource(resourceDirectory).toURI();
+        final File testDir = new File(uri);
+        final String[] fileList = testDir.list();
+        final List<File> testFiles = new ArrayList<File>();
+        if (fileList == null) {
+            throw new FileNotFoundException(resourceDirectory);
+        }
+        for (final String fileName : fileList) {
+            if (new File(testDir, fileName).isDirectory() == false) {
+                testFiles.add(new File(testDir, fileName));
+            }
+        }
+        return parser.parseFiles(testFiles);
+    }
+
+    // @Ignore
+    @Test
+    public void cliTest() throws ReadingException, IOException, WriteException, URISyntaxException {
+
+        final SchemaContext schemaContext = loadSchemaContext("/schema-context");
+        assertNotNull(schemaContext);
+
+        final DataSchemaNode cont1 = findTopLevelElement("ns:model1", "2014-05-14", "cont1", schemaContext);
+        final Map<String, Deque<String>> values = new HashMap<>();
+
+        values.put(prompt("/cont1/cont11/lst111/[entry]/lf1111"), value("55", "32"));
+        values.put(prompt("/cont1/cont11/lst111/[entry]"), value("Y", "Y"));
+        values.put(prompt("/cont1/cont11/lst111/[entry]/cont111/lf1112"),
+                value("value for lf1112", "2value for lf1112"));
+        values.put(prompt("/cont1/cont11/lst111/[entry]/cont111/lflst1111"), value("Y", "N", "Y", "N"));
+        values.put(prompt("/cont1/cont11/lst111/[entry]/cont111/lflst1111/[entry]"), value("10", "15", "20", "30"));
+
+        values.put(prompt("/cont1/cont11/lst111"), value("Y", "N"));
+
+        values.put(prompt("/cont1/cont12/chcA"), value("AB"));
+        values.put(prompt("/cont1/cont12/chcA/cont12AB1/lf12AB1"), value("value for lf12AB1"));
+
+        values.put(prompt("/cont1/cont12/lst121/[entry]/lf1211"), value("value for lf12112", "2value for lf12112"));
+        values.put(prompt("/cont1/cont12/lst121/[entry]"), value("Y", "Y"));
+        values.put(prompt("/cont1/cont12/lst121/[entry]/lst1211"), value("Y", "N", "Y", "N"));
+        values.put(prompt("/cont1/cont12/lst121/[entry]/lst1211/[entry]"), value("Y", "Y", "Y", "Y"));
+        values.put(prompt("/cont1/cont12/lst121/[entry]/lst1211/[entry]/lf12111"), value("5", "10", "21", "50"));
+        values.put(prompt("/cont1/cont12/lst121/[entry]/lst1211/[entry]/lf12112"),
+                value("value for lf12112", "2value for lf12112", "3value for lf12112", "4value for lf12112"));
+
+        values.put(prompt("/cont1/cont12/lst121"), value("Y", "N"));
+
+        values.put(prompt("/cont1/cont12/lst122"), value("Y", "N"));
+
+        values.put(prompt("/cont1/lst11"), value("Y", "Y", "N"));
+        values.put(prompt("/cont1/lst11/[entry]"), value("Y", "Y", "Y"));
+        values.put(prompt("/cont1/lst11/[entry]/lf111"),
+                value("1value for lf111", "2value for lf111", "3value for lf111"));
+
+        values.put(prompt("/cont1/cont12/data"), value("<el1><el11>value</el11><el12>value1</el12></el1>"));
+
+        final List<ValueForMessage> valuesForMessages = new ArrayList<>();
+        valuesForMessages.add(new ValueForMessage("Y", "lst111", "[Y|N]"));
+        valuesForMessages.add(new ValueForMessage("Y", "lst121", "[Y|N]"));
+        valuesForMessages.add(new ValueForMessage("Y", "lst11", "[Y|N]"));
+
+        final ConsoleIOTestImpl console = new ConsoleIOTestImpl(values, valuesForMessages);
+
+        final List<Node<?>> redData = new GenericReader(console, new CommandArgHandlerRegistry(console,
+                new SchemaContextRegistry(schemaContext)), schemaContext).read(cont1);
+        assertNotNull(redData);
+       assertEquals(1, redData.size());
+
+        assertTrue(redData.get(0) instanceof CompositeNode);
+        final CompositeNode redTopLevelNode = (CompositeNode) redData.get(0);
+
+        System.out.println("============================");
+        new NormalizedNodeWriter(console, new OutFormatter()).write(cont1, redData);
+
+    }
+
+    private Deque<String> value(final String... values) {
+        return new ArrayDeque<>(Arrays.asList(values));
+    }
+
+    private String prompt(final String path) {
+        return "/localhost" + path + PROMPT_SUFIX;
+    }
+
+    private DataSchemaNode findTopLevelElement(final String namespace, final String revision,
+            final String topLevelElement, final SchemaContext schemaContext) {
+        final QName requiredElement = QName.create(namespace, revision, topLevelElement);
+        for (final DataSchemaNode dataSchemaNode : schemaContext.getChildNodes()) {
+            if (dataSchemaNode.getQName().equals(requiredElement)) {
+                return dataSchemaNode;
+            }
+        }
+        return null;
+
+    }
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/test/java/org/opendaylight/controller/netconf/cli/ValueForMessages.java b/opendaylight/netconf/netconf-cli/src/test/java/org/opendaylight/controller/netconf/cli/ValueForMessages.java
new file mode 100644 (file)
index 0000000..2532b36
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli;
+
+import java.util.Arrays;
+import java.util.List;
+
+class ValueForMessage {
+    List<String> messageKeyWords;
+    String value;
+
+    public ValueForMessage(final String value, final String... messageKeyWords) {
+        this.messageKeyWords = Arrays.asList(messageKeyWords);
+        this.value = value;
+    }
+
+    public List<String> getKeyWords() {
+        return messageKeyWords;
+    }
+
+    public String getValue() {
+        return value;
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/test/java/org/opendaylight/controller/netconf/cli/io/IOUtilTest.java b/opendaylight/netconf/netconf-cli/src/test/java/org/opendaylight/controller/netconf/cli/io/IOUtilTest.java
new file mode 100644 (file)
index 0000000..2021bf7
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.netconf.cli.io;
+
+import com.google.common.collect.Maps;
+import java.util.Map;
+import junit.framework.Assert;
+import org.junit.Test;
+import org.opendaylight.controller.netconf.cli.commands.CommandConstants;
+import org.opendaylight.yangtools.yang.common.QName;
+
+public class IOUtilTest {
+
+    @Test
+    public void testQNameFromKeyStringNew() throws Exception {
+        final String s = IOUtil.qNameToKeyString(CommandConstants.HELP_QNAME, "module");
+        final Map<String, QName> modulesMap = Maps.newHashMap();
+        modulesMap.put("module", new QName(CommandConstants.HELP_QNAME, "module"));
+        final QName qName = IOUtil.qNameFromKeyString(s, modulesMap);
+        Assert.assertEquals(CommandConstants.HELP_QNAME, qName);
+    }
+}
diff --git a/opendaylight/netconf/netconf-cli/src/test/resources/schema-context/ietf-inet-types.yang b/opendaylight/netconf/netconf-cli/src/test/resources/schema-context/ietf-inet-types.yang
new file mode 100644 (file)
index 0000000..de20feb
--- /dev/null
@@ -0,0 +1,418 @@
+ module ietf-inet-types {
+
+   namespace "urn:ietf:params:xml:ns:yang:ietf-inet-types";
+   prefix "inet";
+
+   organization
+    "IETF NETMOD (NETCONF Data Modeling Language) Working Group";
+
+   contact
+    "WG Web:   <http://tools.ietf.org/wg/netmod/>
+     WG List:  <mailto:netmod@ietf.org>
+
+     WG Chair: David Partain
+               <mailto:david.partain@ericsson.com>
+
+     WG Chair: David Kessens
+               <mailto:david.kessens@nsn.com>
+
+     Editor:   Juergen Schoenwaelder
+               <mailto:j.schoenwaelder@jacobs-university.de>";
+
+   description
+    "This module contains a collection of generally useful derived
+     YANG data types for Internet addresses and related things.
+
+     Copyright (c) 2010 IETF Trust and the persons identified as
+     authors of the code.  All rights reserved.
+
+     Redistribution and use in source and binary forms, with or without
+     modification, is permitted pursuant to, and subject to the license
+     terms contained in, the Simplified BSD License set forth in Section
+     4.c of the IETF Trust's Legal Provisions Relating to IETF Documents
+     (http://trustee.ietf.org/license-info).
+
+     This version of this YANG module is part of RFC 6021; see
+     the RFC itself for full legal notices.";
+
+   revision 2010-09-24 {
+     description
+      "Initial revision.";
+     reference
+      "RFC 6021: Common YANG Data Types";
+   }
+
+   /*** collection of protocol field related types ***/
+
+   typedef ip-version {
+     type enumeration {
+       enum unknown {
+         value "0";
+         description
+          "An unknown or unspecified version of the Internet protocol.";
+       }
+       enum ipv4 {
+         value "1";
+         description
+          "The IPv4 protocol as defined in RFC 791.";
+       }
+       enum ipv6 {
+         value "2";
+         description
+          "The IPv6 protocol as defined in RFC 2460.";
+       }
+     }
+     description
+      "This value represents the version of the IP protocol.
+
+       In the value set and its semantics, this type is equivalent
+       to the InetVersion textual convention of the SMIv2.";
+     reference
+      "RFC  791: Internet Protocol
+       RFC 2460: Internet Protocol, Version 6 (IPv6) Specification
+       RFC 4001: Textual Conventions for Internet Network Addresses";
+   }
+
+   typedef dscp {
+     type uint8 {
+       range "0..63";
+     }
+     description
+      "The dscp type represents a Differentiated Services Code-Point
+       that may be used for marking packets in a traffic stream.
+
+       In the value set and its semantics, this type is equivalent
+       to the Dscp textual convention of the SMIv2.";
+     reference
+      "RFC 3289: Management Information Base for the Differentiated
+                 Services Architecture
+       RFC 2474: Definition of the Differentiated Services Field
+                 (DS Field) in the IPv4 and IPv6 Headers
+       RFC 2780: IANA Allocation Guidelines For Values In
+                 the Internet Protocol and Related Headers";
+   }
+
+   typedef ipv6-flow-label {
+     type uint32 {
+       range "0..1048575";
+     }
+     description
+      "The flow-label type represents flow identifier or Flow Label
+       in an IPv6 packet header that may be used to discriminate
+       traffic flows.
+
+       In the value set and its semantics, this type is equivalent
+       to the IPv6FlowLabel textual convention of the SMIv2.";
+     reference
+      "RFC 3595: Textual Conventions for IPv6 Flow Label
+       RFC 2460: Internet Protocol, Version 6 (IPv6) Specification";
+   }
+
+   typedef port-number {
+     type uint16 {
+       range "0..65535";
+     }
+     description
+      "The port-number type represents a 16-bit port number of an
+       Internet transport layer protocol such as UDP, TCP, DCCP, or
+       SCTP.  Port numbers are assigned by IANA.  A current list of
+       all assignments is available from <http://www.iana.org/>.
+
+       Note that the port number value zero is reserved by IANA.  In
+       situations where the value zero does not make sense, it can
+       be excluded by subtyping the port-number type.
+
+       In the value set and its semantics, this type is equivalent
+       to the InetPortNumber textual convention of the SMIv2.";
+     reference
+      "RFC  768: User Datagram Protocol
+       RFC  793: Transmission Control Protocol
+       RFC 4960: Stream Control Transmission Protocol
+       RFC 4340: Datagram Congestion Control Protocol (DCCP)
+       RFC 4001: Textual Conventions for Internet Network Addresses";
+   }
+
+   /*** collection of autonomous system related types ***/
+
+   typedef as-number {
+     type uint32;
+     description
+      "The as-number type represents autonomous system numbers
+       which identify an Autonomous System (AS).  An AS is a set
+       of routers under a single technical administration, using
+       an interior gateway protocol and common metrics to route
+       packets within the AS, and using an exterior gateway
+       protocol to route packets to other ASs'.  IANA maintains
+       the AS number space and has delegated large parts to the
+       regional registries.
+
+       Autonomous system numbers were originally limited to 16
+       bits.  BGP extensions have enlarged the autonomous system
+       number space to 32 bits.  This type therefore uses an uint32
+       base type without a range restriction in order to support
+       a larger autonomous system number space.
+
+       In the value set and its semantics, this type is equivalent
+       to the InetAutonomousSystemNumber textual convention of
+       the SMIv2.";
+     reference
+      "RFC 1930: Guidelines for creation, selection, and registration
+                 of an Autonomous System (AS)
+       RFC 4271: A Border Gateway Protocol 4 (BGP-4)
+       RFC 4893: BGP Support for Four-octet AS Number Space
+       RFC 4001: Textual Conventions for Internet Network Addresses";
+   }
+
+   /*** collection of IP address and hostname related types ***/
+
+   typedef ip-address {
+     type union {
+       type inet:ipv4-address;
+       type inet:ipv6-address;
+     }
+     description
+      "The ip-address type represents an IP address and is IP
+       version neutral.  The format of the textual representations
+       implies the IP version.";
+   }
+
+   typedef ipv4-address {
+     type string {
+       pattern
+         '(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
+       +  '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
+       + '(%[\p{N}\p{L}]+)?';
+     }
+     description
+       "The ipv4-address type represents an IPv4 address in
+        dotted-quad notation.  The IPv4 address may include a zone
+        index, separated by a % sign.
+
+        The zone index is used to disambiguate identical address
+        values.  For link-local addresses, the zone index will
+        typically be the interface index number or the name of an
+        interface.  If the zone index is not present, the default
+        zone of the device will be used.
+
+        The canonical format for the zone index is the numerical
+        format";
+   }
+
+   typedef ipv6-address {
+     type string {
+       pattern '((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}'
+             + '((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|'
+             + '(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}'
+             + '(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))'
+             + '(%[\p{N}\p{L}]+)?';
+       pattern '(([^:]+:){6}(([^:]+:[^:]+)|(.*\..*)))|'
+             + '((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)'
+             + '(%.+)?';
+     }
+     description
+      "The ipv6-address type represents an IPv6 address in full,
+       mixed, shortened, and shortened-mixed notation.  The IPv6
+       address may include a zone index, separated by a % sign.
+
+       The zone index is used to disambiguate identical address
+       values.  For link-local addresses, the zone index will
+       typically be the interface index number or the name of an
+       interface.  If the zone index is not present, the default
+       zone of the device will be used.
+
+       The canonical format of IPv6 addresses uses the compressed
+       format described in RFC 4291, Section 2.2, item 2 with the
+       following additional rules: the :: substitution must be
+       applied to the longest sequence of all-zero 16-bit chunks
+       in an IPv6 address.  If there is a tie, the first sequence
+       of all-zero 16-bit chunks is replaced by ::.  Single
+       all-zero 16-bit chunks are not compressed.  The canonical
+       format uses lowercase characters and leading zeros are
+       not allowed.  The canonical format for the zone index is
+       the numerical format as described in RFC 4007, Section
+       11.2.";
+     reference
+      "RFC 4291: IP Version 6 Addressing Architecture
+       RFC 4007: IPv6 Scoped Address Architecture
+       RFC 5952: A Recommendation for IPv6 Address Text Representation";
+   }
+
+   typedef ip-prefix {
+     type union {
+       type inet:ipv4-prefix;
+       type inet:ipv6-prefix;
+     }
+     description
+      "The ip-prefix type represents an IP prefix and is IP
+       version neutral.  The format of the textual representations
+       implies the IP version.";
+   }
+
+   typedef ipv4-prefix {
+     type string {
+       pattern
+          '(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}'
+        +  '([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])'
+        + '/(([0-9])|([1-2][0-9])|(3[0-2]))';
+     }
+     description
+      "The ipv4-prefix type represents an IPv4 address prefix.
+       The prefix length is given by the number following the
+       slash character and must be less than or equal to 32.
+
+       A prefix length value of n corresponds to an IP address
+       mask that has n contiguous 1-bits from the most
+       significant bit (MSB) and all other bits set to 0.
+
+       The canonical format of an IPv4 prefix has all bits of
+       the IPv4 address set to zero that are not part of the
+       IPv4 prefix.";
+   }
+
+   typedef ipv6-prefix {
+     type string {
+       pattern '((:|[0-9a-fA-F]{0,4}):)([0-9a-fA-F]{0,4}:){0,5}'
+             + '((([0-9a-fA-F]{0,4}:)?(:|[0-9a-fA-F]{0,4}))|'
+             + '(((25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])\.){3}'
+             + '(25[0-5]|2[0-4][0-9]|[01]?[0-9]?[0-9])))'
+             + '(/(([0-9])|([0-9]{2})|(1[0-1][0-9])|(12[0-8])))';
+       pattern '(([^:]+:){6}(([^:]+:[^:]+)|(.*\..*)))|'
+             + '((([^:]+:)*[^:]+)?::(([^:]+:)*[^:]+)?)'
+             + '(/.+)';
+     }
+     description
+      "The ipv6-prefix type represents an IPv6 address prefix.
+       The prefix length is given by the number following the
+       slash character and must be less than or equal 128.
+
+       A prefix length value of n corresponds to an IP address
+       mask that has n contiguous 1-bits from the most
+       significant bit (MSB) and all other bits set to 0.
+
+       The IPv6 address should have all bits that do not belong
+       to the prefix set to zero.
+
+       The canonical format of an IPv6 prefix has all bits of
+       the IPv6 address set to zero that are not part of the
+       IPv6 prefix.  Furthermore, IPv6 address is represented
+       in the compressed format described in RFC 4291, Section
+       2.2, item 2 with the following additional rules: the ::
+       substitution must be applied to the longest sequence of
+       all-zero 16-bit chunks in an IPv6 address.  If there is
+       a tie, the first sequence of all-zero 16-bit chunks is
+       replaced by ::.  Single all-zero 16-bit chunks are not
+       compressed.  The canonical format uses lowercase
+       characters and leading zeros are not allowed.";
+     reference
+      "RFC 4291: IP Version 6 Addressing Architecture";
+   }
+
+   /*** collection of domain name and URI types ***/
+
+   typedef domain-name {
+     type string {
+       pattern '((([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.)*'
+            +  '([a-zA-Z0-9_]([a-zA-Z0-9\-_]){0,61})?[a-zA-Z0-9]\.?)'
+            +  '|\.';
+       length "1..253";
+     }
+     description
+      "The domain-name type represents a DNS domain name.  The
+       name SHOULD be fully qualified whenever possible.
+
+       Internet domain names are only loosely specified.  Section
+       3.5 of RFC 1034 recommends a syntax (modified in Section
+       2.1 of RFC 1123).  The pattern above is intended to allow
+       for current practice in domain name use, and some possible
+       future expansion.  It is designed to hold various types of
+       domain names, including names used for A or AAAA records
+       (host names) and other records, such as SRV records.  Note
+       that Internet host names have a stricter syntax (described
+       in RFC 952) than the DNS recommendations in RFCs 1034 and
+       1123, and that systems that want to store host names in
+       schema nodes using the domain-name type are recommended to
+       adhere to this stricter standard to ensure interoperability.
+
+       The encoding of DNS names in the DNS protocol is limited
+       to 255 characters.  Since the encoding consists of labels
+       prefixed by a length bytes and there is a trailing NULL
+       byte, only 253 characters can appear in the textual dotted
+       notation.
+
+       The description clause of schema nodes using the domain-name
+       type MUST describe when and how these names are resolved to
+       IP addresses.  Note that the resolution of a domain-name value
+       may require to query multiple DNS records (e.g., A for IPv4
+       and AAAA for IPv6).  The order of the resolution process and
+       which DNS record takes precedence can either be defined
+       explicitely or it may depend on the configuration of the
+       resolver.
+
+       Domain-name values use the US-ASCII encoding.  Their canonical
+       format uses lowercase US-ASCII characters.  Internationalized
+       domain names MUST be encoded in punycode as described in RFC
+       3492";
+     reference
+      "RFC  952: DoD Internet Host Table Specification
+       RFC 1034: Domain Names - Concepts and Facilities
+       RFC 1123: Requirements for Internet Hosts -- Application
+                 and Support
+       RFC 2782: A DNS RR for specifying the location of services
+                 (DNS SRV)
+       RFC 3492: Punycode: A Bootstring encoding of Unicode for
+                 Internationalized Domain Names in Applications
+                 (IDNA)
+       RFC 5891: Internationalizing Domain Names in Applications
+                 (IDNA): Protocol";
+   }
+
+   typedef host {
+     type union {
+       type inet:ip-address;
+       type inet:domain-name;
+     }
+     description
+      "The host type represents either an IP address or a DNS
+       domain name.";
+   }
+
+   typedef uri {
+     type string;
+     description
+      "The uri type represents a Uniform Resource Identifier
+       (URI) as defined by STD 66.
+
+       Objects using the uri type MUST be in US-ASCII encoding,
+       and MUST be normalized as described by RFC 3986 Sections
+       6.2.1, 6.2.2.1, and 6.2.2.2.  All unnecessary
+       percent-encoding is removed, and all case-insensitive
+       characters are set to lowercase except for hexadecimal
+       digits, which are normalized to uppercase as described in
+       Section 6.2.2.1.
+
+       The purpose of this normalization is to help provide
+       unique URIs.  Note that this normalization is not
+       sufficient to provide uniqueness.  Two URIs that are
+       textually distinct after this normalization may still be
+       equivalent.
+
+       Objects using the uri type may restrict the schemes that
+       they permit.  For example, 'data:' and 'urn:' schemes
+       might not be appropriate.
+
+       A zero-length URI is not a valid URI.  This can be used to
+       express 'URI absent' where required.
+
+       In the value set and its semantics, this type is equivalent
+       to the Uri SMIv2 textual convention defined in RFC 5017.";
+     reference
+      "RFC 3986: Uniform Resource Identifier (URI): Generic Syntax
+       RFC 3305: Report from the Joint W3C/IETF URI Planning Interest
+                 Group: Uniform Resource Identifiers (URIs), URLs,
+                 and Uniform Resource Names (URNs): Clarifications
+                 and Recommendations
+       RFC 5017: MIB Textual Conventions for Uniform Resource
+                 Identifiers (URIs)";
+   }
+
+ }
diff --git a/opendaylight/netconf/netconf-cli/src/test/resources/schema-context/ietf-netconf.yang b/opendaylight/netconf/netconf-cli/src/test/resources/schema-context/ietf-netconf.yang
new file mode 100644 (file)
index 0000000..44c19c3
--- /dev/null
@@ -0,0 +1,927 @@
+module ietf-netconf {
+
+  // the namespace for NETCONF XML definitions is unchanged
+  // from RFC 4741, which this document replaces
+  namespace "urn:ietf:params:xml:ns:netconf:base:1.0";
+
+  prefix nc;
+
+  import ietf-inet-types {
+    prefix inet;
+  }
+
+  organization
+    "IETF NETCONF (Network Configuration) Working Group";
+
+  contact
+    "WG Web:   <http://tools.ietf.org/wg/netconf/>
+     WG List:  <netconf@ietf.org>
+
+     WG Chair: Bert Wijnen
+               <bertietf@bwijnen.net>
+
+     WG Chair: Mehmet Ersue
+               <mehmet.ersue@nsn.com>
+
+     Editor:   Martin Bjorklund
+               <mbj@tail-f.com>
+
+     Editor:   Juergen Schoenwaelder
+               <j.schoenwaelder@jacobs-university.de>
+
+     Editor:   Andy Bierman
+               <andy.bierman@brocade.com>";
+  description
+    "NETCONF Protocol Data Types and Protocol Operations.
+
+     Copyright (c) 2011 IETF Trust and the persons identified as
+     the document authors.  All rights reserved.
+
+     Redistribution and use in source and binary forms, with or
+     without modification, is permitted pursuant to, and subject
+     to the license terms contained in, the Simplified BSD License
+     set forth in Section 4.c of the IETF Trust's Legal Provisions
+     Relating to IETF Documents
+     (http://trustee.ietf.org/license-info).
+
+     This version of this YANG module is part of RFC 6241; see
+     the RFC itself for full legal notices.";
+  revision 2011-06-01 {
+    description
+      "Initial revision";
+    reference
+      "RFC 6241: Network Configuration Protocol";
+  }
+
+  extension get-filter-element-attributes {
+    description
+      "If this extension is present within an 'anyxml'
+       statement named 'filter', which must be conceptually
+       defined within the RPC input section for the <get>
+       and <get-config> protocol operations, then the
+       following unqualified XML attribute is supported
+       within the <filter> element, within a <get> or
+       <get-config> protocol operation:
+
+         type : optional attribute with allowed
+                value strings 'subtree' and 'xpath'.
+                If missing, the default value is 'subtree'.
+
+       If the 'xpath' feature is supported, then the
+       following unqualified XML attribute is
+       also supported:
+
+         select: optional attribute containing a
+                 string representing an XPath expression.
+                 The 'type' attribute must be equal to 'xpath'
+                 if this attribute is present.";
+  }
+
+  // NETCONF capabilities defined as features
+  feature writable-running {
+    description
+      "NETCONF :writable-running capability;
+       If the server advertises the :writable-running
+       capability for a session, then this feature must
+       also be enabled for that session.  Otherwise,
+       this feature must not be enabled.";
+    reference "RFC 6241, Section 8.2";
+  }
+
+  feature candidate {
+    description
+      "NETCONF :candidate capability;
+       If the server advertises the :candidate
+       capability for a session, then this feature must
+       also be enabled for that session.  Otherwise,
+       this feature must not be enabled.";
+    reference "RFC 6241, Section 8.3";
+  }
+
+  feature confirmed-commit {
+    if-feature candidate;
+    description
+      "NETCONF :confirmed-commit:1.1 capability;
+       If the server advertises the :confirmed-commit:1.1
+       capability for a session, then this feature must
+       also be enabled for that session.  Otherwise,
+       this feature must not be enabled.";
+
+    reference "RFC 6241, Section 8.4";
+  }
+
+  feature rollback-on-error {
+    description
+      "NETCONF :rollback-on-error capability;
+       If the server advertises the :rollback-on-error
+       capability for a session, then this feature must
+       also be enabled for that session.  Otherwise,
+       this feature must not be enabled.";
+    reference "RFC 6241, Section 8.5";
+  }
+
+  feature validate {
+    description
+      "NETCONF :validate:1.1 capability;
+       If the server advertises the :validate:1.1
+       capability for a session, then this feature must
+       also be enabled for that session.  Otherwise,
+       this feature must not be enabled.";
+    reference "RFC 6241, Section 8.6";
+  }
+
+  feature startup {
+    description
+      "NETCONF :startup capability;
+       If the server advertises the :startup
+       capability for a session, then this feature must
+       also be enabled for that session.  Otherwise,
+       this feature must not be enabled.";
+    reference "RFC 6241, Section 8.7";
+  }
+
+  feature url {
+    description
+      "NETCONF :url capability;
+       If the server advertises the :url
+       capability for a session, then this feature must
+       also be enabled for that session.  Otherwise,
+       this feature must not be enabled.";
+    reference "RFC 6241, Section 8.8";
+  }
+
+  feature xpath {
+    description
+      "NETCONF :xpath capability;
+       If the server advertises the :xpath
+       capability for a session, then this feature must
+       also be enabled for that session.  Otherwise,
+       this feature must not be enabled.";
+    reference "RFC 6241, Section 8.9";
+  }
+
+  // NETCONF Simple Types
+
+  typedef session-id-type {
+    type uint32 {
+      range "1..max";
+    }
+    description
+      "NETCONF Session Id";
+  }
+
+  typedef session-id-or-zero-type {
+    type uint32;
+    description
+      "NETCONF Session Id or Zero to indicate none";
+  }
+  typedef error-tag-type {
+    type enumeration {
+       enum in-use {
+         description
+           "The request requires a resource that
+            already is in use.";
+       }
+       enum invalid-value {
+         description
+           "The request specifies an unacceptable value for one
+            or more parameters.";
+       }
+       enum too-big {
+         description
+           "The request or response (that would be generated) is
+            too large for the implementation to handle.";
+       }
+       enum missing-attribute {
+         description
+           "An expected attribute is missing.";
+       }
+       enum bad-attribute {
+         description
+           "An attribute value is not correct; e.g., wrong type,
+            out of range, pattern mismatch.";
+       }
+       enum unknown-attribute {
+         description
+           "An unexpected attribute is present.";
+       }
+       enum missing-element {
+         description
+           "An expected element is missing.";
+       }
+       enum bad-element {
+         description
+           "An element value is not correct; e.g., wrong type,
+            out of range, pattern mismatch.";
+       }
+       enum unknown-element {
+         description
+           "An unexpected element is present.";
+       }
+       enum unknown-namespace {
+         description
+           "An unexpected namespace is present.";
+       }
+       enum access-denied {
+         description
+           "Access to the requested protocol operation or
+            data model is denied because authorization failed.";
+       }
+       enum lock-denied {
+         description
+           "Access to the requested lock is denied because the
+            lock is currently held by another entity.";
+       }
+       enum resource-denied {
+         description
+           "Request could not be completed because of
+            insufficient resources.";
+       }
+       enum rollback-failed {
+         description
+           "Request to roll back some configuration change (via
+            rollback-on-error or <discard-changes> operations)
+            was not completed for some reason.";
+
+       }
+       enum data-exists {
+         description
+           "Request could not be completed because the relevant
+            data model content already exists.  For example,
+            a 'create' operation was attempted on data that
+            already exists.";
+       }
+       enum data-missing {
+         description
+           "Request could not be completed because the relevant
+            data model content does not exist.  For example,
+            a 'delete' operation was attempted on
+            data that does not exist.";
+       }
+       enum operation-not-supported {
+         description
+           "Request could not be completed because the requested
+            operation is not supported by this implementation.";
+       }
+       enum operation-failed {
+         description
+           "Request could not be completed because the requested
+            operation failed for some reason not covered by
+            any other error condition.";
+       }
+       enum partial-operation {
+         description
+           "This error-tag is obsolete, and SHOULD NOT be sent
+            by servers conforming to this document.";
+       }
+       enum malformed-message {
+         description
+           "A message could not be handled because it failed to
+            be parsed correctly.  For example, the message is not
+            well-formed XML or it uses an invalid character set.";
+       }
+     }
+     description "NETCONF Error Tag";
+     reference "RFC 6241, Appendix A";
+  }
+
+  typedef error-severity-type {
+    type enumeration {
+      enum error {
+        description "Error severity";
+      }
+      enum warning {
+        description "Warning severity";
+      }
+    }
+    description "NETCONF Error Severity";
+    reference "RFC 6241, Section 4.3";
+  }
+
+  typedef edit-operation-type {
+    type enumeration {
+      enum merge {
+        description
+          "The configuration data identified by the
+           element containing this attribute is merged
+           with the configuration at the corresponding
+           level in the configuration datastore identified
+           by the target parameter.";
+      }
+      enum replace {
+        description
+          "The configuration data identified by the element
+           containing this attribute replaces any related
+           configuration in the configuration datastore
+           identified by the target parameter.  If no such
+           configuration data exists in the configuration
+           datastore, it is created.  Unlike a
+           <copy-config> operation, which replaces the
+           entire target configuration, only the configuration
+           actually present in the config parameter is affected.";
+      }
+      enum create {
+        description
+          "The configuration data identified by the element
+           containing this attribute is added to the
+           configuration if and only if the configuration
+           data does not already exist in the configuration
+           datastore.  If the configuration data exists, an
+           <rpc-error> element is returned with an
+           <error-tag> value of 'data-exists'.";
+      }
+      enum delete {
+        description
+          "The configuration data identified by the element
+           containing this attribute is deleted from the
+           configuration if and only if the configuration
+           data currently exists in the configuration
+           datastore.  If the configuration data does not
+           exist, an <rpc-error> element is returned with
+           an <error-tag> value of 'data-missing'.";
+      }
+      enum remove {
+        description
+          "The configuration data identified by the element
+           containing this attribute is deleted from the
+           configuration if the configuration
+           data currently exists in the configuration
+           datastore.  If the configuration data does not
+           exist, the 'remove' operation is silently ignored
+           by the server.";
+      }
+    }
+    default "merge";
+    description "NETCONF 'operation' attribute values";
+    reference "RFC 6241, Section 7.2";
+  }
+
+  // NETCONF Standard Protocol Operations
+
+  rpc get-config {
+    description
+      "Retrieve all or part of a specified configuration.";
+
+    reference "RFC 6241, Section 7.1";
+
+    input {
+      container source {
+        description
+          "Particular configuration to retrieve.";
+
+        choice config-source {
+          mandatory true;
+          description
+            "The configuration to retrieve.";
+          leaf candidate {
+            if-feature candidate;
+            type empty;
+            description
+              "The candidate configuration is the config source.";
+          }
+          leaf running {
+            type empty;
+            description
+              "The running configuration is the config source.";
+          }
+          leaf startup {
+            if-feature startup;
+            type empty;
+            description
+              "The startup configuration is the config source.
+               This is optional-to-implement on the server because
+               not all servers will support filtering for this
+               datastore.";
+          }
+        }
+      }
+
+      anyxml filter {
+        description
+          "Subtree or XPath filter to use.";
+        nc:get-filter-element-attributes;
+      }
+    }
+
+    output {
+      anyxml data {
+        description
+          "Copy of the source datastore subset that matched
+           the filter criteria (if any).  An empty data container
+           indicates that the request did not produce any results.";
+      }
+    }
+  }
+
+  rpc edit-config {
+    description
+      "The <edit-config> operation loads all or part of a specified
+       configuration to the specified target configuration.";
+
+    reference "RFC 6241, Section 7.2";
+
+    input {
+      container target {
+        description
+          "Particular configuration to edit.";
+
+        choice config-target {
+          mandatory true;
+          description
+            "The configuration target.";
+
+          leaf candidate {
+            if-feature candidate;
+            type empty;
+            description
+              "The candidate configuration is the config target.";
+          }
+          leaf running {
+            if-feature writable-running;
+            type empty;
+            description
+              "The running configuration is the config source.";
+          }
+        }
+      }
+
+      leaf default-operation {
+        type enumeration {
+          enum merge {
+            description
+              "The default operation is merge.";
+          }
+          enum replace {
+            description
+              "The default operation is replace.";
+          }
+          enum none {
+            description
+              "There is no default operation.";
+          }
+        }
+        default "merge";
+        description
+          "The default operation to use.";
+      }
+
+      leaf test-option {
+        if-feature validate;
+        type enumeration {
+          enum test-then-set {
+            description
+              "The server will test and then set if no errors.";
+          }
+          enum set {
+            description
+              "The server will set without a test first.";
+          }
+
+          enum test-only {
+            description
+              "The server will only test and not set, even
+               if there are no errors.";
+          }
+        }
+        default "test-then-set";
+        description
+          "The test option to use.";
+      }
+
+      leaf error-option {
+        type enumeration {
+          enum stop-on-error {
+            description
+              "The server will stop on errors.";
+          }
+          enum continue-on-error {
+            description
+              "The server may continue on errors.";
+          }
+          enum rollback-on-error {
+            description
+              "The server will roll back on errors.
+               This value can only be used if the 'rollback-on-error'
+               feature is supported.";
+          }
+        }
+        default "stop-on-error";
+        description
+          "The error option to use.";
+      }
+
+      choice edit-content {
+        mandatory true;
+        description
+          "The content for the edit operation.";
+
+        anyxml config {
+          description
+            "Inline Config content.";
+        }
+        leaf url {
+          if-feature url;
+          type inet:uri;
+          description
+            "URL-based config content.";
+        }
+      }
+    }
+  }
+
+  rpc copy-config {
+    description
+      "Create or replace an entire configuration datastore with the
+       contents of another complete configuration datastore.";
+
+    reference "RFC 6241, Section 7.3";
+
+    input {
+      container target {
+        description
+          "Particular configuration to copy to.";
+
+        choice config-target {
+          mandatory true;
+          description
+            "The configuration target of the copy operation.";
+
+          leaf candidate {
+            if-feature candidate;
+            type empty;
+            description
+              "The candidate configuration is the config target.";
+          }
+          leaf running {
+            if-feature writable-running;
+            type empty;
+            description
+              "The running configuration is the config target.
+               This is optional-to-implement on the server.";
+          }
+          leaf startup {
+            if-feature startup;
+            type empty;
+            description
+              "The startup configuration is the config target.";
+          }
+          leaf url {
+            if-feature url;
+            type inet:uri;
+            description
+              "The URL-based configuration is the config target.";
+          }
+        }
+      }
+
+      container source {
+        description
+          "Particular configuration to copy from.";
+
+        choice config-source {
+          mandatory true;
+          description
+            "The configuration source for the copy operation.";
+
+          leaf candidate {
+            if-feature candidate;
+            type empty;
+            description
+              "The candidate configuration is the config source.";
+          }
+          leaf running {
+            type empty;
+            description
+              "The running configuration is the config source.";
+          }
+          leaf startup {
+            if-feature startup;
+            type empty;
+            description
+              "The startup configuration is the config source.";
+          }
+          leaf url {
+            if-feature url;
+            type inet:uri;
+            description
+              "The URL-based configuration is the config source.";
+          }
+          anyxml config {
+            description
+              "Inline Config content: <config> element.  Represents
+               an entire configuration datastore, not
+               a subset of the running datastore.";
+          }
+        }
+      }
+    }
+  }
+
+  rpc delete-config {
+    description
+      "Delete a configuration datastore.";
+
+    reference "RFC 6241, Section 7.4";
+
+    input {
+      container target {
+        description
+          "Particular configuration to delete.";
+
+        choice config-target {
+          mandatory true;
+          description
+            "The configuration target to delete.";
+
+          leaf startup {
+            if-feature startup;
+            type empty;
+            description
+              "The startup configuration is the config target.";
+          }
+          leaf url {
+            if-feature url;
+            type inet:uri;
+            description
+              "The URL-based configuration is the config target.";
+          }
+        }
+      }
+    }
+  }
+
+  rpc lock {
+    description
+      "The lock operation allows the client to lock the configuration
+       system of a device.";
+
+    reference "RFC 6241, Section 7.5";
+
+    input {
+      container target {
+        description
+          "Particular configuration to lock.";
+
+        choice config-target {
+          mandatory true;
+          description
+            "The configuration target to lock.";
+
+          leaf candidate {
+            if-feature candidate;
+            type empty;
+            description
+              "The candidate configuration is the config target.";
+          }
+          leaf running {
+            type empty;
+            description
+              "The running configuration is the config target.";
+          }
+          leaf startup {
+            if-feature startup;
+            type empty;
+            description
+              "The startup configuration is the config target.";
+          }
+        }
+      }
+    }
+  }
+
+  rpc unlock {
+    description
+      "The unlock operation is used to release a configuration lock,
+       previously obtained with the 'lock' operation.";
+
+    reference "RFC 6241, Section 7.6";
+
+    input {
+      container target {
+        description
+          "Particular configuration to unlock.";
+
+        choice config-target {
+          mandatory true;
+          description
+            "The configuration target to unlock.";
+
+          leaf candidate {
+            if-feature candidate;
+            type empty;
+            description
+              "The candidate configuration is the config target.";
+          }
+          leaf running {
+            type empty;
+            description
+              "The running configuration is the config target.";
+          }
+          leaf startup {
+            if-feature startup;
+            type empty;
+            description
+              "The startup configuration is the config target.";
+          }
+        }
+      }
+    }
+  }
+
+  rpc get {
+    description
+      "Retrieve running configuration and device state information.";
+
+    reference "RFC 6241, Section 7.7";
+
+    input {
+      anyxml filter {
+        description
+          "This parameter specifies the portion of the system
+           configuration and state data to retrieve.";
+        nc:get-filter-element-attributes;
+      }
+    }
+
+    output {
+      anyxml data {
+        description
+          "Copy of the running datastore subset and/or state
+           data that matched the filter criteria (if any).
+           An empty data container indicates that the request did not
+           produce any results.";
+      }
+    }
+  }
+
+  rpc close-session {
+    description
+      "Request graceful termination of a NETCONF session.";
+
+    reference "RFC 6241, Section 7.8";
+  }
+
+  rpc kill-session {
+    description
+      "Force the termination of a NETCONF session.";
+
+    reference "RFC 6241, Section 7.9";
+
+    input {
+      leaf session-id {
+        type session-id-type;
+        mandatory true;
+        description
+          "Particular session to kill.";
+      }
+    }
+  }
+
+  rpc commit {
+    if-feature candidate;
+
+    description
+      "Commit the candidate configuration as the device's new
+       current configuration.";
+
+    reference "RFC 6241, Section 8.3.4.1";
+
+    input {
+      leaf confirmed {
+        if-feature confirmed-commit;
+        type empty;
+        description
+          "Requests a confirmed commit.";
+        reference "RFC 6241, Section 8.3.4.1";
+      }
+
+      leaf confirm-timeout {
+        if-feature confirmed-commit;
+        type uint32 {
+          range "1..max";
+        }
+        units "seconds";
+        default "600";   // 10 minutes
+        description
+          "The timeout interval for a confirmed commit.";
+        reference "RFC 6241, Section 8.3.4.1";
+      }
+
+      leaf persist {
+        if-feature confirmed-commit;
+        type string;
+        description
+          "This parameter is used to make a confirmed commit
+           persistent.  A persistent confirmed commit is not aborted
+           if the NETCONF session terminates.  The only way to abort
+           a persistent confirmed commit is to let the timer expire,
+           or to use the <cancel-commit> operation.
+
+           The value of this parameter is a token that must be given
+           in the 'persist-id' parameter of <commit> or
+           <cancel-commit> operations in order to confirm or cancel
+           the persistent confirmed commit.
+
+           The token should be a random string.";
+        reference "RFC 6241, Section 8.3.4.1";
+      }
+
+      leaf persist-id {
+        if-feature confirmed-commit;
+        type string;
+        description
+          "This parameter is given in order to commit a persistent
+           confirmed commit.  The value must be equal to the value
+           given in the 'persist' parameter to the <commit> operation.
+           If it does not match, the operation fails with an
+          'invalid-value' error.";
+        reference "RFC 6241, Section 8.3.4.1";
+      }
+
+    }
+  }
+
+  rpc discard-changes {
+    if-feature candidate;
+
+    description
+      "Revert the candidate configuration to the current
+       running configuration.";
+    reference "RFC 6241, Section 8.3.4.2";
+  }
+
+  rpc cancel-commit {
+    if-feature confirmed-commit;
+    description
+      "This operation is used to cancel an ongoing confirmed commit.
+       If the confirmed commit is persistent, the parameter
+       'persist-id' must be given, and it must match the value of the
+       'persist' parameter.";
+    reference "RFC 6241, Section 8.4.4.1";
+
+    input {
+      leaf persist-id {
+        type string;
+        description
+          "This parameter is given in order to cancel a persistent
+           confirmed commit.  The value must be equal to the value
+           given in the 'persist' parameter to the <commit> operation.
+           If it does not match, the operation fails with an
+          'invalid-value' error.";
+      }
+    }
+  }
+
+  rpc validate {
+    if-feature validate;
+
+    description
+      "Validates the contents of the specified configuration.";
+
+    reference "RFC 6241, Section 8.6.4.1";
+
+    input {
+      container source {
+        description
+          "Particular configuration to validate.";
+
+        choice config-source {
+          mandatory true;
+          description
+            "The configuration source to validate.";
+
+          leaf candidate {
+            if-feature candidate;
+            type empty;
+            description
+              "The candidate configuration is the config source.";
+          }
+          leaf running {
+            type empty;
+            description
+              "The running configuration is the config source.";
+          }
+          leaf startup {
+            if-feature startup;
+            type empty;
+            description
+              "The startup configuration is the config source.";
+          }
+          leaf url {
+            if-feature url;
+            type inet:uri;
+            description
+              "The URL-based configuration is the config source.";
+          }
+          anyxml config {
+            description
+              "Inline Config content: <config> element.  Represents
+               an entire configuration datastore, not
+               a subset of the running datastore.";
+          }
+        }
+      }
+    }
+  }
+
+}
diff --git a/opendaylight/netconf/netconf-cli/src/test/resources/schema-context/model1.yang b/opendaylight/netconf/netconf-cli/src/test/resources/schema-context/model1.yang
new file mode 100644 (file)
index 0000000..c84d55f
--- /dev/null
@@ -0,0 +1,74 @@
+module model1 {
+  namespace "ns:model1";
+  prefix "mod1";
+
+  revision "2014-05-14" {
+  }
+
+  container cont1 {
+    container cont11 {
+        list lst111 {
+            key lf1111;
+            leaf lf1111 {
+                type int32;
+            }
+            container cont111 {
+                leaf lf1112 {
+                    type string;
+                }
+                leaf-list lflst1111 {
+                    type int8;
+                }
+            }
+        }
+    }
+
+    container cont12 {
+        list lst121 {
+            key lf1211;
+            leaf lf1211 {
+                type string;
+            }
+            list lst1211 {
+                leaf lf12111 {
+                    type uint8;
+                }
+                leaf lf12112 {
+                    type string;
+                }
+            }
+        }
+        choice chcA {
+            case AA {
+                leaf lf12AA1 {
+                    type string;
+                }
+            }
+            case AB {
+                container cont12AB1 {
+                    leaf lf12AB1 {
+                        type string;
+                    }
+                }
+            }
+            leaf lf121 { //should be standalone case
+                type string;
+            }
+        }
+        list lst122 {
+        }
+    }
+  }
+
+  container cont2 {
+    container cont23 {
+    }
+  }
+
+  container contA {
+  }
+
+  container contB {
+  }
+
+}
\ No newline at end of file
diff --git a/opendaylight/netconf/netconf-cli/src/test/resources/schema-context/model2.yang b/opendaylight/netconf/netconf-cli/src/test/resources/schema-context/model2.yang
new file mode 100644 (file)
index 0000000..e92cbd7
--- /dev/null
@@ -0,0 +1,32 @@
+module model2 {
+  namespace "ns:model2";
+  prefix "mod2";
+
+  import model1 {prefix model1; revision-date 2014-05-14;}
+
+  revision "2014-05-14" {
+  }
+
+  container contA {
+  }
+
+  container contB {
+  }
+
+  augment "/model1:cont2" {
+    container cont21 {
+    }
+
+    container cont22 {
+    }
+  }
+
+  augment "/model1:cont1" {
+    list lst11 {
+       leaf lf111 {
+        type string;
+       }
+    }
+  }
+
+}
\ No newline at end of file
index 148b0446e309f4470f55ee0205e7be6cd429499d..eb99be0dc08f006ece7f7a93193f103bfa2bfb61 100644 (file)
@@ -18,17 +18,18 @@ import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertCo
 import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertElementsCount;
 import static org.opendaylight.controller.netconf.util.xml.XmlUtil.readXmlToDocument;
 
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+import io.netty.channel.ChannelFuture;
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.InetSocketAddress;
 import java.util.Collection;
 import java.util.List;
 import java.util.Set;
-
 import javax.management.InstanceNotFoundException;
 import javax.management.Notification;
 import javax.management.NotificationListener;
-
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
@@ -37,7 +38,6 @@ import org.mockito.stubbing.Answer;
 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
 import org.opendaylight.controller.config.persist.api.ConfigSnapshotHolder;
 import org.opendaylight.controller.config.persist.api.Persister;
-import org.opendaylight.controller.config.spi.ModuleFactory;
 import org.opendaylight.controller.netconf.api.NetconfMessage;
 import org.opendaylight.controller.netconf.api.jmx.CommitJMXNotification;
 import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
@@ -63,10 +63,6 @@ import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 import org.xml.sax.SAXException;
 
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-import io.netty.channel.ChannelFuture;
-
 public class NetconfConfigPersisterITTest extends AbstractNetconfConfigTest {
 
     private static final InetSocketAddress tcpAddress = new InetSocketAddress("127.0.0.1", 12023);
@@ -76,8 +72,7 @@ public class NetconfConfigPersisterITTest extends AbstractNetconfConfigTest {
 
     @Before
     public void setUp() throws Exception {
-        super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext,NetconfITTest.getModuleFactoriesS().toArray(
-                new ModuleFactory[0])));
+        super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext,NetconfITTest.FACTORIES));
 
         NetconfMonitoringServiceImpl monitoringService = new NetconfMonitoringServiceImpl(getNetconfOperationProvider());
 
@@ -143,8 +138,8 @@ public class NetconfConfigPersisterITTest extends AbstractNetconfConfigTest {
         }
 
         notificationVerifier.assertNotificationCount(2);
-        notificationVerifier.assertNotificationContent(0, 0, 0, 9);
-        notificationVerifier.assertNotificationContent(1, 4, 3, 9);
+        notificationVerifier.assertNotificationContent(0, 0, 0, 8);
+        notificationVerifier.assertNotificationContent(1, 4, 3, 8);
 
         mockedAggregator.assertSnapshotCount(2);
         // Capabilities are stripped for persister
index 0969bd92a59a7cb6132a2b3b6cb5ad713af5077e..2f7bd20d615b074a945bf49e2c60c9559c3df7e7 100644 (file)
@@ -8,6 +8,7 @@
 
 package org.opendaylight.controller.netconf.it;
 
+import static java.util.Arrays.asList;
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyString;
 import static org.mockito.Mockito.doAnswer;
@@ -99,7 +100,7 @@ public class NetconfITSecureTest extends AbstractNetconfConfigTest {
     }
 
     protected List<ModuleFactory> getModuleFactories() {
-        return NetconfITTest.getModuleFactoriesS();
+        return asList(NetconfITTest.FACTORIES);
     }
 
     @Test
index 60a5207daa2e74b54cbc5a1a2b1ec9dd423a3f2b..8e69e6a345ffef868c2ed4e5bc454c440dc989a4 100644 (file)
@@ -16,6 +16,7 @@ import static org.mockito.Matchers.anyString;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 
+import com.google.common.base.Function;
 import com.google.common.base.Throwables;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
@@ -28,6 +29,7 @@ import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
+import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
 import java.util.concurrent.ExecutionException;
@@ -39,11 +41,14 @@ import org.junit.Before;
 import org.junit.Ignore;
 import org.junit.Test;
 import org.junit.matchers.JUnitMatchers;
+import org.opendaylight.controller.config.api.jmx.ObjectNameUtil;
 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
 import org.opendaylight.controller.config.spi.ModuleFactory;
 import org.opendaylight.controller.config.util.ConfigTransactionJMXClient;
 import org.opendaylight.controller.config.yang.test.impl.DepTestImplModuleFactory;
 import org.opendaylight.controller.config.yang.test.impl.IdentityTestModuleFactory;
+import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleFactory;
+import org.opendaylight.controller.config.yang.test.impl.MultipleDependenciesModuleMXBean;
 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleFactory;
 import org.opendaylight.controller.config.yang.test.impl.NetconfTestImplModuleMXBean;
 import org.opendaylight.controller.config.yang.test.impl.TestImplModuleFactory;
@@ -81,23 +86,27 @@ public class NetconfITTest extends AbstractNetconfConfigTest {
 
 
     private NetconfMessage getConfig, getConfigCandidate, editConfig, closeSession;
-    private DefaultCommitNotificationProducer commitNot;
+    private DefaultCommitNotificationProducer commitNotificationProducer;
     private NetconfServerDispatcher dispatch;
 
     private NetconfClientDispatcherImpl clientDispatcher;
 
+    static ModuleFactory[] FACTORIES = {new TestImplModuleFactory(), new DepTestImplModuleFactory(),
+            new NetconfTestImplModuleFactory(), new IdentityTestModuleFactory(),
+            new MultipleDependenciesModuleFactory()};
+
     @Before
     public void setUp() throws Exception {
-        super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext,getModuleFactories().toArray(
-                new ModuleFactory[0])));
+        initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext,
+                FACTORIES
+        ));
 
         loadMessages();
 
         NetconfOperationServiceFactoryListenerImpl factoriesListener = new NetconfOperationServiceFactoryListenerImpl();
         factoriesListener.onAddNetconfOperationServiceFactory(new NetconfOperationServiceFactoryImpl(getYangStore()));
 
-
-        commitNot = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
+        commitNotificationProducer = new DefaultCommitNotificationProducer(ManagementFactory.getPlatformMBeanServer());
 
         dispatch = createDispatcher(factoriesListener);
         ChannelFuture s = dispatch.createServer(tcpAddress);
@@ -107,7 +116,7 @@ public class NetconfITTest extends AbstractNetconfConfigTest {
     }
 
     private NetconfServerDispatcher createDispatcher(NetconfOperationServiceFactoryListenerImpl factoriesListener) {
-        return super.createDispatcher(factoriesListener, getNetconfMonitoringListenerService(), commitNot);
+        return super.createDispatcher(factoriesListener, getNetconfMonitoringListenerService(), commitNotificationProducer);
     }
 
     static NetconfMonitoringServiceImpl getNetconfMonitoringListenerService() {
@@ -120,7 +129,7 @@ public class NetconfITTest extends AbstractNetconfConfigTest {
 
     @After
     public void tearDown() throws Exception {
-        commitNot.close();
+        commitNotificationProducer.close();
         clientDispatcher.close();
     }
 
@@ -155,14 +164,6 @@ public class NetconfITTest extends AbstractNetconfConfigTest {
         return yangDependencies;
     }
 
-    protected List<ModuleFactory> getModuleFactories() {
-        return getModuleFactoriesS();
-    }
-
-    static List<ModuleFactory> getModuleFactoriesS() {
-        return Lists.newArrayList(new TestImplModuleFactory(), new DepTestImplModuleFactory(),
-                new NetconfTestImplModuleFactory(), new IdentityTestModuleFactory());
-    }
 
     @Test
     public void testNetconfClientDemonstration() throws Exception {
@@ -392,4 +393,66 @@ public class NetconfITTest extends AbstractNetconfConfigTest {
         doReturn(codec).when(ret).getIdentityCodec();
         return ret;
     }
+
+
+    @Test
+    public void testMultipleDependencies() throws Exception {
+        // push first xml, should add parent and d1,d2 dependencies
+        try (TestingNetconfClient netconfClient = createSession(tcpAddress, "1")) {
+            Document rpcReply = netconfClient.sendMessage(
+                    XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_multiple-deps1.xml"))
+                    .getDocument();
+            assertIsOK(rpcReply);
+            commit(netconfClient);
+        }
+        // verify that parent.getTestingDeps == d1,d2
+        MultipleDependenciesModuleMXBean parentProxy = configRegistryClient.newMXBeanProxy(
+                configRegistryClient.lookupConfigBean(MultipleDependenciesModuleFactory.NAME, "parent"),
+                MultipleDependenciesModuleMXBean.class);
+        {
+            List<ObjectName> testingDeps = parentProxy.getTestingDeps();
+            assertEquals(2, testingDeps.size());
+            Set<String> actualRefs = getServiceReferences(testingDeps);
+            assertEquals(Sets.newHashSet("ref_d1", "ref_d2"), actualRefs);
+        }
+
+        // push second xml, should add d3 to parent's dependencies
+        mergeD3(parentProxy);
+        // push second xml again, to test that d3 is not added again
+        mergeD3(parentProxy);
+    }
+
+    public void mergeD3(MultipleDependenciesModuleMXBean parentProxy) throws Exception {
+        try (TestingNetconfClient netconfClient = new TestingNetconfClient(
+                "test " + tcpAddress.toString(), clientDispatcher, getClientConfiguration(tcpAddress, 5000))) {
+
+            Document rpcReply = netconfClient.sendMessage(
+                    XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/editConfig_merge_multiple-deps2.xml"))
+                    .getDocument();
+            assertIsOK(rpcReply);
+            commit(netconfClient);
+        }
+        {
+            List<ObjectName> testingDeps = parentProxy.getTestingDeps();
+            assertEquals(3, testingDeps.size());
+            Set<String> actualRefs = getServiceReferences(testingDeps);
+            assertEquals(Sets.newHashSet("ref_d1", "ref_d2", "ref_d3"), actualRefs);
+        }
+    }
+
+    public Set<String> getServiceReferences(List<ObjectName> testingDeps) {
+        return new HashSet<>(Lists.transform(testingDeps, new Function<ObjectName, String>() {
+            @Override
+            public String apply(ObjectName input) {
+                return ObjectNameUtil.getReferenceName(input);
+            }
+        }));
+    }
+
+    public void commit(TestingNetconfClient netconfClient) throws Exception {
+        Document rpcReply;
+        rpcReply = netconfClient.sendMessage(XmlFileLoader.xmlFileToNetconfMessage("netconfMessages/commit.xml"))
+                .getDocument();
+        assertIsOK(rpcReply);
+    }
 }
index 3b263f7e75cc826b55b893a76a1f5fbf4b051c34..05e32577fe771f1e8a47a30bdd3ecbceb43a189d 100644 (file)
@@ -13,6 +13,10 @@ import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
 import static org.opendaylight.controller.netconf.util.test.XmlUnitUtil.assertContainsElementWithText;
 
+import com.google.common.base.Charsets;
+import com.google.common.base.Optional;
+import com.google.common.collect.Sets;
+import io.netty.channel.ChannelFuture;
 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStream;
@@ -22,14 +26,11 @@ import java.net.Socket;
 import java.util.Collection;
 import java.util.List;
 import java.util.Set;
-
 import junit.framework.Assert;
-
 import org.junit.Before;
 import org.junit.Test;
 import org.mockito.Mock;
 import org.opendaylight.controller.config.manager.impl.factoriesresolver.HardcodedModuleFactoriesResolver;
-import org.opendaylight.controller.config.spi.ModuleFactory;
 import org.opendaylight.controller.netconf.api.NetconfMessage;
 import org.opendaylight.controller.netconf.api.monitoring.NetconfManagementSession;
 import org.opendaylight.controller.netconf.client.NetconfClientDispatcherImpl;
@@ -53,11 +54,6 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.w3c.dom.Document;
 
-import com.google.common.base.Charsets;
-import com.google.common.base.Optional;
-import com.google.common.collect.Sets;
-import io.netty.channel.ChannelFuture;
-
 public class NetconfMonitoringITTest extends AbstractNetconfConfigTest {
 
     private static final Logger logger =  LoggerFactory.getLogger(NetconfITTest.class);
@@ -74,8 +70,7 @@ public class NetconfMonitoringITTest extends AbstractNetconfConfigTest {
 
     @Before
     public void setUp() throws Exception {
-        super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, NetconfITTest.getModuleFactoriesS().toArray(
-                new ModuleFactory[0])));
+        super.initConfigTransactionManagerImpl(new HardcodedModuleFactoriesResolver(mockedContext, NetconfITTest.FACTORIES));
 
         monitoringService = new NetconfMonitoringServiceImpl(getNetconfOperationProvider());
 
index 07ca2f134dda4f5910bc4acf11dfd0ba650e4199..4d232a619a49affd154c46d9fd6aa92ec08592b6 100644 (file)
@@ -28,7 +28,7 @@ public final class SSLUtil {
     }
 
     public static SSLContext initializeSecureContext(final String pass, final InputStream ksKeysFile, final InputStream ksTrustFile,
-            final String algorithm) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
+                                                     final String algorithm) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
             UnrecoverableKeyException, KeyManagementException {
 
         Preconditions.checkNotNull(ksTrustFile, "ksTrustFile cannot be null");
similarity index 83%
rename from opendaylight/netconf/netconf-it/src/test/resources/logback.xml
rename to opendaylight/netconf/netconf-it/src/test/resources/logback-test.xml
index fa467a1080f1c605008f5da36cfab7e1d277a7f1..c5037d34ed4ac01fcea4b5dd264b8f715ad2cc9c 100644 (file)
@@ -6,7 +6,7 @@
         </encoder>
     </appender>
 
-  <logger name="org.opendaylight.controller.netconf" level="DEBUG"/>
+  <logger name="org.opendaylight.controller.netconf" level="TRACE"/>
 
   <root level="error">
     <appender-ref ref="STDOUT" />
index f0e1b3f51fd1abdb445bc33f221f1e90aff1a6dc..de3f732b25763fa19d6b481a64bfbcf4d8bcf87c 100644 (file)
@@ -11,6 +11,7 @@ package org.opendaylight.controller.netconf.nettyutil;
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import io.netty.channel.Channel;
+import io.netty.channel.ChannelFuture;
 import io.netty.channel.ChannelHandler;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.channel.ChannelInboundHandlerAdapter;
@@ -60,6 +61,7 @@ extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
     }
 
     private State state = State.IDLE;
+    private final Promise<S> promise;
     private final Timer timer;
     private final long connectionTimeoutMillis;
 
@@ -68,6 +70,7 @@ extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
             L sessionListener, long connectionTimeoutMillis) {
         super(promise, channel);
         this.sessionPreferences = sessionPreferences;
+        this.promise = promise;
         this.timer = timer;
         this.sessionListener = sessionListener;
         this.connectionTimeoutMillis = connectionTimeoutMillis;
@@ -102,32 +105,52 @@ extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
 
     private void start() {
         final NetconfMessage helloMessage = this.sessionPreferences.getHelloMessage();
-        logger.debug("Session negotiation started with hello message {}", XmlUtil.toString(helloMessage.getDocument()));
+        logger.debug("Session negotiation started with hello message {} on channel {}", XmlUtil.toString(helloMessage.getDocument()), channel);
 
         channel.pipeline().addLast(NAME_OF_EXCEPTION_HANDLER, new ExceptionHandlingInboundChannelHandler());
 
+        // FIXME, make sessionPreferences return HelloMessage, move NetconfHelloMessage to API
+        sendMessage((NetconfHelloMessage)helloMessage);
+
+        replaceHelloMessageOutboundHandler();
+        changeState(State.OPEN_WAIT);
+
         timeout = this.timer.newTimeout(new TimerTask() {
             @Override
             public void run(final Timeout timeout) {
                 synchronized (this) {
                     if (state != State.ESTABLISHED) {
+
                         logger.debug("Connection timeout after {}, session is in state {}", timeout, state);
-                        final IllegalStateException cause = new IllegalStateException(
-                                "Session was not established after " + timeout);
-                        negotiationFailed(cause);
-                        changeState(State.FAILED);
+
+                        // Do not fail negotiation if promise is done or canceled
+                        // It would result in setting result of the promise second time and that throws exception
+                        if (isPromiseFinished() == false) {
+                            negotiationFailed(new IllegalStateException("Session was not established after " + timeout));
+                            changeState(State.FAILED);
+
+                            channel.closeFuture().addListener(new GenericFutureListener<ChannelFuture>() {
+                                @Override
+                                public void operationComplete(ChannelFuture future) throws Exception {
+                                    if(future.isSuccess()) {
+                                        logger.debug("Channel {} closed: success", future.channel());
+                                    } else {
+                                        logger.warn("Channel {} closed: fail", future.channel());
+                                    }
+                                }
+                            });
+                        }
                     } else if(channel.isOpen()) {
                         channel.pipeline().remove(NAME_OF_EXCEPTION_HANDLER);
                     }
                 }
             }
-        }, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
 
-        // FIXME, make sessionPreferences return HelloMessage, move NetconfHelloMessage to API
-        sendMessage((NetconfHelloMessage)helloMessage);
+            private boolean isPromiseFinished() {
+                return promise.isDone() || promise.isCancelled();
+            }
 
-        replaceHelloMessageOutboundHandler();
-        changeState(State.OPEN_WAIT);
+        }, connectionTimeoutMillis, TimeUnit.MILLISECONDS);
     }
 
     private void cancelTimeout() {
@@ -200,9 +223,9 @@ extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
     protected abstract S getSession(L sessionListener, Channel channel, NetconfHelloMessage message) throws NetconfDocumentedException;
 
     private synchronized void changeState(final State newState) {
-        logger.debug("Changing state from : {} to : {}", state, newState);
-        Preconditions.checkState(isStateChangePermitted(state, newState), "Cannot change state from %s to %s", state,
-                newState);
+        logger.debug("Changing state from : {} to : {} for channel: {}", state, newState, channel);
+        Preconditions.checkState(isStateChangePermitted(state, newState), "Cannot change state from %s to %s for chanel %s", state,
+                newState, channel);
         this.state = newState;
     }
 
@@ -236,7 +259,7 @@ extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
     private final class ExceptionHandlingInboundChannelHandler extends ChannelInboundHandlerAdapter {
         @Override
         public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
-            logger.warn("An exception occurred during negotiation on channel {}", channel.localAddress(), cause);
+            logger.warn("An exception occurred during negotiation with {}", channel.remoteAddress(), cause);
             cancelTimeout();
             negotiationFailed(cause);
             changeState(State.FAILED);
index f260bcbcefbf0fff5baa41bda46b8b6c4efc617a..a87a08ded72ea97db3396c24697b780be501911d 100644 (file)
@@ -9,56 +9,15 @@
 package org.opendaylight.controller.netconf.nettyutil.handler;
 
 import io.netty.buffer.ByteBuf;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.handler.codec.ByteToMessageDecoder;
-
-import java.util.List;
-
+import io.netty.buffer.Unpooled;
+import io.netty.handler.codec.DelimiterBasedFrameDecoder;
 import org.opendaylight.controller.netconf.util.messages.NetconfMessageConstants;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Charsets;
+public class NetconfEOMAggregator extends DelimiterBasedFrameDecoder {
 
-public class NetconfEOMAggregator extends ByteToMessageDecoder {
-    private final static Logger logger = LoggerFactory.getLogger(NetconfEOMAggregator.class);
+    public static final ByteBuf DELIMITER = Unpooled.wrappedBuffer(NetconfMessageConstants.END_OF_MESSAGE);
 
-    @Override
-    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
-        int index = indexOfSequence(in, NetconfMessageConstants.END_OF_MESSAGE);
-        if (index == -1) {
-            logger.debug("Message is not complete, read again.");
-            if (logger.isTraceEnabled()) {
-                String str = in.toString(Charsets.UTF_8);
-                logger.trace("Message read so far: {}", str);
-            }
-            ctx.read();
-        } else {
-            ByteBuf msg = in.readBytes(index);
-            in.readBytes(NetconfMessageConstants.END_OF_MESSAGE.length);
-            in.discardReadBytes();
-            logger.debug("Message is complete.");
-            out.add(msg);
-        }
+    public NetconfEOMAggregator() {
+        super(Integer.MAX_VALUE, DELIMITER);
     }
-
-    private int indexOfSequence(ByteBuf in, byte[] sequence) {
-        int index = -1;
-        for (int i = 0; i < in.readableBytes() - sequence.length + 1; i++) {
-            if (in.getByte(i) == sequence[0]) {
-                index = i;
-                for (int j = 1; j < sequence.length; j++) {
-                    if (in.getByte(i + j) != sequence[j]) {
-                        index = -1;
-                        break;
-                    }
-                }
-                if (index != -1) {
-                    return index;
-                }
-            }
-        }
-        return index;
-    }
-
 }
index fae2000bb53c7b0873f90cc677464ef04be6666a..d810a870ff29f68b59b19788bf3064e0218cb148 100644 (file)
@@ -12,6 +12,7 @@ import io.netty.buffer.ByteBufOutputStream;
 import io.netty.channel.ChannelHandlerContext;
 import io.netty.handler.codec.MessageToByteEncoder;
 
+import java.io.BufferedWriter;
 import java.io.IOException;
 import java.io.OutputStream;
 import java.io.OutputStreamWriter;
@@ -61,7 +62,8 @@ public class NetconfMessageToXMLEncoder extends MessageToByteEncoder<NetconfMess
             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
             transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
 
-            StreamResult result = new StreamResult(new OutputStreamWriter(os));
+            // Wrap OutputStreamWriter with BufferedWriter as suggested in javadoc for OutputStreamWriter
+            StreamResult result = new StreamResult(new BufferedWriter(new OutputStreamWriter(os)));
             DOMSource source = new DOMSource(msg.getDocument());
             transformer.transform(source, result);
         }
diff --git a/opendaylight/netconf/netconf-util/src/test/resources/netconfMessages/editConfig_merge_multiple-deps1.xml b/opendaylight/netconf/netconf-util/src/test/resources/netconfMessages/editConfig_merge_multiple-deps1.xml
new file mode 100644 (file)
index 0000000..0a02114
--- /dev/null
@@ -0,0 +1,59 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<rpc message-id="6"
+     xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
+  <edit-config xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
+    <target>
+      <candidate/>
+    </target>
+    <default-operation>merge</default-operation>
+    <test-option>set</test-option>
+    <config>
+      <modules xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
+        <module>
+          <name>d1</name>
+          <type xmlns:th-java="urn:opendaylight:params:xml:ns:yang:controller:test:impl">th-java:multiple-dependencies</type>
+        </module>
+        <module>
+          <name>d2</name>
+          <type xmlns:th-java="urn:opendaylight:params:xml:ns:yang:controller:test:impl">th-java:multiple-dependencies</type>
+        </module>
+        <module>
+          <name>parent</name>
+          <type xmlns:th-java="urn:opendaylight:params:xml:ns:yang:controller:test:impl">th-java:multiple-dependencies</type>
+
+          <multiple-dependencies xmlns="urn:opendaylight:params:xml:ns:yang:controller:test:impl">
+            <testing-deps>
+              <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:test">prefix:testing</type>
+              <name>ref_d1</name>
+            </testing-deps>
+            <testing-deps>
+              <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:test">prefix:testing</type>
+              <name>ref_d2</name>
+            </testing-deps>
+          </multiple-dependencies>
+
+        </module>
+
+      </modules>
+
+      <services xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
+        <service>
+          <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:test">prefix:testing</type>
+          <instance>
+            <name>ref_d1</name>
+            <provider>/modules/module[type='multiple-dependencies'][name='d1']
+            </provider>
+          </instance>
+        </service>
+        <service>
+          <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:test">prefix:testing</type>
+          <instance>
+            <name>ref_d2</name>
+            <provider>/modules/module[type='multiple-dependencies'][name='d2']
+            </provider>
+          </instance>
+        </service>
+      </services>
+    </config>
+  </edit-config>
+</rpc>
diff --git a/opendaylight/netconf/netconf-util/src/test/resources/netconfMessages/editConfig_merge_multiple-deps2.xml b/opendaylight/netconf/netconf-util/src/test/resources/netconfMessages/editConfig_merge_multiple-deps2.xml
new file mode 100644 (file)
index 0000000..d331976
--- /dev/null
@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<rpc message-id="6"
+     xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
+  <edit-config xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
+    <target>
+      <candidate/>
+    </target>
+    <default-operation>merge</default-operation>
+    <test-option>set</test-option>
+    <config>
+      <modules xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
+        <module>
+          <name>d3</name>
+          <type xmlns:th-java="urn:opendaylight:params:xml:ns:yang:controller:test:impl">th-java:multiple-dependencies</type>
+        </module>
+        <module>
+          <name>parent</name>
+          <type xmlns:th-java="urn:opendaylight:params:xml:ns:yang:controller:test:impl">th-java:multiple-dependencies</type>
+          <multiple-dependencies xmlns="urn:opendaylight:params:xml:ns:yang:controller:test:impl">
+            <testing-deps>
+              <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:test">prefix:testing</type>
+              <name>ref_d3</name>
+            </testing-deps>
+          </multiple-dependencies>
+        </module>
+      </modules>
+      <services xmlns="urn:opendaylight:params:xml:ns:yang:controller:config">
+        <service>
+          <type xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:test">prefix:testing</type>
+          <instance>
+            <name>ref_d3</name>
+            <provider>/modules/module[type='multiple-dependencies'][name='d3']
+            </provider>
+          </instance>
+        </service>
+      </services>
+    </config>
+  </edit-config>
+</rpc>
index d26fcf987e5469388b5c01bac3a391b805a46536..937949a17e5827bbe74d22eb5071904b3a71906d 100644 (file)
@@ -19,6 +19,7 @@
 
   <modules>
     <module>netconf-api</module>
+    <module>netconf-cli</module>
     <module>netconf-impl</module>
     <module>config-netconf-connector</module>
     <module>netconf-util</module>
diff --git a/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronObject.java b/opendaylight/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/INeutronObject.java
new file mode 100644 (file)
index 0000000..bebac37
--- /dev/null
@@ -0,0 +1,19 @@
+/*
+ * 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
+ *
+ *  Authors : Dave Tucker
+ */
+
+package org.opendaylight.controller.networkconfig.neutron;
+
+/**
+ * This class contains behaviour common to Neutron configuration objects
+ */
+public interface INeutronObject {
+    public String getID();
+    public void setID(String id);
+}
index 5b35dc2b34ff73519e4350fa7070ec06cf60801d..a3c38a9265dc50c814a83c776a0c0c7e599f1dba 100644 (file)
@@ -23,7 +23,7 @@ import org.opendaylight.controller.configuration.ConfigurationObject;
 @XmlRootElement(name = "network")
 @XmlAccessorType(XmlAccessType.NONE)
 
-public class NeutronNetwork extends ConfigurationObject implements Serializable {
+public class NeutronNetwork extends ConfigurationObject implements Serializable, INeutronObject {
     // See OpenStack Network API v2.0 Reference for description of
     // annotated attributes
 
@@ -93,6 +93,8 @@ public class NeutronNetwork extends ConfigurationObject implements Serializable
 
     public String getID() { return networkUUID; }
 
+    public void setID(String id) { this.networkUUID = id; }
+
     public String getNetworkUUID() {
         return networkUUID;
     }
index 680a07453b94b3f56072804b2981006574837f5a..b32b01cb3f3015930510d22fd1a39836a25a0cbb 100644 (file)
@@ -25,7 +25,7 @@ import org.opendaylight.controller.configuration.ConfigurationObject;
 @XmlRootElement
 @XmlAccessorType(XmlAccessType.NONE)
 
-public class NeutronPort extends ConfigurationObject implements Serializable {
+public class NeutronPort extends ConfigurationObject implements Serializable, INeutronObject {
     private static final long serialVersionUID = 1L;
 
     // See OpenStack Network API v2.0 Reference for description of
@@ -76,6 +76,8 @@ public class NeutronPort extends ConfigurationObject implements Serializable {
 
     public String getID() { return portUUID; }
 
+    public void setID(String id) { this.portUUID = id; }
+
     public String getPortUUID() {
         return portUUID;
     }
index fa35f71fd6ae425aac90f7d31524198413ade2f2..2c10cca0c0e4d0819f91d2f7d5543897d216cd65 100644 (file)
@@ -23,7 +23,7 @@ import org.opendaylight.controller.configuration.ConfigurationObject;
 @XmlRootElement
 @XmlAccessorType(XmlAccessType.NONE)
 
-public class NeutronRouter extends ConfigurationObject implements Serializable {
+public class NeutronRouter extends ConfigurationObject implements Serializable, INeutronObject {
     private static final long serialVersionUID = 1L;
 
     // See OpenStack Network API v2.0 Reference for description of
@@ -57,6 +57,8 @@ public class NeutronRouter extends ConfigurationObject implements Serializable {
 
     public String getID() { return routerUUID; }
 
+    public void setID(String id) { this.routerUUID = id; }
+
     public String getRouterUUID() {
         return routerUUID;
     }
index ae84a72bbac84ddda56c102972c894e21873a603..840029006be5b16a4d394bae0d6daa0b5efd65a5 100644 (file)
@@ -25,7 +25,7 @@ import org.opendaylight.controller.configuration.ConfigurationObject;
 @XmlRootElement
 @XmlAccessorType(XmlAccessType.NONE)
 
-public class NeutronSubnet extends ConfigurationObject implements Serializable {
+public class NeutronSubnet extends ConfigurationObject implements Serializable, INeutronObject {
     private static final long serialVersionUID = 1L;
 
     // See OpenStack Network API v2.0 Reference for description of
@@ -83,6 +83,8 @@ public class NeutronSubnet extends ConfigurationObject implements Serializable {
 
     public String getID() { return subnetUUID; }
 
+    public void setID(String id) { this.subnetUUID = id; }
+
     public String getSubnetUUID() {
         return subnetUUID;
     }
index 09c075735a6c3b7090de71554c6fdefc73ef34ec..a2d2dac112e932d7578698bd1eccf54f54942f50 100644 (file)
@@ -12,7 +12,6 @@
   <version>0.4.2-SNAPSHOT</version>
   <packaging>bundle</packaging>
   <dependencies>
-
     <dependency>
       <groupId>com.fasterxml.jackson.core</groupId>
       <artifactId>jackson-databind</artifactId>
       <groupId>org.opendaylight.controller</groupId>
       <artifactId>usermanager</artifactId>
     </dependency>
+
+    <dependency>
+      <groupId>ch.qos.logback</groupId>
+      <artifactId>logback-classic</artifactId>
+      <scope>test</scope>
+    </dependency>
+
   </dependencies>
 
   <build>
@@ -78,6 +84,7 @@
             <Export-Package>org.opendaylight.controller.northbound.commons.exception,
               org.opendaylight.controller.northbound.commons.types,
               org.opendaylight.controller.northbound.commons.utils,
+              org.opendaylight.controller.northbound.commons.query,
               org.opendaylight.controller.northbound.commons</Export-Package>
             <Import-Package>javax.ws.rs,
               javax.ws.rs.ext,
           <manifestLocation>${project.basedir}/META-INF</manifestLocation>
         </configuration>
       </plugin>
+
+      <plugin>
+        <groupId>org.codehaus.mojo</groupId>
+        <artifactId>build-helper-maven-plugin</artifactId>
+        <executions>
+          <execution>
+            <id>add-source</id>
+            <goals>
+              <goal>add-source</goal>
+            </goals>
+            <phase>generate-sources</phase>
+            <configuration>
+              <sources>
+                <source>${project.build.directory}/generated-sources/javacc</source>
+              </sources>
+            </configuration>
+          </execution>
+        </executions>
+      </plugin>
+
+      <plugin>
+        <groupId>org.codehaus.mojo</groupId>
+        <artifactId>javacc-maven-plugin</artifactId>
+        <version>2.6</version>
+        <executions>
+          <execution>
+            <id>javacc</id>
+            <goals>
+              <goal>javacc</goal>
+            </goals>
+          </execution>
+        </executions>
+      </plugin>
+
     </plugins>
   </build>
   <scm>
index 4393b79f6446463074b869918651c273ff6cfa2a..cf48729113ce7b1304f2a0f7b3f2e4a7c0e05dfc 100644 (file)
@@ -20,6 +20,8 @@ import javax.xml.bind.JAXBException;
 import javax.xml.bind.annotation.XmlRootElement;
 
 import org.opendaylight.controller.northbound.bundlescanner.IBundleScanService;
+import org.opendaylight.controller.northbound.commons.exception.GenericExceptionMapper;
+import org.opendaylight.controller.northbound.commons.query.QueryContextProvider;
 import org.osgi.framework.Bundle;
 import org.osgi.framework.BundleContext;
 import org.osgi.framework.BundleReference;
@@ -58,6 +60,8 @@ public class NorthboundApplication extends Application {
         } );
         _singletons.add(getJsonProvider());
         _singletons.add(new JacksonJsonProcessingExceptionMapper());
+        _singletons.add(new QueryContextProvider());
+        _singletons.add(new GenericExceptionMapper());
     }
 
     ////////////////////////////////////////////////////////////////
diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/GenericExceptionMapper.java b/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/exception/GenericExceptionMapper.java
new file mode 100644 (file)
index 0000000..d2bbfea
--- /dev/null
@@ -0,0 +1,24 @@
+package org.opendaylight.controller.northbound.commons.exception;
+
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.ext.ExceptionMapper;
+import javax.ws.rs.ext.Provider;
+
+@Provider
+public class GenericExceptionMapper implements ExceptionMapper<Exception> {
+
+    @Override
+    public Response toResponse(Exception exception) {
+        //check if WebApplicationException and reuse status code
+        if (exception instanceof WebApplicationException) {
+            WebApplicationException ex = (WebApplicationException) exception;
+            return Response.status(ex.getResponse().getStatus()).
+                    entity(ex.getResponse().getEntity()).build();
+        }
+        // throw 500 for all other errors
+        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).
+                entity(exception.getMessage()).build();
+    }
+
+}
diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Accessor.java b/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Accessor.java
new file mode 100644 (file)
index 0000000..2d910ed
--- /dev/null
@@ -0,0 +1,55 @@
+package org.opendaylight.controller.northbound.commons.query;
+
+import java.lang.annotation.Annotation;
+import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.lang.reflect.Type;
+
+/*package*/ class Accessor {
+    protected final AccessibleObject _accessorObj;
+
+    public Accessor(AccessibleObject accessor) {
+        _accessorObj = accessor;
+        _accessorObj.setAccessible(true);
+    }
+
+    public AccessibleObject getAccessibleObject() {
+        return _accessorObj;
+    }
+
+    public Annotation[] getAnnotations() {
+        return _accessorObj.getAnnotations();
+    }
+
+    public Object getValue(Object parent) throws QueryException {
+        try {
+            if (_accessorObj instanceof Field) {
+                return ((Field)_accessorObj).get(parent);
+            } else {
+                // assume method
+                return ((Method)_accessorObj).invoke(parent);
+            }
+        } catch (Exception e) {
+            throw new QueryException("Failure in retrieving value", e);
+        }
+    }
+    public Type getGenericType() {
+        if (_accessorObj instanceof Field) {
+            return ((Field)_accessorObj).getGenericType();
+        } else {
+            // assume method
+            return ((Method)_accessorObj).getGenericReturnType();
+        }
+    }
+    public Class<?> getType() {
+
+        if (_accessorObj instanceof Field) {
+            return ((Field)_accessorObj).getType();
+        } else {
+            // assume method
+            return ((Method)_accessorObj).getReturnType();
+        }
+    }
+
+}
diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/CompareExpression.java b/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/CompareExpression.java
new file mode 100644 (file)
index 0000000..6b972e6
--- /dev/null
@@ -0,0 +1,56 @@
+/**
+ * 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.northbound.commons.query;
+
+/*package*/ class CompareExpression implements Expression {
+
+    public static enum OP { RE, EQ, NE, GT, GE, LT, LE };
+
+    private final OP _operation;
+    private final String _selector;
+    private final String _arg;
+
+    public CompareExpression(OP op, String selector, String arg) {
+        _operation = op;
+        _selector = selector;
+        _arg = unQuote(arg);
+    }
+
+
+    public OP getOperator() {
+        return _operation;
+    }
+
+    public String getSelector() {
+        return _selector;
+    }
+
+    public String getArgument() {
+        return _arg;
+    }
+
+    @Override
+    public boolean accept(Visitor visitor) throws QueryException {
+        return visitor.visit(this);
+    }
+
+    @Override
+    public String toString() {
+        return "[" + _selector + " " + _operation + " " + _arg + "]";
+    }
+
+    private static String unQuote(String s) {
+        if (s.startsWith("\"") && s.endsWith("\"")) {
+            s = s.substring(1, s.length()-1);
+        } else if (s.startsWith("\'") && s.endsWith("\'")) {
+            s = s.substring(1, s.length()-1);
+        }
+        return s;
+    }
+
+}
@@ -1,12 +1,12 @@
-/*
+/**
  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
  *
  * This program and the accompanying materials are made available under the
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
-package org.opendaylight.controller.sal.binding.impl.connect.dom;
+package org.opendaylight.controller.northbound.commons.query;
 
-public class Constants {
-    public static final Class<byte[]> BYTES_CLASS = byte[].class;
+/*package*/ interface Expression {
+    boolean accept(Visitor visitor) throws QueryException;
 }
diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/ExpressionBuilder.java b/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/ExpressionBuilder.java
new file mode 100644 (file)
index 0000000..f1b2999
--- /dev/null
@@ -0,0 +1,41 @@
+/**
+ * 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.northbound.commons.query;
+
+import java.util.Stack;
+
+/*package*/ class ExpressionBuilder {
+    private final Stack<Expression> _stack = new Stack<Expression>();
+    private LogicalExpression.OP _lastOp = null;
+
+    public ExpressionBuilder() {}
+
+    public ExpressionBuilder withAnd() {
+        _lastOp = LogicalExpression.OP.AND;
+        return this;
+    }
+
+    public ExpressionBuilder withOr() {
+        _lastOp = LogicalExpression.OP.OR;
+        return this;
+    }
+
+    public ExpressionBuilder withTerm(Expression exp) {
+        if (_lastOp != null) {
+            exp = new LogicalExpression(_lastOp, _stack.pop(), exp);
+            _lastOp = null;
+        }
+        _stack.push(exp);
+        return this;
+    }
+
+    public Expression build() {
+        return _stack.pop();
+    }
+
+}
diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/IteratableTypeInfo.java b/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/IteratableTypeInfo.java
new file mode 100644 (file)
index 0000000..3977837
--- /dev/null
@@ -0,0 +1,67 @@
+package org.opendaylight.controller.northbound.commons.query;
+
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ */
+/*package*/ class IteratableTypeInfo extends TypeInfo {
+
+    public IteratableTypeInfo(String name, Accessor accessor) {
+        super(name, accessor.getType(), accessor);
+    }
+
+    @Override
+    public Object retrieve(Object target, String[] query, int index) throws QueryException {
+        if (LOGGER.isDebugEnabled()) {
+            LOGGER.debug("retrieve collection: {}/{} type:{}", index, query.length,
+                    target.getClass());
+        }
+        explore();
+        Collection<?> c = (Collection<?>) target;
+        Iterator<?> it = c.iterator();
+        List<Object> objects = new ArrayList<Object>();
+        while (it.hasNext()) {
+            Object item = it.next();
+            for (TypeInfo child : _types.values()) {
+                Object val = child.retrieve(item, query, index);
+                if (val != null) objects.add(val);
+            }
+        }
+        return objects;
+
+    }
+
+    @Override
+    public synchronized void explore() {
+        if (_explored) return;
+        if (LOGGER.isDebugEnabled()) {
+            LOGGER.debug("exploring iteratable type: {} gtype: {}", _class,
+                    _accessor.getGenericType());
+        }
+        Type t = _accessor.getGenericType();
+        if (t instanceof ParameterizedType) {
+            Type[] pt = ((ParameterizedType) t).getActualTypeArguments();
+            // First type is a child, ignore rest
+            if (pt.length > 0) {
+                _types.put(_name, new TypeInfo(_name, (Class)pt[0], null));
+            }
+        }
+        _explored = true;
+    }
+
+    @Override
+    public TypeInfo getCollectionChild(Class<?> childType) {
+        explore();
+        for (TypeInfo ti : _types.values()) {
+            if (ti.getType().equals(childType)) {
+                return ti;
+            }
+        }
+        return null;
+    }
+}
diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/LogicalExpression.java b/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/LogicalExpression.java
new file mode 100644 (file)
index 0000000..4e99820
--- /dev/null
@@ -0,0 +1,50 @@
+/**
+ * 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.northbound.commons.query;
+
+/*package*/ class LogicalExpression implements Expression {
+
+    public static enum OP { AND, OR }
+
+    private final OP _op;
+    private final Expression _arg1;
+    private final Expression _arg2;
+
+    public LogicalExpression(OP op, Expression first, Expression second) {
+        _op = op;
+        _arg1 = first;
+        _arg2 = second;
+    }
+
+    public OP getOperator() {
+        return _op;
+    }
+
+    public Expression getFirst() {
+        return _arg1;
+    }
+
+    public Expression getSecond() {
+        return _arg2;
+    }
+
+    @Override
+    public boolean accept(Visitor visitor) throws QueryException {
+        return visitor.visit(this);
+    }
+
+    @Override
+    public String toString() {
+        StringBuilder sb = new StringBuilder();
+        sb.append(_arg1.toString())
+        .append(_op.toString())
+        .append(_arg2.toString());
+        return sb.toString();
+    }
+
+}
diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Query.java b/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Query.java
new file mode 100644 (file)
index 0000000..15dcaeb
--- /dev/null
@@ -0,0 +1,52 @@
+/**
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.northbound.commons.query;
+
+import java.util.Collection;
+import java.util.List;
+
+
+/**
+ * Represents a parsed query used in filtering of collections.
+ */
+public interface Query<T> {
+
+    /**
+     * Find items in the given collection and return them as a new list. The
+     * original collection is not changed.
+     *
+     * @param collection to search in.
+     * @return list of items which match the query.
+     * @throws QueryException
+     */
+    public List<T> find(Collection<T> collection) throws QueryException;
+
+    /**
+     * Apply the query on the given collection. Note that this method will modify
+     * the given object by removing any items which don't match the query criteria.
+     * If the collection is 'singleton' or unmodifiable, invocation will result in
+     * an exception.
+     *
+     * @param collection
+     * @return the number matched items
+     * @throws QueryException
+     */
+    public int filter(Collection<T> collection) throws QueryException;
+
+    /**
+     * Search the given root for a child collection and them apply the query on.
+     * Note that this method will modify the given object by removing any items
+     * which don't match the query criteria.
+     *
+     * @param root - top level object to search in
+     * @param childType - the child type which represents the collection.
+     * @return the number of matched items
+     * @throws QueryException
+     */
+    public int filter(T root, Class<?> childType) throws QueryException;
+}
diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContext.java b/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContext.java
new file mode 100644 (file)
index 0000000..59a78ac
--- /dev/null
@@ -0,0 +1,25 @@
+/**
+ * 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.northbound.commons.query;
+
+/**
+ * Query context
+ */
+public interface QueryContext {
+
+    /**
+     * Create a Query
+     * @param queryString - query string to parse
+     * @param clazz - The class which represents the top level jaxb object
+     * @return a query object
+     * @throws QueryException if the query cannot be parsed.
+     */
+    <T> Query<T> createQuery(String queryString, Class<T> clazz)
+            throws QueryException;
+
+}
diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContextImpl.java b/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContextImpl.java
new file mode 100644 (file)
index 0000000..13d70b1
--- /dev/null
@@ -0,0 +1,33 @@
+/**
+ * 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.northbound.commons.query;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/*package*/ class QueryContextImpl implements QueryContext {
+
+    private static final Logger LOGGER = LoggerFactory.getLogger(QueryContext.class);
+
+    @Override
+    public <T> Query<T> createQuery(String queryString, Class<T> type) throws QueryException {
+        if (queryString == null || queryString.trim().length() == 0) return null;
+        try {
+            if (LOGGER.isDebugEnabled()) LOGGER.debug("Processing query: {}", queryString);
+            // FiqlParser is a parser generated by javacc
+            Expression expression = FiqlParser.parse(queryString);
+            if (LOGGER.isDebugEnabled()) LOGGER.debug("Query expression: {}", expression);
+            // create Query and return;
+            return new QueryImpl<T>(type, expression);
+        } catch (Exception ex) {
+            if (LOGGER.isDebugEnabled()) LOGGER.error("Query processing failed = {}",
+                    queryString, ex);
+            throw new QueryException("Unable to parse query.", ex);
+        }
+    }
+}
\ No newline at end of file
diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContextProvider.java b/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryContextProvider.java
new file mode 100644 (file)
index 0000000..65a232c
--- /dev/null
@@ -0,0 +1,27 @@
+/**
+ * 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.northbound.commons.query;
+
+import javax.ws.rs.ext.ContextResolver;
+import javax.ws.rs.ext.Provider;
+
+/**
+ * A provider for getting hold of the QueryContext.
+ */
+@Provider
+public class QueryContextProvider implements ContextResolver<QueryContext> {
+
+    // Singleton Query Context instance
+    private static final QueryContext queryContext = new QueryContextImpl();
+
+    @Override
+    public QueryContext getContext(Class<?> type) {
+        return queryContext;
+    }
+
+}
diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryException.java b/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryException.java
new file mode 100644 (file)
index 0000000..9ff78ed
--- /dev/null
@@ -0,0 +1,30 @@
+/**
+ * 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.northbound.commons.query;
+
+import javax.ws.rs.WebApplicationException;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+
+/**
+ * Signals that an error happened during the parsing or processing of a query.
+ */
+public class QueryException extends WebApplicationException {
+
+    private static final long serialVersionUID = 1L;
+
+    public QueryException(String msg) {
+        super(Response.status(Response.Status.BAD_REQUEST)
+                .entity(msg).type(MediaType.TEXT_PLAIN).build());
+    }
+
+    public QueryException(String msg, Throwable cause) {
+        super(cause, Response.status(Response.Status.BAD_REQUEST)
+                .entity(msg).type(MediaType.TEXT_PLAIN).build());
+    }
+}
diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryImpl.java b/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/QueryImpl.java
new file mode 100644 (file)
index 0000000..a520f98
--- /dev/null
@@ -0,0 +1,237 @@
+/**
+ * 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.northbound.commons.query;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.List;
+import java.util.regex.Pattern;
+
+import org.opendaylight.controller.northbound.commons.query.CompareExpression.OP;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ *
+ */
+/*package*/ class QueryImpl<T> implements Query<T> {
+    public static final Logger LOGGER = LoggerFactory.getLogger(QueryImpl.class);
+    private static final boolean ALLOW_OBJECT_STRING_COMPARE = true;
+
+    private final Expression expression;
+    private final TypeInfo rootType ;
+    /**
+     * Set the expression and cache
+     * @param type
+     * @param expression
+     */
+    public QueryImpl(Class<T> type, Expression expression) {
+        this.expression = expression;
+        this.rootType = TypeInfo.createRoot(null, type);
+    }
+
+    @Override
+    public List<T> find(Collection<T> collection) throws QueryException {
+        // new arraylist for result
+        List<T> result = new ArrayList<T>();
+        for (T item : collection) {
+            if (match(item, rootType)) {
+                result.add(item);
+            }
+        }
+        return result;
+    }
+
+    @Override
+    public int filter(Collection<T> collection) throws QueryException {
+        // find items
+        List<T> matched = new ArrayList<T>();
+        for (T item : collection) {
+            if (match(item, rootType)) {
+                matched.add(item);
+            }
+        }
+        collection.clear();
+        collection.addAll(matched);
+        return matched.size();
+    }
+
+    @SuppressWarnings({ "rawtypes", "unchecked" })
+    @Override
+    public int filter(T rootObject, Class<?> childClass) throws QueryException {
+        // retrieve underlying collection
+        TypeInfo childType = rootType.getCollectionChild(childClass);
+        if (childType == null || !(childType instanceof IteratableTypeInfo)) {
+            return 0;
+        }
+        Collection collection = (Collection)
+                childType.getAccessor().getValue(rootObject);
+        // get the child type of the collection type
+        TypeInfo ti = childType.getCollectionChild(childClass);
+        List matched = new ArrayList();
+        for (Object item : collection) {
+            if (match(item, ti)) {
+                matched.add(item);
+            }
+        }
+        collection.clear();
+        collection.addAll(matched);
+        return matched.size();
+    }
+
+    private boolean match(final Object object, final TypeInfo rootType)
+            throws QueryException {
+        return expression.accept(new Visitor () {
+            @Override
+            public boolean visit(LogicalExpression le) throws QueryException {
+                if (LOGGER.isDebugEnabled()) {
+                    LOGGER.debug("Logical exp {}|{}|{}", le.getOperator(), le.getFirst(),
+                            le.getSecond());
+                }
+                return (le.getOperator() == LogicalExpression.OP.AND) ?
+                        le.getFirst().accept(this) && le.getSecond().accept(this) :
+                            le.getFirst().accept(this) || le.getSecond().accept(this);
+            }
+
+            @Override
+            public boolean visit(CompareExpression ce) throws QueryException {
+                boolean result = visitInternal(ce);
+                if (LOGGER.isDebugEnabled()) {
+                    LOGGER.debug("=== Compare exp {}|{}|{} == {}", ce.getOperator(),
+                            ce.getSelector(), ce.getArgument(), result);
+                }
+                return result;
+            }
+
+            public boolean visitInternal(CompareExpression ce) throws QueryException {
+                String[] selector = ce.getSelector().split("\\.");
+                if (!rootType.getName().equals(selector[0])) {
+                    if (LOGGER.isDebugEnabled()) {
+                        LOGGER.debug("Root name mismatch: {} != {}",
+                                rootType.getName(), selector[0]);
+                    }
+                    return false;
+                }
+                Object value = rootType.retrieve(object, selector, 1);
+                if(value == null){ // nothing to compare against
+                    return false;
+                }
+                if (LOGGER.isDebugEnabled()) {
+                    LOGGER.debug("Comparing [{}] {} [{}]", ce.getArgument(),
+                            ce.getOperator(), value.toString());
+                }
+                if (value instanceof Collection) {
+                    Collection<?> collection = (Collection<?>) value;
+                    if(collection.size() == 0 && ce.getOperator() == OP.NE) {
+                        // collection doesn't contain query string
+                        return true;
+                    }
+                    // If there are elements iterate
+                    Iterator<?> it = collection.iterator();
+                    OP operator = ce.getOperator();
+                    if (operator == OP.NE) {
+                        // negate the operator
+                        operator = OP.EQ;
+                    }
+                    while (it.hasNext()) {
+                        Object item = it.next();
+                        if (compare(parse(ce.getArgument(), item), item, operator)) {
+                            // if match found check the operator and return false for NE
+                            return (ce.getOperator() != OP.NE);
+                        }
+                    }
+                    // return true for NE and false for rest
+                    return (ce.getOperator() == OP.NE);
+                } else {
+                    return compare(parse(ce.getArgument(), value), value,
+                            ce.getOperator());
+                }
+            }
+
+        });
+    }
+
+    private boolean compare(Object valueToMatch, Object actualValue, OP operator) {
+        if (valueToMatch == null || actualValue == null) return false;
+        if (ALLOW_OBJECT_STRING_COMPARE && (valueToMatch instanceof String)
+                && !(actualValue instanceof String)) {
+            actualValue = actualValue.toString();
+        }
+
+        int compareResult = -1;
+        if (valueToMatch instanceof Comparable) {
+            compareResult = ((Comparable)actualValue).compareTo(valueToMatch);
+        } else {
+            if (LOGGER.isDebugEnabled()) {
+                LOGGER.debug("Not a comparable type: {} {}",
+                        valueToMatch.getClass().getName(),
+                        actualValue.getClass().getName());
+            }
+            return false;
+        }
+        switch(operator) {
+            case EQ :
+                return compareResult == 0;
+            case RE :
+                // Regex match,
+                if (valueToMatch instanceof String) {
+                    return Pattern.matches((String)valueToMatch, actualValue.toString());
+                } else {
+                    return compareResult == 0;
+                }
+            case NE:
+                return compareResult != 0;
+            case GT :
+                return compareResult > 0;
+            case GE :
+                return compareResult >= 0;
+            case LT :
+                return compareResult < 0;
+            case LE :
+                return compareResult <= 0;
+            default:
+                if (LOGGER.isDebugEnabled()) {
+                    LOGGER.debug("Unrecognized comparator - {}", operator);
+                }
+            return false;
+        }
+    }
+    private Object parse(String arg, Object value) {
+        if (value == null) return null;
+
+        try {
+            if (value instanceof String) {
+                return arg;
+            } else if (value instanceof Byte) {
+                return Byte.decode(arg);
+            } else if (value instanceof Double) {
+                return Double.parseDouble(arg);
+            } else if (value instanceof Float) {
+                return Float.parseFloat(arg);
+            } else if (value instanceof Integer) {
+                return Integer.parseInt(arg);
+            } else if (value instanceof Long) {
+                return Long.parseLong(arg);
+            } else if (value instanceof Short) {
+                return Short.parseShort(arg);
+            }
+        } catch (NumberFormatException ignore) {
+            if (LOGGER.isDebugEnabled()) {
+                LOGGER.debug("Exception parsing {}", arg, value);
+            }
+        }
+        if (LOGGER.isDebugEnabled()) {
+            LOGGER.debug("Using string comparision for type - {}",
+                    value.getClass().getName());
+        }
+        // Not a number or string. Convert to a string and compare as last resort
+        return ALLOW_OBJECT_STRING_COMPARE ? arg.toString() : null;
+    }
+
+}
diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/TypeInfo.java b/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/TypeInfo.java
new file mode 100644 (file)
index 0000000..91f01d8
--- /dev/null
@@ -0,0 +1,294 @@
+package org.opendaylight.controller.northbound.commons.query;
+
+import java.beans.BeanInfo;
+import java.beans.IntrospectionException;
+import java.beans.Introspector;
+import java.beans.PropertyDescriptor;
+import java.lang.annotation.Annotation;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlAttribute;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlElementRef;
+import javax.xml.bind.annotation.XmlElementWrapper;
+import javax.xml.bind.annotation.XmlRootElement;
+import javax.xml.bind.annotation.XmlTransient;
+import javax.xml.bind.annotation.XmlType;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * A wrapper over a JAXB type to allow traversal of the object graph and
+ * search for specific values in the object tree.
+ */
+/*package*/ class TypeInfo {
+
+    public static final Logger LOGGER = LoggerFactory.getLogger(TypeInfo.class);
+    public static final String DEFAULT_NAME = "##default";
+
+    protected final String _name; // the jaxb name
+    protected Class<?> _class; // jaxb type class
+    protected final XmlAccessType _accessType; // jaxb access type
+    protected final Accessor _accessor; // accessor to access object value
+    protected Map<String,TypeInfo> _types = new HashMap<String,TypeInfo>();
+    protected volatile boolean _explored = false;
+    /**
+     * Create a TypeInfo with a name and a class type. The accessor will be null
+     * for a root node.
+     */
+    protected TypeInfo(String name, Class<?> clz, Accessor accessor) {
+        _name = name;
+        _class = clz;
+        _accessor = accessor;
+        XmlAccessorType accessorType = null;
+        if(clz == null) {
+            throw new NullPointerException("Type class can not be null");
+        }
+        accessorType = clz.getAnnotation(XmlAccessorType.class);
+        _accessType = (accessorType == null ?
+                XmlAccessType.PUBLIC_MEMBER : accessorType.value());
+        if (LOGGER.isDebugEnabled()) {
+            LOGGER.debug("Created type info name:{} type:{}", _name, _class);
+        }
+    }
+
+    /**
+     * @return the Accessor to access the value
+     */
+    public final Accessor getAccessor() {
+        return _accessor;
+    }
+
+    /**
+     * @return get the child by name
+     */
+    public final TypeInfo getChild(String name) {
+        return _types.get(name);
+    }
+
+    public TypeInfo getCollectionChild(Class<?> childType) {
+        explore();
+        for (TypeInfo ti : _types.values()) {
+            if (Collection.class.isAssignableFrom(ti.getType())) {
+                ParameterizedType p = (ParameterizedType)
+                        ti.getAccessor().getGenericType();
+                Type[] pts = p.getActualTypeArguments();
+                if (pts.length == 1 && pts[0].equals(childType)) {
+                    return ti;
+                }
+            }
+        }
+        return null;
+    }
+
+    public Class getType() {
+        return _class;
+    }
+
+    public String getName() {
+        return _name;
+    }
+
+    /**
+     * @return the object value by a selector query
+     */
+    public Object retrieve(Object target, String[] query, int index)
+            throws QueryException {
+        if (LOGGER.isDebugEnabled()) {
+            LOGGER.debug("retrieve: {}/{} type:{}", index, query.length, target.getClass());
+        }
+        if (index >= query.length) return null;
+        explore();
+        if (!target.getClass().equals(_class)) {
+            if (_class.isAssignableFrom(target.getClass())) {
+                if (LOGGER.isDebugEnabled()) {
+                    LOGGER.debug("Handling subtype {} of {} ", target.getClass(), _class);
+                }
+                // explore the subtype
+                TypeInfo subTypeInfo = new TypeInfo(getRootName(target.getClass()),
+                        target.getClass(), _accessor);
+                return subTypeInfo.retrieve(target, query, index);
+            } else {
+                // non compatible object; bail out
+                return null;
+            }
+        }
+        TypeInfo child = getChild(query[index]);
+        if (child == null) return null;
+        target = child.getAccessor().getValue(target);
+        if (index+1 == query.length) {
+            // match found
+            return target;
+        }
+        return child.retrieve(target, query, index+1);
+    }
+
+    /**
+     * Explore the type info for children.
+     */
+    public synchronized void explore() {
+        if (_explored) return;
+        for (Class<?> c = _class; c != null; c = c.getSuperclass()) {
+            if (c.equals(Object.class)) break;
+            // Currently only fields and methods annotated with JAXB annotations are
+            // considered as valid for search purposes.
+            //check methods first
+            for (Method m : c.getDeclaredMethods()) {
+                String tn = getTypeName(m, _accessType);
+                if (tn != null) {
+                    if (LOGGER.isDebugEnabled()) LOGGER.debug(
+                            "exploring type: {} name: {} method: {}",
+                            _class.getSimpleName(), tn, m);
+                    _types.put(tn, createTypeInfo(tn, new Accessor(m)));
+                }
+            }
+            for (Field f : c.getDeclaredFields()) {
+                String tn = getTypeName(f, _accessType);
+                if (tn != null) {
+                    if (LOGGER.isDebugEnabled()) LOGGER.debug(
+                            "exploring type: {} name: {} field: {}",
+                            _class.getSimpleName(), tn, f);
+                    _types.put(tn, createTypeInfo(tn, new Accessor(f)));
+                }
+            }
+        }
+        _explored = true;
+    }
+
+    public static final String getTypeName(Field f, XmlAccessType access) {
+        // ignore static, transient and xmltransient fields
+        if (Modifier.isTransient(f.getModifiers()) ||
+                Modifier.isStatic(f.getModifiers()) ||
+                f.getAnnotation(XmlTransient.class) != null ) {
+            return null;
+        }
+        // try to read annotation
+        String name = getTypeName(f.getAnnotations(), f.getName());
+        if (name != null) return name;
+        // no annotation present check accesstype
+        else if (access == XmlAccessType.NONE) { // none return name
+            return name;
+        } else if (access == XmlAccessType.FIELD) {
+            // return field name if no annotation present
+            return f.getName();
+        } else if (access == XmlAccessType.PUBLIC_MEMBER
+                && Modifier.isPublic(f.getModifiers())) { // look for public access
+            return f.getName();
+        }
+        // return annotated name ( if any )
+        return null;
+    }
+
+    public static final String getTypeName(Method m, XmlAccessType access) {
+        // ignore static, transient and xmltransient fields
+        if (Modifier.isStatic(m.getModifiers()) ||
+                m.getAnnotation(XmlTransient.class) != null ) {
+            return null;
+        }
+        // try to read annotation
+        String name = getTypeName(m.getAnnotations(), m.getName());
+        if (name != null) return name;
+        //check acces type
+        else if (access == XmlAccessType.NONE) { // none return name
+            return name;
+        } else if (access == XmlAccessType.PROPERTY) {
+            // return bean property name if no annotation present
+            return getBeanPropertyName(m);
+        } else if (access == XmlAccessType.PUBLIC_MEMBER
+                && Modifier.isPublic(m.getModifiers())) { // look for public access
+            return getBeanPropertyName(m);
+        }
+        return null;
+    }
+
+    private static String getBeanPropertyName(Method m){
+        try
+        {
+            Class<?> clazz=m.getDeclaringClass();
+            BeanInfo info = Introspector.getBeanInfo(clazz);
+            PropertyDescriptor[] props = info.getPropertyDescriptors();
+            for (PropertyDescriptor pd : props)
+            {
+                if (m.equals(pd.getReadMethod())) return pd.getName();
+            }
+        }
+        catch (IntrospectionException e)
+        {
+            LOGGER.error("Could not read bean property name for method = {}",
+                    m.getName(), e);
+        }
+        return null;
+    }
+
+    public static TypeInfo createRoot(String name, Class<?> clz) {
+        // root is always a composite type
+        // FIXME assert its a JAXB type
+        XmlRootElement root = clz.getAnnotation(XmlRootElement.class);
+        if (root == null) throw new IllegalArgumentException("Not a JAXB type: " + clz);
+        if (name == null) name = getRootName(clz);
+        return new TypeInfo(name, clz, null);
+    }
+
+    public static TypeInfo createTypeInfo(String name, Accessor accessor) {
+        if (accessor.getAccessibleObject().getAnnotation(XmlElementWrapper.class) != null) {
+            //XmlElementWrapperType
+            return new WrapperTypeInfo(name, accessor);
+        } else if (Collection.class.isAssignableFrom(accessor.getType())) {
+            // collection type
+            return new IteratableTypeInfo(name, accessor);
+        }
+        return new TypeInfo(name, accessor.getType(), accessor);
+    }
+
+    public static String getRootName(Class<?> cls) {
+        XmlRootElement root = cls.getAnnotation(XmlRootElement.class);
+        if (root == null) return null;
+        String rootName = root.name();
+        if (DEFAULT_NAME.equals(rootName)) {
+            String clsName = cls.getSimpleName();
+            rootName = Character.toLowerCase(clsName.charAt(0)) + clsName.substring(1);
+        }
+        return rootName;
+    }
+
+    protected static String getTypeName(Annotation[] annotations, String dflt) {
+        String name = null;
+        for (Annotation a : annotations) {
+            if (a.annotationType() == XmlAttribute.class) {
+                name = ((XmlAttribute)a).name();
+            } else if (a.annotationType() == XmlElement.class) {
+                name = ((XmlElement)a).name();
+            } else if (a.annotationType() == XmlElementRef.class) {
+                name = ((XmlElementRef)a).name();
+            } else if (a.annotationType() == XmlElementWrapper.class) {
+                name = ((XmlElementWrapper)a).name();
+                // break the loop as we don't want name to be overwritten by XmlElement
+                break;
+            } else if (a.annotationType() == XmlType.class) {
+                name = ((XmlType)a).name();
+            } else if (a.annotationType() == XmlTransient.class) {
+                // transient type
+                return null;
+            }
+        }
+        if (DEFAULT_NAME.equals(name)) return dflt;
+        return name;
+    }
+
+    @Override
+    public String toString() {
+        return " TypeInfo [_name=" + _name + ", _class=" + _class
+                + ", _accessType=" + _accessType + ", _accessor=" + _accessor
+                + ", _types=" + _types + ", _explored=" + _explored + " ] ";
+    }
+}
diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Visitor.java b/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/Visitor.java
new file mode 100644 (file)
index 0000000..0c1d2be
--- /dev/null
@@ -0,0 +1,16 @@
+/**
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.northbound.commons.query;
+
+/*package*/ interface Visitor {
+
+    boolean visit(LogicalExpression exp) throws QueryException;
+
+    boolean visit(CompareExpression exp) throws QueryException;
+
+}
diff --git a/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/WrapperTypeInfo.java b/opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/query/WrapperTypeInfo.java
new file mode 100644 (file)
index 0000000..a8172f2
--- /dev/null
@@ -0,0 +1,59 @@
+/**
+ * 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.northbound.commons.query;
+
+import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+
+import javax.xml.bind.annotation.XmlElement;
+
+public class WrapperTypeInfo extends TypeInfo {
+
+    protected WrapperTypeInfo(String name, Accessor accessor) {
+        super(name, accessor.getType(), accessor);
+    }
+
+    @Override
+    public Object retrieve(Object target, String[] query, int index) throws QueryException {
+        if (LOGGER.isDebugEnabled()) {
+            LOGGER.debug("retrieve collection: {}/{}", index, query.length);
+        }
+        if (index >= query.length) return null;
+        explore();
+        TypeInfo child = getChild(query[index]);
+        if (child == null) return null;
+        if (query.length == index+1) { // skipping this node
+            return target;
+        }else { // if list of list go to next node to get value
+            return child.retrieve(target, query, index+1);
+        }
+    }
+
+    @Override
+    public synchronized void explore() {
+        if (_explored) return;
+        if (LOGGER.isDebugEnabled()) {
+            LOGGER.debug("exploring wrapper type: {} gtype: {}", _class,
+                    _accessor.getGenericType());
+        }
+        String tn = null;
+        AccessibleObject accessibleObject = _accessor.getAccessibleObject();
+        XmlElement xmlElement = accessibleObject.getAnnotation(XmlElement.class);
+        if (accessibleObject instanceof Field) {
+            Field f = (Field) accessibleObject;
+            tn = DEFAULT_NAME.equals(xmlElement.name())?f.getName() : xmlElement.name();
+        }else if (accessibleObject instanceof Method) {
+            Method m = (Method) accessibleObject;
+            tn = DEFAULT_NAME.equals(xmlElement.name())?m.getName() : xmlElement.name();
+        }
+        this._types.put(tn, new IteratableTypeInfo(tn, this._accessor));
+        _explored = true;
+    }
+
+}
diff --git a/opendaylight/northbound/commons/src/main/javacc/fiql.jj b/opendaylight/northbound/commons/src/main/javacc/fiql.jj
new file mode 100644 (file)
index 0000000..b447a32
--- /dev/null
@@ -0,0 +1,124 @@
+
+options {
+  STATIC = false;
+}
+
+PARSER_BEGIN(FiqlParser)
+package org.opendaylight.controller.northbound.commons.query;
+
+import java.util.regex.*;
+
+/*package*/ class FiqlParser {
+  public static Expression parse(String query) throws ParseException {
+    FiqlParser parser = new FiqlParser(new java.io.StringReader(query));
+    return parser.START();
+  }
+}
+
+PARSER_END(FiqlParser)
+
+/* whitespace */
+SKIP :
+{
+  " " | "\t"
+}
+
+TOKEN : {
+  <#ALPHA  : ( ["a"-"z", "A"-"Z", "0"-"9"] )+ >
+}
+
+TOKEN : {
+  <NUM     : ("+"|"-")?(["0"-"9"])+"."(["0"-"9"])* >
+  |
+  <LPAREN  : "(" >
+  |
+  <RPAREN  : ")" >
+}
+
+/* comparision ops */
+TOKEN : {
+  <RE      : ("=") >
+  |
+  <EQ      : ("==" | "=eq=") >
+  |
+  <NE      : ("!=" | "=ne=") >
+  |
+  <LT      : ("=lt=" | "<") >
+  |
+  <LE      : ("=le=" | "<=") >
+  |
+  <GT      : ("=gt=" | ">") >
+  |
+  <GE      : ("=ge=" | ">=") >
+}
+
+/* ops */
+TOKEN : {
+  <AND     : (";" | "and") >
+  |
+  <OR      : ("," | "or") >
+}
+
+/* strings */
+TOKEN : {
+  <STRING : ( ~["\"", "'", "(", ")", ";", ",", "=", "<", ">", "!", "~", " "] )+ >
+  |
+  <DQ_STRING : ( "\"" ( ~["\""] )* "\"" ) >
+  |
+  <SQ_STRING : ( "'" ( ~["'"] )* "'" ) >
+}
+
+/* Root production */
+Expression START() :
+{
+  Expression e;
+}
+{
+  e = EXPR()
+  <EOF>
+  {
+    return e;
+  }
+}
+
+Expression EXPR():
+{
+  ExpressionBuilder builder = new ExpressionBuilder();
+  Expression t;
+}
+{
+  t = TERM() { builder.withTerm(t); }
+  (
+    (<AND> t = TERM()) { builder.withAnd().withTerm(t); }
+    |
+    (<OR> t = TERM() ) { builder.withOr().withTerm(t); }
+  )*
+  {
+    return builder.build();
+  }
+}
+
+Expression TERM() :
+{
+  Token selector, arg;
+  Expression exp;
+  CompareExpression.OP op;
+}
+{
+  selector = <STRING>
+  (
+    ( <EQ>  {op=CompareExpression.OP.EQ;} |
+      <RE>  {op=CompareExpression.OP.RE;} |
+      <NE>  {op=CompareExpression.OP.NE;} |
+      <LT>  {op=CompareExpression.OP.LT;} |
+      <LE>  {op=CompareExpression.OP.LE;} |
+      <GT>  {op=CompareExpression.OP.GT;} |
+      <GE>  {op=CompareExpression.OP.GE;}
+    )
+    ( arg = <STRING> | arg = <DQ_STRING> | arg = <SQ_STRING> | arg = <NUM>)
+  ) { return new CompareExpression(op, selector.image, arg.image); }
+  |
+  (
+    <LPAREN> exp = EXPR() <RPAREN>
+  ) { return exp; }
+}
diff --git a/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/BookBean.java b/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/BookBean.java
new file mode 100644 (file)
index 0000000..5d518f6
--- /dev/null
@@ -0,0 +1,92 @@
+package org.opendaylight.controller.northbound.commons.query;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlElementWrapper;
+import javax.xml.bind.annotation.XmlRootElement;
+
+import org.opendaylight.controller.northbound.commons.types.StringList;
+
+/**
+ */
+
+@XmlRootElement(name="book")
+public class BookBean {
+
+    @XmlElement(name="name")
+    private String _name; // simple type
+
+    private String _isbn; // method annotation
+
+    @XmlElement(name="author")
+    private PersonBean _author; // composite type
+
+    @XmlElementWrapper//for XMLWrapper iterative composite types
+    @XmlElement(name="review")
+    private final List<ReviewBean> reviews = new ArrayList<ReviewBean>();
+
+    @XmlElement
+    private List<String> soldBy; //Iterative Type
+
+    @XmlElementWrapper(name="test")
+    @XmlElement
+    private final List<StringList> testList = new ArrayList<StringList>(); //XMLWrapper list of list
+
+    @XmlElementWrapper(name="parent")
+    @XmlElement(name="child")
+    private final List<WrapperList> wrapperList = new ArrayList<WrapperList>(); // XMLWrapper of XMLWrapper
+
+    public BookBean(){}
+
+    public BookBean(String name, String id, PersonBean person) {
+        _name = name;
+        _isbn = id;
+        _author = person;
+        soldBy = new ArrayList<String>();
+    }
+
+    public BookBean addReview(ReviewBean review) {
+        reviews.add(review);
+        return this;
+    }
+
+    public void setSellerInfo(List<String> sellers) {
+        soldBy = new ArrayList<String>(sellers);
+    }
+
+    public void addWrapperList(WrapperList list){
+        wrapperList.add(list);
+    }
+
+    public void addToTestList(StringList testList){
+        this.testList.add(testList);
+    }
+    public String getName() {
+        return "1"+_name;
+    }
+
+    @XmlElement(name="isbn")
+    public String get_isbn() {
+        return "pre"+_isbn;
+    }
+
+    public PersonBean getauthor() {
+        return _author;
+    }
+
+    @Override
+    public String toString() {
+        return "BookBean [_name=" + _name + ", _isbn=" + _isbn + ", _author="
+                + _author + ", reviews=" + reviews + ", soldBy=" + soldBy
+                + ", testList=" + testList + ", wrapperList=" + wrapperList + "]";
+    }
+
+}
+
+class WrapperList {
+  @XmlElementWrapper(name="items")
+  @XmlElement
+  public List<String> item = new ArrayList<String>();
+}
diff --git a/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/ExpresssionTest.java b/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/ExpresssionTest.java
new file mode 100644 (file)
index 0000000..3e2e153
--- /dev/null
@@ -0,0 +1,207 @@
+/**
+ * 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.northbound.commons.query;
+
+import java.lang.reflect.Field;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.regex.Pattern;
+
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.controller.northbound.commons.query.CompareExpression.OP;
+
+public class ExpresssionTest {
+
+    private static final List<PersonBean> people = new ArrayList<PersonBean>();
+    private static final ArrayList<BookBean> books = new ArrayList<BookBean>();
+
+    public static void p(String msg) {
+        //System.out.println("======= " + msg);
+    }
+
+    public static boolean matches(Expression exp, final PersonBean person) throws Exception {
+
+        boolean result = exp.accept(new Visitor() {
+            @Override
+            public boolean visit(LogicalExpression le) throws QueryException {
+                p("=== LE " + le.getOperator() + "|" + le.getFirst() + "|" + le.getSecond());
+                return (le.getOperator() == LogicalExpression.OP.AND) ?
+                        le.getFirst().accept(this) && le.getSecond().accept(this) :
+                            le.getFirst().accept(this) || le.getSecond().accept(this);
+            }
+
+            @Override
+            public boolean visit(CompareExpression ce) {
+                p("=== CE " + ce.getOperator() + "|" + ce.getSelector() + "|" + ce.getArgument());
+                if (person == null) {
+                    return false;
+                }
+                try {
+                    // check if the selector matches any of the fields
+                    Field field = PersonBean.class.getDeclaredField(ce.getSelector());
+                    if (field == null) {
+                        p("No field found by name : " + ce.getSelector());
+                        return false;
+                    }
+                    Object value = field.get(person);
+                    if (value instanceof String) {
+                        p("Comparing [" + ce.getArgument() + "] "+ ce.getOperator() + " [" + value.toString() + "]");
+                        if (ce.getOperator() == OP.EQ) {
+                            return ce.getArgument().equals(value.toString());
+                        } else if (ce.getOperator() == OP.RE) {
+                            return Pattern.matches(ce.getArgument(), value.toString());
+                        } else if (ce.getOperator() == OP.NE) {
+                            return !ce.getArgument().equals(value.toString());
+                        } else {
+                            p("Comparator : " + ce.getOperator() + " cannot apply to Strings");
+                            return false;
+                        }
+                    } else {
+                        // assume its a #
+                        int valToMatch = Integer.parseInt(ce.getArgument());
+                        int actualValue = (Integer)value;
+                        p("Comparing: " + valToMatch + " " + ce.getOperator() + " " + actualValue);
+                        switch(ce.getOperator()) {
+                        case EQ :
+                        case RE :
+                            return actualValue == valToMatch;
+                        case NE :
+                            return actualValue != valToMatch;
+                        case GT :
+                            return actualValue > valToMatch;
+                        case GE :
+                            return actualValue >= valToMatch;
+                        case LT :
+                            return actualValue < valToMatch;
+                        case LE :
+                            return actualValue <= valToMatch;
+                        default:
+                            p("Unrecognized compare operator: " + ce.getOperator());
+                            return false;
+                        }
+                    }
+                } catch (Exception e) {
+                    throw new IllegalStateException(e);
+                }
+            }
+        });
+        p("RESULT: " + result);
+        return result;
+    }
+
+    @BeforeClass
+    public static void load() {
+        System.setProperty("org.slf4j.simpleLogger.defaultLogLevel", "debug");
+
+        people.add(new PersonBean(100, "John", "Doe", "San Jose"));
+        people.add(new PersonBean(200, "Foo", "Bar", "San Francisco"));
+        people.add(new PersonBean(300, "A", "B", "San Francisco"));
+        people.add(new PersonBean(400, "X", "Y", "New York"));
+
+        books.add(new BookBean("Book1", "A001", people.get(0)));
+        books.add(new BookBean("Book2", "A002", people.get(1)));
+        books.add(new BookBean("Book3", "A003", people.get(2)));
+
+        ReviewBean review1 = new ReviewBean("cool", people.get(2));
+        ReviewBean review2 = new ReviewBean("kewl", people.get(3));
+        ReviewBean review3 = new ReviewBean("+++", people.get(0));
+        ReviewBean review4 = new ReviewBean("---", people.get(1));
+
+        books.get(0).addReview(review1).addReview(review2).addReview(review3).addReview(review4);
+        books.get(1).addReview(review1).addReview(review2).addReview(review3).addReview(review4);
+        books.get(2).addReview(review1).addReview(review2).addReview(review3).addReview(review4);
+    }
+
+    @Test
+    public void testCXFQueries() throws Exception {
+        // following queries copied from apache cxf
+        Assert.assertFalse(matches(parseQuery("id=gt=100;name=Fred"), null));
+        Assert.assertFalse(matches(parseQuery("id=gt=100;name==Fred"), null));
+        Assert.assertFalse(matches(parseQuery("id=lt=123"), null));
+        Assert.assertFalse(matches(parseQuery("date=le=2010-03-11"), null));
+        Assert.assertFalse(matches(parseQuery("time=le=2010-03-11T18:00:00"), null));
+        Assert.assertFalse(matches(parseQuery("name==CXF;version=ge=2.2"), null));
+        Assert.assertFalse(matches(parseQuery("(age=lt=25,age=gt=35);city==London"), null));
+        Assert.assertFalse(matches(parseQuery("date=lt=2000-01-01;date=gt=1999-01-01;(sub==math,sub==physics)"), null));
+    }
+
+    public Expression parseQuery(String query) throws Exception {
+        p("PARSING query: " + query);
+        // FiqlParser is a parser generated by javacc
+        Expression exp = FiqlParser.parse(query);
+        p(exp.toString());
+        return exp;
+    }
+
+    public int find(String query) throws Exception {
+        int found = 0;
+        Expression exp = parseQuery(query);
+        TypeInfo.createRoot("person", PersonBean.class);
+        for (PersonBean person : people) {
+            if (matches(exp, person)) found++;
+        }
+        return found;
+    }
+
+    @Test
+    public void testPeopleQueries() throws Exception {
+        Assert.assertTrue(find("id==200") == 1);
+        Assert.assertTrue(find("id!=100;(city='San.*')") == 2);
+        Assert.assertTrue(find("id>200;(city='San.*')") == 1);
+        Assert.assertTrue(find("city='San.*'") == 3);
+    }
+
+    @Test
+    public void testTypeTree() throws Exception {
+        TypeInfo bookType = TypeInfo.createRoot("book", BookBean.class);
+        Assert.assertEquals("John", bookType.retrieve(books.get(0),
+                "book.author.firstName".split("\\."), 1));
+        Object result = bookType.retrieve(books.get(0),
+                "book.reviews.review.comment".split("\\."), 1);
+        Assert.assertTrue( result instanceof List);
+        List<Object> commentList = (List<Object>) result;
+        Assert.assertTrue(commentList.contains("cool"));
+    }
+
+    @Test
+    public void testQueryAPI() throws Exception {
+        QueryContext qc = new QueryContextImpl();
+
+        // find all books written by author with firstName "John"
+        Query q1 = qc.createQuery("book.author.firstName==John", BookBean.class);
+        Collection<BookBean> r1 = q1.find(books);
+        p("Filtered books: " + r1.size());
+        Assert.assertEquals(1, r1.size());
+
+        // find all books reviewed by people in a city "San*"
+        Query q2 = qc.createQuery("book.reviews.review.reviewer.city=San.*", BookBean.class);
+        Collection<BookBean> r2 = q2.find(books);
+
+        p("Filtered books: " + r2.size());
+        Assert.assertEquals(3, r2.size());
+
+        // find all books reviewed by people in a city "San*"
+        Query q3 = qc.createQuery("book==foo", BookBean.class);
+        Collection<BookBean> r3 = q3.find(books);
+        Assert.assertEquals(0, r3.size());
+    }
+
+    @Test
+    public void testFilter() throws Exception {
+        Library library = new Library((List)books.clone());
+        QueryContext qc = new QueryContextImpl();
+        // find all books written by author with firstName "John"
+        Query q1 = qc.createQuery("book.author.firstName==John", Library.class);
+        int sizeBefore = library.getList().size();
+        System.out.println(q1.filter(library, BookBean.class));
+        Assert.assertEquals(1, library.getList().size());
+    }
+}
diff --git a/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/Library.java b/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/Library.java
new file mode 100644 (file)
index 0000000..c54b0e7
--- /dev/null
@@ -0,0 +1,29 @@
+/**
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.northbound.commons.query;
+
+import java.util.List;
+
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement(name="library")
+public class Library {
+
+    @XmlElement(name="book")
+    private final List<BookBean> _list;
+
+    public Library(List<BookBean> list) {
+        _list = list;
+    }
+
+    public List<BookBean> getList() {
+        return _list;
+    }
+
+}
diff --git a/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/PersonBean.java b/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/PersonBean.java
new file mode 100644 (file)
index 0000000..b4b9ed5
--- /dev/null
@@ -0,0 +1,50 @@
+/**
+ * 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.northbound.commons.query;
+
+import java.util.List;
+
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlElementWrapper;
+import javax.xml.bind.annotation.XmlRootElement;
+
+@XmlRootElement(name="person")
+
+public class PersonBean {
+
+    @XmlElement
+    public String firstName;
+    @XmlElement
+    public String lastName;
+    @XmlElement
+    public String city;
+    @XmlElement
+    public int id;
+
+    @XmlElementWrapper(name="emails") // ElementWrapper iteratable type
+    @XmlElement
+    public List<String> email;
+
+    public PersonBean(){}
+    public PersonBean(int n, String f, String l, String c) {
+        firstName = f;
+        lastName = l;
+        city = c;
+        id = n;
+    }
+
+    public void setEmail(List<String> emails){
+        email = emails;
+    }
+    @Override
+    public String toString() {
+        return "PersonBean [firstName=" + firstName + ", lastName=" + lastName
+                + ", city=" + city + ", id=" + id + "]";
+    }
+
+}
diff --git a/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/QueryContextTest.java b/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/QueryContextTest.java
new file mode 100644 (file)
index 0000000..b6e582b
--- /dev/null
@@ -0,0 +1,269 @@
+/**
+ * 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.northbound.commons.query;
+
+import java.io.ByteArrayOutputStream;
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.Marshaller;
+
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.opendaylight.controller.northbound.commons.types.StringList;
+
+public class QueryContextTest {
+
+    protected static final List<PersonBean> people = new ArrayList<PersonBean>();
+    protected static final List<BookBean> books = new ArrayList<BookBean>();
+
+    public static void p(String msg) {
+        System.out.println("=== " + msg);
+    }
+
+    @BeforeClass
+    public static void load() {
+        people.add(new PersonBean(100, "John", "Doe", "San Jose"));
+        people.add(new PersonBean(200, "Foo", "Bar", "San Francisco"));
+        people.add(new PersonBean(300, "A", "B", "San Francisco"));
+        people.add(new PersonBean(400, "X", "Y", "New York"));
+
+        books.add(new BookBean("Book1", "A001", people.get(0)));
+        books.add(new BookBean("Book2", "A002", people.get(1)));
+        books.add(new BookBean("Book3", "A003", people.get(2)));
+
+        ReviewBean review1 = new ReviewBean("cool", people.get(2));
+        ReviewBean review2 = new ReviewBean("kewl", people.get(3));
+
+        books.get(0).addReview(review1).addReview(review2);
+        books.get(1).addReview(review1);
+        books.get(2).addReview(review2).addReview(review1);
+
+    }
+
+    @Test
+    public void testQueryContext() {
+        QueryContext queryContext = new QueryContextImpl();
+        Assert.assertNotNull(queryContext);
+    }
+
+    @Test
+    public void testSimpleQuery() throws QueryException {
+        QueryContext queryContext = new QueryContextImpl();
+        Query<PersonBean> query = queryContext.createQuery(
+                "person.id==200", PersonBean.class);
+        Assert.assertNotNull(query);
+
+        List<PersonBean> found = query.find(people);
+        Assert.assertNotNull(found);
+        Assert.assertTrue(found.size() == 1);
+        Assert.assertEquals("Foo", found.get(0).firstName);
+    }
+
+    @Test
+    public void testAndQuery() throws QueryException {
+        QueryContext queryContext = new QueryContextImpl();
+        Query<PersonBean> query = queryContext.createQuery(
+                "person.id!=200;(person.city='San.*')", PersonBean.class);
+        Assert.assertNotNull(query);
+
+        List<PersonBean> found = query.find(people);
+        Assert.assertNotNull(found);
+        Assert.assertTrue(found.size() == 2);
+        Assert.assertEquals("John", found.get(0).firstName);
+        Assert.assertEquals("A", found.get(1).firstName);
+    }
+
+    @Test
+    public void testOrQuery() throws QueryException {
+        QueryContext queryContext = new QueryContextImpl();
+        Query<PersonBean> query = queryContext.createQuery(
+                "person.id==200,(person.city='San.*')", PersonBean.class);
+        Assert.assertNotNull(query);
+
+        List<PersonBean> found = query.find(people);
+        Assert.assertNotNull(found);
+        Assert.assertTrue(found.size() == 3);
+        Assert.assertEquals("John", found.get(0).firstName);
+        Assert.assertEquals("Foo", found.get(1).firstName);
+        Assert.assertEquals("A", found.get(2).firstName);
+    }
+
+    @Test
+    public void testXmlElementWrapper() throws QueryException {
+        List<String> emails = new ArrayList<String>();
+        emails.add("john@cisco.com");
+        emails.add("john@gmail.com");
+        people.get(0).setEmail(emails);
+
+        p(toXml(people.get(0)));
+        QueryContext queryContext = new QueryContextImpl();
+        Query<PersonBean> query = queryContext.createQuery(
+                "person.emails.email==john@cisco.com", PersonBean.class);
+        Assert.assertNotNull(query);
+
+        List<PersonBean> found = query.find(people);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(1,found.size());
+        Assert.assertEquals("John", found.get(0).firstName);
+    }
+
+    @Test
+    public void testXmlWrapperOfWrapper() throws QueryException{
+        WrapperList wrapper = new WrapperList();
+        wrapper.item.add("Test1");
+        wrapper.item.add("Test2");
+
+        books.get(0).addWrapperList(wrapper);
+        books.get(1).addWrapperList(wrapper);
+
+        System.out.println(toXml(books.get(0)));
+        QueryContext queryContext = new QueryContextImpl();
+        Query<BookBean> query = queryContext.createQuery(
+                "book.parent.child.items.item==Test1", BookBean.class);
+        Assert.assertNotNull(query);
+    }
+
+    @Test
+    public void testXmlElementWrapperListofList() throws QueryException {
+        // create Stringlist
+        List<String> testList = new ArrayList<String>();
+        testList.add("A");
+        testList.add("B");
+        StringList itemList = new StringList(testList);
+        books.get(0).addToTestList(itemList);
+
+        System.out.println(toXml(books.get(0)));
+        QueryContext queryContext = new QueryContextImpl();
+        Query<BookBean> query = queryContext.createQuery(
+                "book.test.testList.item==A", BookBean.class);
+        Assert.assertNotNull(query);
+    }
+
+    @Test
+    public void testPrimitiveIteratableTypes() throws QueryException {
+        // Load data for this test
+        List<String> sellers = new ArrayList<String>();
+        sellers.add("Amazon");
+
+        books.get(0).setSellerInfo(sellers);
+        sellers.add("Barners & Nobles");
+        books.get(1).setSellerInfo(sellers);
+        sellers.add("Borders");
+        sellers.remove("Amazon");
+        sellers.add("BookShop");
+        books.get(2).setSellerInfo(sellers);
+
+        System.out.println(toXml(books.get(0)));
+
+        QueryContext queryContext = new QueryContextImpl();
+        Query<BookBean> query = queryContext.createQuery(
+                "book.soldBy==Amazon", BookBean.class);
+        Assert.assertNotNull(query);
+
+        List<BookBean> found = query.find(books);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(2,found.size());
+        Assert.assertEquals("John", found.get(0).getauthor().firstName);
+
+        query = queryContext.createQuery(
+                "book.soldBy!=Amazon", BookBean.class);
+        Assert.assertNotNull(query);
+
+        found = query.find(books);
+        System.out.println("books" +found);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(1,found.size());
+        Assert.assertEquals("A", found.get(0).getauthor().firstName);
+    }
+
+    @Test
+    public void testCompositeIteratableTypes() throws QueryException {
+        QueryContext queryContext = new QueryContextImpl();
+        Query<BookBean> query = queryContext.createQuery("book.reviews.review.reviewer.firstName==X",
+                BookBean.class);
+        Assert.assertNotNull(query);
+
+        List<BookBean> found = query.find(books);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(2, found.size());
+        Assert.assertEquals("John", found.get(0).getauthor().firstName);
+
+        query = queryContext.createQuery("book.reviews.review.comment==kewl",
+                BookBean.class);
+        Assert.assertNotNull(query);
+
+        found = query.find(books);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(2, found.size());
+        p("Book 0" + found.get(0));
+        Assert.assertEquals("John", found.get(0).getauthor().firstName);
+
+        query = queryContext.createQuery("book.reviews.review.reviewer.id>300",
+                BookBean.class);
+        Assert.assertNotNull(query);
+
+        found = query.find(books);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(2, found.size());
+        p("Book 0" + found.get(0));
+        Assert.assertEquals("John", found.get(0).getauthor().firstName);
+
+        query = queryContext.createQuery("book.reviews.review.reviewer.firstName!=X",
+                BookBean.class);
+        Assert.assertNotNull(query);
+
+        found = query.find(books);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(1, found.size());
+        p("Book 0" + found.get(0));
+        Assert.assertEquals("Foo", found.get(0).getauthor().firstName);
+    }
+
+    @Test
+    public void testXMLAccessorType() {
+        //Assert.fail("implement");
+    }
+
+    @Test
+    public void testMethodAnnotation() throws QueryException {
+        System.out.println(toXml(books.get(0)));
+        QueryContext queryContext = new QueryContextImpl();
+        Query<BookBean> query = queryContext.createQuery(
+                "book.isbn==preA003", BookBean.class);
+        Assert.assertNotNull(query);
+
+        List<BookBean> found = query.find(books);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(1,found.size());
+        Assert.assertEquals("A", found.get(0).getauthor().firstName);
+    }
+
+    public static String toXml(Object element) {
+        try {
+            JAXBContext jc = JAXBContext.newInstance(element.getClass());
+            Marshaller marshaller = jc.createMarshaller();
+            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
+
+            ByteArrayOutputStream baos = new ByteArrayOutputStream();
+            marshaller.marshal(element, baos);
+            return baos.toString();
+        } catch (Exception e) {
+            e.printStackTrace();
+        }
+        return "";
+    }
+
+    @Test
+    public void testXMLElementWrapperForCompositeTypes(){
+        //Assert.fail("implement");
+    }
+
+}
\ No newline at end of file
diff --git a/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/ReviewBean.java b/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/ReviewBean.java
new file mode 100644 (file)
index 0000000..ea2f873
--- /dev/null
@@ -0,0 +1,41 @@
+package org.opendaylight.controller.northbound.commons.query;
+
+import java.util.Date;
+
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+
+/**
+ */
+@XmlRootElement(name="review")
+public class ReviewBean {
+    @XmlElement(name="date")
+    private  Date _publishedDate;
+    @XmlElement(name="comment")
+    private  String _comment;
+    @XmlElement(name="reviewer")
+    private  PersonBean _reviewer;
+    @XmlElement
+    private int _upVotes;
+    @XmlElement
+    private int _downVotes;
+    public ReviewBean(){}
+
+    public ReviewBean(String comment, PersonBean user) {
+        _comment = comment;
+        _reviewer = user;
+        _publishedDate = new Date();
+    }
+
+    public void vote(int up, int down) {
+        _upVotes += up;
+        _downVotes += down;
+    }
+
+    @Override
+    public String toString() {
+        return "ReviewBean <publishedDate>" + _publishedDate + "</publishedDate> <comment>"
+                + _comment + "</comment> <reviewer>" + _reviewer + "</reviewer> <upVotes>" + _upVotes
+                + "</upVotes> <downVotes>" + _downVotes + "</downVotes>";
+    }
+}
diff --git a/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/XMLAccessorTypeTest.java b/opendaylight/northbound/commons/src/test/java/org/opendaylight/controller/northbound/commons/query/XMLAccessorTypeTest.java
new file mode 100644 (file)
index 0000000..25cb692
--- /dev/null
@@ -0,0 +1,374 @@
+package org.opendaylight.controller.northbound.commons.query;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.xml.bind.annotation.XmlAccessType;
+import javax.xml.bind.annotation.XmlAccessorType;
+import javax.xml.bind.annotation.XmlElement;
+import javax.xml.bind.annotation.XmlRootElement;
+import javax.xml.bind.annotation.XmlTransient;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+public class XMLAccessorTypeTest {
+
+    @Test
+    public void testPublicAccessType() throws Exception {
+        // create bean
+        List<PublicAccessBean> testList = new ArrayList<PublicAccessBean>();
+        testList.add(new PublicAccessBean("John", "Scott", "private", 1,
+                "transient", "elem1"));
+        testList.add(new PublicAccessBean("Foo", "Bar", "private1", 2,
+                "transient1", "elem2"));
+        QueryContextTest.p(QueryContextTest.toXml(testList.get(0)));
+
+        QueryContext queryContext = new QueryContextImpl();
+        Assert.assertNotNull(queryContext);
+        // search for public field
+        Query<PublicAccessBean> query = queryContext.createQuery(
+                "publicbean.firstName==Foo", PublicAccessBean.class);
+        Assert.assertNotNull(query);
+
+        List<PublicAccessBean> found = query.find(testList);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(1, found.size());
+        Assert.assertEquals("Foo", found.get(0).firstName);
+
+        // search for public getter
+        query = queryContext.createQuery("publicbean.privateGetterField<2",
+                PublicAccessBean.class);
+        Assert.assertNotNull(query);
+
+        found = query.find(testList);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(1, found.size());
+        Assert.assertEquals("John", found.get(0).firstName);
+
+        // test for transient field
+        query = queryContext.createQuery("publicbean.transientField='trans*'",
+                PublicAccessBean.class);
+        Assert.assertNotNull(query);
+
+        found = query.find(testList);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(0, found.size());
+
+        // test for private field
+        query = queryContext.createQuery("publicbean.privateField==private",
+                PublicAccessBean.class);
+        Assert.assertNotNull(query);
+
+        found = query.find(testList);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(0, found.size());
+
+        // test for XML Element
+        query = queryContext.createQuery("publicbean.element==elem1",
+                PublicAccessBean.class);
+        Assert.assertNotNull(query);
+
+        found = query.find(testList);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(1, found.size());
+        Assert.assertEquals("John", found.get(0).firstName);
+    }
+
+    @Test
+    public void testFieldAccessType() throws QueryException {
+        // create bean
+        List<FieldAccessBean> testList = new ArrayList<FieldAccessBean>();
+        testList.add(new FieldAccessBean("John", "Scott", "private", 1, "elem1"));
+        testList.add(new FieldAccessBean("Foo", "Bar", "private1", 2, "elem2"));
+
+        QueryContextTest.p(QueryContextTest.toXml(testList.get(0)));
+        QueryContext queryContext = new QueryContextImpl();
+        Assert.assertNotNull(queryContext);
+        // test private field
+        Query<FieldAccessBean> query = queryContext.createQuery(
+                "field.privateField==private", FieldAccessBean.class);
+        Assert.assertNotNull(query);
+
+        List<FieldAccessBean> found = query.find(testList);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(1, found.size());
+        Assert.assertEquals("John", found.get(0).firstName);
+
+        // test public field
+        query = queryContext.createQuery("field.firstName==Foo",
+                FieldAccessBean.class);
+        Assert.assertNotNull(query);
+
+        found = query.find(testList);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(1, found.size());
+        Assert.assertEquals("Foo", found.get(0).firstName);
+
+        // test annotated field
+        query = queryContext.createQuery("field.element==elem2",
+                FieldAccessBean.class);
+        Assert.assertNotNull(query);
+
+        found = query.find(testList);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(1, found.size());
+        Assert.assertEquals("Foo", found.get(0).firstName);
+
+        // test annotated method
+        query = queryContext.createQuery("field.privateGetterField==11",
+                FieldAccessBean.class);
+        Assert.assertNotNull(query);
+
+        found = query.find(testList);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(1, found.size());
+        Assert.assertEquals("John", found.get(0).firstName);
+    }
+
+    @Test
+    public void testPropertyAccessType() throws QueryException {
+        // create bean
+        List<PropertyAccessBean> testList = new ArrayList<PropertyAccessBean>();
+        testList.add(new PropertyAccessBean("John", "Scott", "private", 1, "elem1",
+                "transient1"));
+        testList.add(new PropertyAccessBean("Foo", "Bar", "private1", 2, "elem2",
+                "transient2"));
+
+        QueryContextTest.p(QueryContextTest.toXml(testList.get(0)));
+        QueryContext queryContext = new QueryContextImpl();
+        Assert.assertNotNull(queryContext);
+        // test public getter public field
+        Query<PropertyAccessBean> query = queryContext.createQuery(
+                "property.firstName==John", PropertyAccessBean.class);
+        Assert.assertNotNull(query);
+
+        List<PropertyAccessBean> found = query.find(testList);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(1, found.size());
+        Assert.assertEquals("John", found.get(0).firstName);
+
+        // test public field no getter
+        query = queryContext.createQuery("property.lastName==Bar",
+                PropertyAccessBean.class);
+        Assert.assertNotNull(query);
+
+        found = query.find(testList);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(0, found.size());
+
+        // test annotated field
+        query = queryContext.createQuery("property.element==elem2",
+                PropertyAccessBean.class);
+        Assert.assertNotNull(query);
+
+        found = query.find(testList);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(1, found.size());
+        Assert.assertEquals("Foo", found.get(0).firstName);
+
+        // test annotated method
+        query = queryContext.createQuery("property.field==private",
+                PropertyAccessBean.class);
+        Assert.assertNotNull(query);
+
+        found = query.find(testList);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(1, found.size());
+        Assert.assertEquals("John", found.get(0).firstName);
+
+        // test transient method
+        query = queryContext.createQuery("property.transientField==transient1",
+                PropertyAccessBean.class);
+        Assert.assertNotNull(query);
+
+        found = query.find(testList);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(0, found.size());
+    }
+
+    @Test
+    public void testNoneAccessType() throws QueryException {
+        // create bean
+        List<NoneAccessBean> testList = new ArrayList<NoneAccessBean>();
+        testList.add(new NoneAccessBean("John", "Scott", "private"));
+        testList.add(new NoneAccessBean("Foo", "Bar", "private1"));
+
+        QueryContextTest.p(QueryContextTest.toXml(testList.get(0)));
+        QueryContext queryContext = new QueryContextImpl();
+        Assert.assertNotNull(queryContext);
+        // test annotated field
+        Query<NoneAccessBean> query = queryContext.createQuery(
+                "test.firstName==John", NoneAccessBean.class);
+        Assert.assertNotNull(query);
+
+        List<NoneAccessBean> found = query.find(testList);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(1, found.size());
+        Assert.assertEquals("John", found.get(0).getFirstName());
+        // test unannotated field
+        query = queryContext
+                .createQuery("test.lastName==Bar", NoneAccessBean.class);
+        Assert.assertNotNull(query);
+
+        found = query.find(testList);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(0, found.size());
+        // test annotated method
+        query = queryContext.createQuery("test.testField==private",
+                NoneAccessBean.class);
+        Assert.assertNotNull(query);
+
+        found = query.find(testList);
+        Assert.assertNotNull(found);
+        Assert.assertEquals(1, found.size());
+        Assert.assertEquals("John", found.get(0).getFirstName());
+
+    }
+
+}
+
+// default ( public memeber )
+@XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
+@XmlRootElement(name = "publicbean")
+class PublicAccessBean {
+
+  public String firstName;
+  public String lastName;
+  private String privateField;
+  private int privateGetterField;
+  @XmlTransient
+  public String transientField;
+  @XmlElement(name = "element")
+  private String xmlElem;
+
+  public PublicAccessBean() {
+  }
+
+  public PublicAccessBean(String firstName, String lastName,
+      String privateField, int privateGetterField, String transientField,
+      String xmlElem) {
+    this.firstName = firstName;
+    this.lastName = lastName;
+    this.privateField = privateField;
+    this.privateGetterField = privateGetterField;
+    this.transientField = transientField;
+    this.xmlElem = xmlElem;
+  }
+
+  public int getPrivateGetterField() {
+    return privateGetterField;
+  }
+
+  public void setPrivateGetterField(int field) {
+    this.privateGetterField = field;
+  }
+}
+
+// default ( public memeber )
+@XmlAccessorType(XmlAccessType.FIELD)
+@XmlRootElement(name = "field")
+class FieldAccessBean {
+
+  public String firstName;
+  public String lastName;
+  private String privateField;
+  private int test;
+  @XmlElement(name = "element")
+  private String xmlElem;
+
+  public FieldAccessBean() {
+  }
+
+  public FieldAccessBean(String firstName, String lastName,
+      String privateField, int privateGetterField, String xmlElem) {
+    this.firstName = firstName;
+    this.lastName = lastName;
+    this.privateField = privateField;
+    this.xmlElem = xmlElem;
+    this.test = privateGetterField;
+  }
+
+  public String getPrivateField() {
+    return privateField;
+  }
+
+  @XmlElement(name = "privateGetterField")
+  public int getPrivateGetterField() {
+    return test + 10;
+  }
+}
+
+// default ( public memeber )
+@XmlAccessorType(XmlAccessType.PROPERTY)
+@XmlRootElement(name = "property")
+class PropertyAccessBean {
+
+  public String firstName;
+  public String lastName;
+  private String privateField;
+  private int privateGetterField;
+  @XmlElement(name = "element")
+  private String xmlElem;
+  private String transientField;
+
+  public PropertyAccessBean() {
+  }
+
+  public PropertyAccessBean(String firstName, String lastName,
+      String privateField, int privateGetterField, String xmlElem,
+      String transientField) {
+    this.firstName = firstName;
+    this.lastName = lastName;
+    this.privateField = privateField;
+    this.privateGetterField = privateGetterField;
+    this.xmlElem = xmlElem;
+    this.transientField = transientField;
+  }
+
+  public int getPrivateGetterField() {
+    return privateGetterField;
+  }
+
+  @XmlElement(name = "field")
+  public String getPrivateField() {
+    return privateField;
+  }
+
+  public String getFirstName() {
+    return firstName;
+  }
+
+  @XmlTransient
+  public String getTransientField() {
+    return transientField;
+  }
+}
+
+// default ( public memeber )
+@XmlAccessorType(XmlAccessType.NONE)
+@XmlRootElement(name = "test")
+class NoneAccessBean {
+  @XmlElement
+  private String firstName;
+  public String lastName;
+  private String testField;
+
+  public NoneAccessBean() {
+  }
+
+  public NoneAccessBean(String firstName, String lastName, String testField) {
+    this.firstName = firstName;
+    this.lastName = lastName;
+    this.testField = testField;
+  }
+
+  @XmlElement(name = "testField")
+  public String getTestField() {
+    return testField;
+  }
+
+  public String getFirstName() {
+    return firstName;
+  }
+}
similarity index 61%
rename from opendaylight/md-sal/remoterpc-routingtable/integrationtest/src/test/resources/logback.xml
rename to opendaylight/northbound/commons/src/test/resources/logback.xml
index 6d9dfda9a365f9a08f9d4ba5b7733f2cb6340ba6..97e15deb944b4093fbb3a52e225b4a8e34fa0cae 100644 (file)
@@ -1,11 +1,15 @@
 <configuration scan="true">
+
   <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
     <encoder>
-      <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+      <pattern>%d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n
       </pattern>
     </encoder>
   </appender>
 
+
+  <logger name="org.opendaylight.controller.northbound.commons.query" level="INFO"/>
+
   <root level="error">
     <appender-ref ref="STDOUT" />
   </root>
index a0940e34284833673913654600ef50a81908b9b8..ad315ac008e78e78712fc6bbc7a6f74e8b12b7b3 100644 (file)
               org.opendaylight.controller.northbound.commons,
               org.opendaylight.controller.northbound.commons.exception,
               org.opendaylight.controller.northbound.commons.utils,
+              org.opendaylight.controller.northbound.commons.query,
               org.opendaylight.controller.sal.authorization,
               org.opendaylight.controller.connectionmanager,
               org.opendaylight.controller.sal.connection,
               org.slf4j,
               javax.ws.rs,
+              javax.ws.rs.ext,
               javax.ws.rs.core,
               javax.xml.bind.annotation,
               javax.xml.bind,
index e2c1b32c4bf3ab129604d3e66763b3913f0f03d2..dde3210928689278af7d7f2e3103b0e78c114b47 100644 (file)
@@ -27,6 +27,7 @@ import javax.ws.rs.core.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.SecurityContext;
+import javax.ws.rs.ext.ContextResolver;
 
 import org.codehaus.enunciate.jaxrs.ResponseCode;
 import org.codehaus.enunciate.jaxrs.StatusCodes;
@@ -36,6 +37,7 @@ import org.opendaylight.controller.northbound.commons.exception.NotAcceptableExc
 import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException;
 import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException;
 import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException;
+import org.opendaylight.controller.northbound.commons.query.QueryContext;
 import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils;
 import org.opendaylight.controller.sal.authorization.Privilege;
 import org.opendaylight.controller.sal.connection.ConnectionConstants;
@@ -50,7 +52,14 @@ import org.opendaylight.controller.sal.utils.Status;
 @Path("/")
 public class ConnectionManagerNorthbound {
     private String username;
+    private QueryContext queryContext;
 
+    @Context
+    public void setQueryContext(ContextResolver<QueryContext> queryCtxResolver) {
+      if (queryCtxResolver != null) {
+        queryContext = queryCtxResolver.getContext(QueryContext.class);
+      }
+    }
     @Context
     public void setSecurityContext(SecurityContext context) {
         if (context != null && context.getUserPrincipal() != null) username = context.getUserPrincipal().getName();
@@ -115,7 +124,8 @@ public class ConnectionManagerNorthbound {
         @ResponseCode(code = 406, condition = "Invalid Controller IP Address passed."),
         @ResponseCode(code = 503, condition = "Connection Manager Service not available")})
 
-    public Nodes getNodes(@DefaultValue("") @QueryParam("controller") String controllerAddress) {
+    public Nodes getNodes(@DefaultValue("") @QueryParam("controller") String controllerAddress,
+        @QueryParam("_q") String queryString) {
         if (!NorthboundUtils.isAuthorized(getUserName(), "default", Privilege.READ, this)) {
             throw new UnauthorizedException("User is not authorized to perform this operation on container");
         }
@@ -140,7 +150,12 @@ public class ConnectionManagerNorthbound {
         } else {
             nodeSet = connectionManager.getLocalNodes();
         }
-        return new Nodes(nodeSet);
+        Nodes nodes = new Nodes(nodeSet);
+        if (queryString != null) {
+            queryContext.createQuery(queryString, Nodes.class)
+                .filter(nodes, Node.class);
+        }
+        return nodes;
     }
 
     /**
index 457b1bd6a40c714e8b7dbd7f94d837f07c51d8d4..2e6bb7d40ca0d5245200699822198b8d9ba1c697 100644 (file)
               org.opendaylight.controller.northbound.commons,
               org.opendaylight.controller.northbound.commons.exception,
               org.opendaylight.controller.northbound.commons.utils,
+              org.opendaylight.controller.northbound.commons.query,
               com.sun.jersey.spi.container.servlet,
               javax.ws.rs,
+              javax.ws.rs.ext,
               javax.ws.rs.core,
               javax.xml.bind.annotation,
               javax.xml.bind,
index fe38361cca246465bf514686b0beb872e72dd9f5..754167814d763555ede965c5de8c6ee867f5c9f5 100644 (file)
@@ -21,11 +21,13 @@ 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.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.SecurityContext;
 import javax.ws.rs.core.UriInfo;
+import javax.ws.rs.ext.ContextResolver;
 
 import org.codehaus.enunciate.jaxrs.ResponseCode;
 import org.codehaus.enunciate.jaxrs.StatusCodes;
@@ -41,6 +43,7 @@ import org.opendaylight.controller.northbound.commons.exception.ResourceConflict
 import org.opendaylight.controller.northbound.commons.exception.ResourceForbiddenException;
 import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException;
 import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException;
+import org.opendaylight.controller.northbound.commons.query.QueryContext;
 import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils;
 import org.opendaylight.controller.sal.authorization.Privilege;
 import org.opendaylight.controller.sal.authorization.UserLevel;
@@ -68,6 +71,14 @@ import org.opendaylight.controller.usermanager.IUserManager;
 @Path("/")
 public class ContainerManagerNorthbound {
     private String username;
+    private QueryContext queryContext;
+
+    @Context
+    public void setQueryContext(ContextResolver<QueryContext> queryCtxResolver) {
+      if (queryCtxResolver != null) {
+        queryContext = queryCtxResolver.getContext(QueryContext.class);
+      }
+    }
 
     @Context
     public void setSecurityContext(SecurityContext context) {
@@ -172,13 +183,18 @@ public class ContainerManagerNorthbound {
     @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"),
             @ResponseCode(code = 401, condition = "User is not authorized to perform this operation"),
             @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
-    public ContainerConfigs viewAllContainers() {
+    public ContainerConfigs viewAllContainers(@QueryParam("_q") String queryString) {
 
         handleNetworkAuthorization(getUserName());
 
         IContainerManager containerManager = getContainerManager();
-
-        return new ContainerConfigs(containerManager.getContainerConfigList());
+        ContainerConfigs result = new ContainerConfigs(
+                containerManager.getContainerConfigList());
+        if (queryString != null) {
+            queryContext.createQuery(queryString, ContainerConfigs.class)
+                .filter(result, ContainerConfig.class);
+        }
+        return result;
     }
 
     /**
@@ -481,7 +497,8 @@ public class ContainerManagerNorthbound {
     @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"),
             @ResponseCode(code = 404, condition = "The container is not found"),
             @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
-    public FlowSpecConfigs viewContainerFlowSpecs(@PathParam(value = "container") String container) {
+    public FlowSpecConfigs viewContainerFlowSpecs(@PathParam(value = "container") String container,
+        @QueryParam("_q") String queryString) {
 
         handleContainerAuthorization(container, getUserName());
         handleForbiddenOnDefault(container);
@@ -489,8 +506,13 @@ public class ContainerManagerNorthbound {
         handleContainerNotExists(container);
 
         IContainerManager containerManager = getContainerManager();
-
-        return new FlowSpecConfigs(containerManager.getContainerFlows(container));
+        FlowSpecConfigs result = new FlowSpecConfigs(
+                containerManager.getContainerFlows(container));
+        if (queryString != null) {
+            queryContext.createQuery(queryString, FlowSpecConfigs.class)
+                .filter(result, ContainerFlowConfig.class);
+        }
+        return result;
     }
 
     /**
index b9d2200180dbd858c17624dbaa7b2bd8e0c97038..db3d543a69d9d948e77f67fe8bd68a76fb797fd7 100644 (file)
@@ -11,8 +11,11 @@ package org.opendaylight.controller.containermanager.northbound;
 
 import java.util.HashSet;
 import java.util.Set;
+
 import javax.ws.rs.core.Application;
 
+import org.opendaylight.controller.northbound.commons.query.QueryContextProvider;
+
 import com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider;
 
 /**
@@ -28,6 +31,7 @@ public class ContainerManagerNorthboundRSApplication extends Application {
         Set<Class<?>> classes = new HashSet<Class<?>>();
         classes.add(ContainerManagerNorthbound.class);
         classes.add(JacksonJaxbJsonProvider.class);
+        classes.add(QueryContextProvider.class);
         return classes;
     }
 }
index 07d34cb6d4ee7e20ff48c387d8275687837c445e..89d2b99cadb7b89409a11fb600638edd8897ed2d 100644 (file)
               org.opendaylight.controller.northbound.commons,
               org.opendaylight.controller.northbound.commons.exception,
               org.opendaylight.controller.northbound.commons.utils,
+              org.opendaylight.controller.northbound.commons.query,
               org.opendaylight.controller.sal.authorization,
               javax.ws.rs,
+              javax.ws.rs.ext,
               javax.ws.rs.core,
               javax.xml.bind.annotation,
               javax.xml.bind,
index 003f8b3b95df37b465ad04caf487181614511ddc..aaf93d1f4bacb0c73ace34595121f6641ce33323 100644 (file)
@@ -25,6 +25,7 @@ import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.SecurityContext;
 import javax.ws.rs.core.UriInfo;
+import javax.ws.rs.ext.ContextResolver;
 
 import org.codehaus.enunciate.jaxrs.ResponseCode;
 import org.codehaus.enunciate.jaxrs.StatusCodes;
@@ -36,6 +37,7 @@ import org.opendaylight.controller.northbound.commons.exception.BadRequestExcept
 import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException;
 import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException;
 import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException;
+import org.opendaylight.controller.northbound.commons.query.QueryContext;
 import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils;
 import org.opendaylight.controller.sal.authorization.Privilege;
 import org.opendaylight.controller.sal.core.Property;
@@ -55,6 +57,14 @@ import org.opendaylight.controller.switchmanager.ISwitchManager;
 public class ControllerManagerNorthbound {
 
     private String username;
+    private QueryContext queryContext;
+
+    @Context
+    public void setQueryContext(ContextResolver<QueryContext> queryCtxResolver) {
+      if (queryCtxResolver != null) {
+        queryContext = queryCtxResolver.getContext(QueryContext.class);
+      }
+    }
 
     @Context
     public void setSecurityContext(SecurityContext context) {
@@ -122,7 +132,8 @@ public class ControllerManagerNorthbound {
             @ResponseCode(code = 404, condition = "The containerName or property is not found"),
             @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
     public ControllerProperties getControllerProperties(@PathParam("containerName") String containerName,
-            @QueryParam("propertyName") String propertyName) {
+            @QueryParam("propertyName") String propertyName,
+            @QueryParam("_q") String queryString) {
 
         if (!isValidContainer(containerName)) {
             throw new ResourceNotFoundException("Container " + containerName + " does not exist.");
@@ -147,8 +158,12 @@ public class ControllerManagerNorthbound {
             throw new ResourceNotFoundException("Unable to find property with name: " + propertyName);
         }
         properties.add(property);
-
-        return new ControllerProperties(properties);
+        ControllerProperties result = new ControllerProperties(properties);
+        if (queryString != null) {
+            queryContext.createQuery(queryString, ControllerProperties.class)
+                .filter(result, Property.class);
+        }
+        return result;
 
     }
 
index 205b68a91c9859055d51aa0d043b6ce42abd6dd9..43797f5c6558d84cca3f256d6f2bbdcf4f380407 100644 (file)
               org.opendaylight.controller.northbound.commons,
               org.opendaylight.controller.northbound.commons.exception,
               org.opendaylight.controller.northbound.commons.utils,
+              org.opendaylight.controller.northbound.commons.query,
               org.opendaylight.controller.sal.authorization,
               org.opendaylight.controller.usermanager,
               com.sun.jersey.spi.container.servlet,
               org.apache.catalina.filters,
               javax.ws.rs,
+              javax.ws.rs.ext,
               javax.ws.rs.core,
               javax.xml.bind.annotation,
               javax.xml.bind,
index 4928ddef3b0296b8525531791dfe4272064dfaa1..42bd59ea4577ff5c6d40b3ad4e8efaa976c900f5 100644 (file)
@@ -19,10 +19,12 @@ 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.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.SecurityContext;
+import javax.ws.rs.ext.ContextResolver;
 
 import org.codehaus.enunciate.jaxrs.ResponseCode;
 import org.codehaus.enunciate.jaxrs.StatusCodes;
@@ -37,6 +39,7 @@ import org.opendaylight.controller.northbound.commons.exception.NotAcceptableExc
 import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException;
 import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException;
 import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException;
+import org.opendaylight.controller.northbound.commons.query.QueryContext;
 import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils;
 import org.opendaylight.controller.sal.authorization.Privilege;
 import org.opendaylight.controller.sal.core.Node;
@@ -62,6 +65,14 @@ public class FlowProgrammerNorthbound {
 
     private String username;
 
+    private QueryContext queryContext;
+    @Context
+    public void setQueryContext(ContextResolver<QueryContext> queryCtxResolver) {
+      if (queryCtxResolver != null) {
+        queryContext = queryCtxResolver.getContext(QueryContext.class);
+      }
+    }
+
     @Context
     public void setSecurityContext(SecurityContext context) {
         if (context != null && context.getUserPrincipal() != null) {
@@ -194,15 +205,21 @@ public class FlowProgrammerNorthbound {
     @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"),
         @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
         @ResponseCode(code = 404, condition = "The containerName is not found"),
-        @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
-    public FlowConfigs getStaticFlows(@PathParam("containerName") String containerName) {
+        @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable"),
+        @ResponseCode(code = 400, condition = "Incorrect query syntex")})
+    public FlowConfigs getStaticFlows(@PathParam("containerName") String containerName,
+                   @QueryParam("_q") String queryString) {
         if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
             throw new UnauthorizedException("User is not authorized to perform this operation on container "
                     + containerName);
         }
 
-        List<FlowConfig> flowConfigs = getStaticFlowsInternal(containerName, null);
-        return new FlowConfigs(flowConfigs);
+        FlowConfigs result = new FlowConfigs(getStaticFlowsInternal(containerName, null));
+        if (queryString != null) {
+            queryContext.createQuery(queryString, FlowConfigs.class)
+                .filter(result, FlowConfig.class);
+        }
+        return result;
     }
 
     /**
@@ -272,7 +289,8 @@ public class FlowProgrammerNorthbound {
         @ResponseCode(code = 404, condition = "The containerName or nodeId is not found"),
         @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
     public FlowConfigs getStaticFlows(@PathParam("containerName") String containerName,
-            @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId) {
+            @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId,
+            @QueryParam("_q") String queryString) {
         if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
             throw new UnauthorizedException("User is not authorized to perform this operation on container "
                     + containerName);
@@ -281,8 +299,12 @@ public class FlowProgrammerNorthbound {
         if (node == null) {
             throw new ResourceNotFoundException(nodeId + " : " + RestMessages.NONODE.toString());
         }
-        List<FlowConfig> flows = getStaticFlowsInternal(containerName, node);
-        return new FlowConfigs(flows);
+        FlowConfigs flows = new FlowConfigs(getStaticFlowsInternal(containerName, node));
+        if (queryString != null) {
+            queryContext.createQuery(queryString, FlowConfigs.class)
+                .filter(flows, FlowConfig.class);
+        }
+        return flows;
     }
 
     /**
index bf1b082cfef7eecb48f4c8861eebbd0b97b74e39..c8415f8b4f77cc63496d3a8abaa5abe0810da9b4 100644 (file)
               com.sun.jersey.spi.container.servlet,
               org.opendaylight.controller.northbound.commons,
               org.opendaylight.controller.northbound.commons.exception,
+              org.opendaylight.controller.northbound.commons.query,
               org.opendaylight.controller.northbound.commons.utils,
               org.opendaylight.controller.sal.authorization,
               org.opendaylight.controller.sal.packet.address,
               javax.ws.rs,
               javax.ws.rs.core,
+              javax.ws.rs.ext,
               javax.xml.bind.annotation,
               javax.xml.bind,
               org.slf4j,
index 74c13d11f129943ba45e449411adfbc9f09d41e3..d7579c82e10bdd378dd603bfee9c4fde1d0ad414 100644 (file)
@@ -21,11 +21,13 @@ 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.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.SecurityContext;
 import javax.ws.rs.core.UriInfo;
+import javax.ws.rs.ext.ContextResolver;
 
 import org.codehaus.enunciate.jaxrs.ResponseCode;
 import org.codehaus.enunciate.jaxrs.StatusCodes;
@@ -39,6 +41,7 @@ import org.opendaylight.controller.northbound.commons.exception.ResourceConflict
 import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException;
 import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException;
 import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException;
+import org.opendaylight.controller.northbound.commons.query.QueryContext;
 import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils;
 import org.opendaylight.controller.sal.authorization.Privilege;
 import org.opendaylight.controller.sal.core.Node;
@@ -69,6 +72,14 @@ import org.opendaylight.controller.switchmanager.ISwitchManager;
 public class HostTrackerNorthbound {
 
     private String username;
+    private QueryContext queryContext;
+
+    @Context
+    public void setQueryContext(ContextResolver<QueryContext> queryCtxResolver) {
+      if (queryCtxResolver != null) {
+        queryContext = queryCtxResolver.getContext(QueryContext.class);
+      }
+    }
 
     @Context
     public void setSecurityContext(SecurityContext context) {
@@ -107,7 +118,7 @@ public class HostTrackerNorthbound {
         return hostTracker;
     }
 
-    private Hosts convertHosts(Set<HostNodeConnector> hostNodeConnectors) {
+    private Set<HostConfig> convertHosts(Set<HostNodeConnector> hostNodeConnectors) {
         if(hostNodeConnectors == null) {
             return null;
         }
@@ -115,7 +126,7 @@ public class HostTrackerNorthbound {
         for(HostNodeConnector hnc : hostNodeConnectors) {
             hosts.add(HostConfig.convert(hnc));
         }
-        return new Hosts(hosts);
+        return hosts;
     }
 
     /**
@@ -194,14 +205,20 @@ public class HostTrackerNorthbound {
             @ResponseCode(code = 200, condition = "Operation successful"),
             @ResponseCode(code = 404, condition = "The containerName is not found"),
             @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
-    public Hosts getActiveHosts(@PathParam("containerName") String containerName) {
+    public Hosts getActiveHosts(@PathParam("containerName") String containerName,
+        @QueryParam("_q") String queryString) {
 
         if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
             throw new UnauthorizedException("User is not authorized to perform this operation on container "
                     + containerName);
         }
         IfIptoHost hostTracker = getIfIpToHostService(containerName);
-        return convertHosts(hostTracker.getAllHosts());
+        Hosts hosts = new Hosts(convertHosts(hostTracker.getAllHosts()));
+        if (queryString != null) {
+            queryContext.createQuery(queryString, Hosts.class)
+                .filter(hosts, HostConfig.class);
+        }
+        return hosts;
     }
 
     /**
@@ -281,13 +298,19 @@ public class HostTrackerNorthbound {
             @ResponseCode(code = 404, condition = "The containerName is not found"),
             @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
     public Hosts getInactiveHosts(
-            @PathParam("containerName") String containerName) {
+            @PathParam("containerName") String containerName,
+            @QueryParam("_q") String queryString) {
         if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
             throw new UnauthorizedException("User is not authorized to perform this operation on container "
                     + containerName);
         }
         IfIptoHost hostTracker = getIfIpToHostService(containerName);
-        return convertHosts(hostTracker.getInactiveStaticHosts());
+        Hosts hosts = new Hosts(convertHosts(hostTracker.getInactiveStaticHosts()));
+        if (queryString != null) {
+            queryContext.createQuery(queryString, Hosts.class)
+                .filter(hosts, HostConfig.class);
+        }
+        return hosts;
     }
 
     /**
diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/INeutronRequest.java b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/INeutronRequest.java
new file mode 100644 (file)
index 0000000..8e0ff5c
--- /dev/null
@@ -0,0 +1,21 @@
+/*
+ * 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
+ *
+ *  Authors : Dave Tucker
+ */
+
+package org.opendaylight.controller.networkconfig.neutron.northbound;
+
+import org.opendaylight.controller.networkconfig.neutron.INeutronObject;
+
+import java.util.List;
+
+public interface INeutronRequest<T extends INeutronObject> {
+    public T getSingleton();
+    public boolean isSingleton();
+    public List<T> getBulk();
+}
index cebd3c267dd1a1ad2d3b345f2f97d498046631b0..a4c113c2c1803081409e61c4132770482d51f3c0 100644 (file)
@@ -19,7 +19,7 @@ import org.opendaylight.controller.networkconfig.neutron.NeutronNetwork;
 
 @XmlRootElement
 @XmlAccessorType(XmlAccessType.NONE)
-public class NeutronNetworkRequest {
+public class NeutronNetworkRequest implements INeutronRequest {
     // See OpenStack Network API v2.0 Reference for description of
     // annotated attributes
 
@@ -29,9 +29,18 @@ public class NeutronNetworkRequest {
     @XmlElement(name="networks")
     List<NeutronNetwork> bulkRequest;
 
+    @XmlElement(name="networks_links")
+    List<NeutronPageLink> links;
+
     NeutronNetworkRequest() {
     }
 
+    NeutronNetworkRequest(List<NeutronNetwork> bulkRequest, List<NeutronPageLink> links) {
+        this.bulkRequest = bulkRequest;
+        this.links = links;
+        this.singletonNetwork = null;
+    }
+
     NeutronNetworkRequest(List<NeutronNetwork> bulk) {
         bulkRequest = bulk;
         singletonNetwork = null;
index 52c3337e40047fb844352fd9dcc0b6c596fcb8d0..9de5aef5f421eb2436ac73a6dff63e24efcf4c64 100644 (file)
@@ -9,8 +9,6 @@
 package org.opendaylight.controller.networkconfig.neutron.northbound;
 
 import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
@@ -33,6 +31,7 @@ import javax.ws.rs.core.Response;
 import org.codehaus.enunciate.jaxrs.ResponseCode;
 import org.codehaus.enunciate.jaxrs.StatusCodes;
 import org.codehaus.enunciate.jaxrs.TypeHint;
+
 import org.opendaylight.controller.networkconfig.neutron.INeutronNetworkAware;
 import org.opendaylight.controller.networkconfig.neutron.INeutronNetworkCRUD;
 import org.opendaylight.controller.networkconfig.neutron.NeutronCRUDInterfaces;
@@ -95,13 +94,13 @@ public class NeutronNetworksNorthbound {
             @QueryParam("provider_network_type") String queryProviderNetworkType,
             @QueryParam("provider_physical_network") String queryProviderPhysicalNetwork,
             @QueryParam("provider_segmentation_id") String queryProviderSegmentationID,
-            // pagination
+            // linkTitle
             @QueryParam("limit") Integer limit,
             @QueryParam("marker") String marker,
             @DefaultValue("false") @QueryParam("page_reverse") Boolean pageReverse
             // sorting not supported
             ) {
-        INeutronNetworkCRUD networkInterface = NeutronCRUDInterfaces.getINeutronNetworkCRUD( this);
+        INeutronNetworkCRUD networkInterface = NeutronCRUDInterfaces.getINeutronNetworkCRUD(this);
         if (networkInterface == null) {
             throw new ServiceUnavailableException("Network CRUD Interface "
                     + RestMessages.SERVICEUNAVAILABLE.toString());
@@ -139,89 +138,11 @@ public class NeutronNetworksNorthbound {
             }
         }
 
-        Comparator<NeutronNetwork> neutronNetworkComparator = new Comparator<NeutronNetwork>() {
-            @Override
-            public int compare(NeutronNetwork o1, NeutronNetwork o2) {
-                return o1.getID().compareTo(o2.getID());
-            }
-        };
-
-        Collections.sort(ans, neutronNetworkComparator);
-
         if (limit != null && ans.size() > 1) {
-            List<NeutronPageLink> links = new ArrayList<>();
-            Integer startPos = null;
-            String startMarker;
-            String endMarker;
-            Boolean firstPage = false;
-            Boolean lastPage = false;
-
-            if (marker == null) {
-                startPos = 0;
-            }
-
-            else {
-
-                NeutronNetwork markerNetwork = new NeutronNetwork();
-                markerNetwork.setNetworkUUID(marker);
-
-                startPos = Collections.binarySearch(ans, markerNetwork, neutronNetworkComparator);
-
-                if (!pageReverse){
-                    startPos = startPos + 1;
-                }
-                else {
-                    startPos = startPos - limit;
-                }
-
-            }
-
-            if (startPos == null) {
-                throw new ResourceNotFoundException("UUID for marker:" + marker + " could not be found");
-            }
-
-            if (startPos == 0){
-                firstPage = true;
-            }
-
-            if (startPos + limit >= ans.size()) {
-                ans = ans.subList(startPos, ans.size());
-                startMarker = ans.get(0).getID();
-                endMarker = ans.get(ans.size() - 1).getID();
-                lastPage = true;
-            }
-            else if (startPos < 0) {
-                if (startPos + limit > 0) {
-                    ans = ans.subList(0, startPos + limit);
-                    startMarker = ans.get(0).getID();
-                    endMarker = ans.get(ans.size() - 1).getID();
-                    firstPage = true;
-                }
-                else {
-                    throw new BadRequestException("Requested page is out of bounds. Please check the supplied limit and marker");
-                }
-            }
-            else {
-                ans = ans.subList(startPos, startPos + limit);
-                startMarker = ans.get(0).getID();
-                endMarker = ans.get(limit-1).getID();
-            }
-
-            if (!lastPage) {
-                NeutronPageLink next = new NeutronPageLink();
-                next.setRef("next");
-                next.setHref(uriInfo.getAbsolutePath().toString() + "?limit=" + limit.toString() + "&marker=" + endMarker);
-                links.add(next);
-            }
-
-            if (!firstPage) {
-                NeutronPageLink previous = new NeutronPageLink();
-                previous.setRef("previous");
-                previous.setHref(uriInfo.getAbsolutePath().toString() + "?limit=" + limit.toString() + "&marker=" + startMarker + "&page_reverse=True");
-                links.add(previous);
-            }
-
-            return Response.status(200).entity(new PaginatedNeutronNetworkRequest(ans, links)).build();
+            // Return a paginated request
+            NeutronNetworkRequest request = (NeutronNetworkRequest) PaginatedRequestFactory.createRequest(limit,
+                    marker, pageReverse, uriInfo, ans, NeutronNetwork.class);
+            return Response.status(200).entity(request).build();
         }
 
     return Response.status(200).entity(new NeutronNetworkRequest(ans)).build();
index 9b3399d9a8bfe72266843b0d4d8c34d6b163ef52..12b58aa2abc54e30799fd0458a4e126b9185124a 100644 (file)
@@ -19,7 +19,7 @@ import org.opendaylight.controller.networkconfig.neutron.NeutronPort;
 
 @XmlRootElement
 @XmlAccessorType(XmlAccessType.NONE)
-public class NeutronPortRequest {
+public class NeutronPortRequest implements INeutronRequest {
     // See OpenStack Network API v2.0 Reference for description of
     // annotated attributes
 
@@ -29,9 +29,18 @@ public class NeutronPortRequest {
     @XmlElement(name="ports")
     List<NeutronPort> bulkRequest;
 
+    @XmlElement(name="ports_links")
+    List<NeutronPageLink> links;
+
     NeutronPortRequest() {
     }
 
+    public NeutronPortRequest(List<NeutronPort> bulkRequest, List<NeutronPageLink> links) {
+        this.bulkRequest = bulkRequest;
+        this.links = links;
+        this.singletonPort = null;
+    }
+
     NeutronPortRequest(List<NeutronPort> bulk) {
         bulkRequest = bulk;
         singletonPort = null;
index 1a2512fde3c3fd6c689a872f9ee148bba4a67521..5451fbf3e129e4be88addabcc7816e308c2cb2b7 100644 (file)
@@ -15,6 +15,7 @@ import java.util.List;
 
 import javax.ws.rs.Consumes;
 import javax.ws.rs.DELETE;
+import javax.ws.rs.DefaultValue;
 import javax.ws.rs.GET;
 import javax.ws.rs.POST;
 import javax.ws.rs.PUT;
@@ -22,8 +23,10 @@ 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.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
 
 import org.codehaus.enunciate.jaxrs.ResponseCode;
 import org.codehaus.enunciate.jaxrs.StatusCodes;
@@ -69,6 +72,9 @@ public class NeutronPortsNorthbound {
         return o.extractFields(fields);
     }
 
+    @Context
+    UriInfo uriInfo;
+
     /**
      * Returns a list of all Ports */
 
@@ -92,10 +98,10 @@ public class NeutronPortsNorthbound {
             @QueryParam("device_id") String queryDeviceID,
             @QueryParam("device_owner") String queryDeviceOwner,
             @QueryParam("tenant_id") String queryTenantID,
-            // pagination
-            @QueryParam("limit") String limit,
+            // linkTitle
+            @QueryParam("limit") Integer limit,
             @QueryParam("marker") String marker,
-            @QueryParam("page_reverse") String pageReverse
+            @DefaultValue("false") @QueryParam("page_reverse") Boolean pageReverse
             // sorting not supported
             ) {
         INeutronPortCRUD portInterface = NeutronCRUDInterfaces.getINeutronPortCRUD(this);
@@ -124,7 +130,14 @@ public class NeutronPortsNorthbound {
                 }
             }
         }
-        //TODO: apply pagination to results
+
+        if (limit != null && ans.size() > 1) {
+            // Return a paginated request
+            NeutronPortRequest request = (NeutronPortRequest) PaginatedRequestFactory.createRequest(limit,
+                    marker, pageReverse, uriInfo, ans, NeutronPort.class);
+            return Response.status(200).entity(request).build();
+        }
+
         return Response.status(200).entity(
                 new NeutronPortRequest(ans)).build();
     }
index aed9db58bd34c3255c54830c8b76957da6d4de5c..57a724c1cc60936b3a15ed80ba0c1b9bc6d53288 100644 (file)
@@ -20,7 +20,7 @@ import org.opendaylight.controller.networkconfig.neutron.NeutronSubnet;
 @XmlRootElement
 @XmlAccessorType(XmlAccessType.NONE)
 
-public class NeutronSubnetRequest {
+public class NeutronSubnetRequest implements INeutronRequest {
     // See OpenStack Network API v2.0 Reference for description of
     // annotated attributes
 
@@ -30,16 +30,28 @@ public class NeutronSubnetRequest {
     @XmlElement(name="subnets")
     List<NeutronSubnet> bulkRequest;
 
+    @XmlElement(name="subnets_links")
+    List<NeutronPageLink> links;
+
     NeutronSubnetRequest() {
     }
 
+    public NeutronSubnetRequest(List<NeutronSubnet> bulkRequest, List<NeutronPageLink> links) {
+        this.bulkRequest = bulkRequest;
+        this.links = links;
+        this.singletonSubnet = null;
+    }
+
     NeutronSubnetRequest(List<NeutronSubnet> bulk) {
         bulkRequest = bulk;
         singletonSubnet = null;
+        links = null;
     }
 
     NeutronSubnetRequest(NeutronSubnet subnet) {
         singletonSubnet = subnet;
+        bulkRequest = null;
+        links = null;
     }
 
     public NeutronSubnet getSingleton() {
index f397eb3a97b0630002b3fc1b70901a1a25cf0609..8f20269603b1ed1802fc04812974125016c1811b 100644 (file)
@@ -13,8 +13,10 @@ import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
+
 import javax.ws.rs.Consumes;
 import javax.ws.rs.DELETE;
+import javax.ws.rs.DefaultValue;
 import javax.ws.rs.GET;
 import javax.ws.rs.POST;
 import javax.ws.rs.PUT;
@@ -22,8 +24,10 @@ 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.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
 
 import org.codehaus.enunciate.jaxrs.ResponseCode;
 import org.codehaus.enunciate.jaxrs.StatusCodes;
@@ -65,6 +69,8 @@ public class NeutronSubnetsNorthbound {
         return o.extractFields(fields);
     }
 
+    @Context
+    UriInfo uriInfo;
 
     /**
      * Returns a list of all Subnets */
@@ -89,13 +95,13 @@ public class NeutronSubnetsNorthbound {
             @QueryParam("tenant_id") String queryTenantID,
             @QueryParam("ipv6_address_mode") String queryIpV6AddressMode,
             @QueryParam("ipv6_ra_mode") String queryIpV6RaMode,
-            // pagination
-            @QueryParam("limit") String limit,
+            // linkTitle
+            @QueryParam("limit") Integer limit,
             @QueryParam("marker") String marker,
-            @QueryParam("page_reverse") String pageReverse
+            @DefaultValue("false") @QueryParam("page_reverse") Boolean pageReverse
             // sorting not supported
             ) {
-        INeutronSubnetCRUD subnetInterface = NeutronCRUDInterfaces.getINeutronSubnetCRUD( this);
+        INeutronSubnetCRUD subnetInterface = NeutronCRUDInterfaces.getINeutronSubnetCRUD(this);
         if (subnetInterface == null) {
             throw new ServiceUnavailableException("Subnet CRUD Interface "
                     + RestMessages.SERVICEUNAVAILABLE.toString());
@@ -122,7 +128,14 @@ public class NeutronSubnetsNorthbound {
                 }
             }
         }
-        //TODO: apply pagination to results
+
+        if (limit != null && ans.size() > 1) {
+            // Return a paginated request
+            NeutronSubnetRequest request = (NeutronSubnetRequest) PaginatedRequestFactory.createRequest(limit,
+                    marker, pageReverse, uriInfo, ans, NeutronSubnet.class);
+            return Response.status(200).entity(request).build();
+        }
+
         return Response.status(200).entity(
                 new NeutronSubnetRequest(ans)).build();
     }
diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/PaginatedNeutronNetworkRequest.java b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/PaginatedNeutronNetworkRequest.java
deleted file mode 100644 (file)
index c050661..0000000
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (C) 2014 Hewlett-Packard Development Company L.P
- *
- * 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
- *
- * Authors : Dave Tucker
- */
-
-package org.opendaylight.controller.networkconfig.neutron.northbound;
-
-import org.opendaylight.controller.networkconfig.neutron.NeutronNetwork;
-
-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 PaginatedNeutronNetworkRequest {
-
-    @XmlElement (name="networks")
-    List<NeutronNetwork> networks;
-
-    @XmlElement (name="network_links")
-    List<NeutronPageLink> networkLinks;
-
-    public PaginatedNeutronNetworkRequest() {
-    }
-
-    public PaginatedNeutronNetworkRequest(List<NeutronNetwork> networks, List<NeutronPageLink> networkLinks) {
-        this.networks = networks;
-        this.networkLinks = networkLinks;
-    }
-
-    public List<NeutronNetwork> getNetworks() {
-        return networks;
-    }
-
-    public void setNetworks(List<NeutronNetwork> networks) {
-        this.networks = networks;
-    }
-
-    public List<NeutronPageLink> getNetworkLinks() {
-        return networkLinks;
-    }
-
-    public void setNetworkLinks(List<NeutronPageLink> networkLinks) {
-        this.networkLinks = networkLinks;
-    }
-}
diff --git a/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/PaginatedRequestFactory.java b/opendaylight/northbound/networkconfiguration/neutron/src/main/java/org/opendaylight/controller/networkconfig/neutron/northbound/PaginatedRequestFactory.java
new file mode 100644 (file)
index 0000000..8f05e76
--- /dev/null
@@ -0,0 +1,154 @@
+/*
+ * 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
+ *
+ *  Authors : Dave Tucker
+ */
+
+package org.opendaylight.controller.networkconfig.neutron.northbound;
+
+import org.opendaylight.controller.networkconfig.neutron.INeutronObject;
+import org.opendaylight.controller.networkconfig.neutron.NeutronNetwork;
+import org.opendaylight.controller.networkconfig.neutron.NeutronPort;
+import org.opendaylight.controller.networkconfig.neutron.NeutronSubnet;
+import org.opendaylight.controller.northbound.commons.exception.BadRequestException;
+import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException;
+
+import javax.ws.rs.core.UriInfo;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.List;
+
+public class PaginatedRequestFactory {
+
+    public static class PaginationResults<T extends INeutronObject> {
+        List<T> collection;
+        List<NeutronPageLink> links;
+
+        public PaginationResults(List<T> collection, List<NeutronPageLink> links) {
+            this.collection = collection;
+            this.links = links;
+        }
+    }
+
+    public static <T extends INeutronObject> INeutronRequest createRequest(Integer limit, String marker,
+                                                                           Boolean pageReverse,
+                                                                           UriInfo uriInfo,
+                                                                           List<T> collection,
+                                                                           Class<T> clazz) {
+        PaginationResults results = _paginate(limit, marker, pageReverse, uriInfo, collection);
+
+        if (clazz.equals(NeutronNetwork.class)){
+            return new NeutronNetworkRequest(results.collection, results.links);
+        }
+        if (clazz.equals(NeutronSubnet.class)){
+            return new NeutronSubnetRequest(results.collection, results.links);
+        }
+        if (clazz.equals(NeutronPort.class)){
+            return new NeutronPortRequest(results.collection, results.links);
+        }
+        return null;
+    }
+
+    private static <T extends INeutronObject> PaginationResults _paginate(Integer limit, String marker, Boolean pageReverse, UriInfo uriInfo, List<T> collection) {
+        List<NeutronPageLink> links = new ArrayList<>();
+        Integer startPos = null;
+        String startMarker;
+        String endMarker;
+        Boolean firstPage = false;
+        Boolean lastPage = false;
+
+        Comparator<INeutronObject> neutronObjectComparator = new Comparator<INeutronObject>() {
+            @Override
+            public int compare(INeutronObject o1, INeutronObject o2) {
+                return o1.getID().compareTo(o2.getID());
+            }
+        };
+
+        Collections.sort(collection, neutronObjectComparator);
+
+        if (marker == null) {
+            startPos = 0;
+        }
+
+        else {
+
+            class MarkerObject implements INeutronObject {
+                private String id;
+
+                public String getID() {
+                    return id;
+                }
+
+                public void setID(String id) {
+                    this.id = id;
+                }
+            }
+
+            INeutronObject markerObject = new MarkerObject();
+
+            markerObject.setID(marker);
+
+            startPos = Collections.binarySearch(collection, markerObject, neutronObjectComparator);
+
+            if (!pageReverse){
+                startPos = startPos + 1;
+            }
+            else {
+                startPos = startPos - limit;
+            }
+
+        }
+
+        if (startPos == null) {
+            throw new ResourceNotFoundException("UUID for marker:" + marker + " could not be found");
+        }
+
+        if (startPos == 0){
+            firstPage = true;
+        }
+
+        if (startPos + limit >= collection.size()) {
+            collection = collection.subList(startPos, collection.size());
+            startMarker = collection.get(0).getID();
+            endMarker = collection.get(collection.size() - 1).getID();
+            lastPage = true;
+        }
+        else if (startPos < 0) {
+            if (startPos + limit > 0) {
+                collection = collection.subList(0, startPos + limit);
+                startMarker = collection.get(0).getID();
+                endMarker = collection.get(collection.size() - 1).getID();
+                firstPage = true;
+            }
+            else {
+                throw new BadRequestException("Requested page is out of bounds. Please check the supplied limit and marker");
+            }
+        }
+        else {
+            collection = collection.subList(startPos, startPos + limit);
+            startMarker = collection.get(0).getID();
+            endMarker = collection.get(limit-1).getID();
+        }
+
+        if (!lastPage) {
+            NeutronPageLink next = new NeutronPageLink();
+            next.setRef("next");
+            next.setHref(uriInfo.getAbsolutePath().toString() + "?limit=" + limit.toString() + "&marker=" + endMarker);
+            links.add(next);
+        }
+
+        if (!firstPage) {
+            NeutronPageLink previous = new NeutronPageLink();
+            previous.setRef("previous");
+            previous.setHref(uriInfo.getAbsolutePath().toString() + "?limit=" + limit.toString() + "&marker=" + startMarker + "&page_reverse=True");
+            links.add(previous);
+        }
+
+        return new PaginationResults(collection, links);
+    }
+}
index dd2a2e6223bb5ab19d776fa71093ad70e89d2bc3..83f8191e025e1c4d23d3bd8673f2ed0046ff9408 100644 (file)
               org.opendaylight.controller.northbound.commons,
               org.opendaylight.controller.northbound.commons.exception,
               org.opendaylight.controller.northbound.commons.utils,
+              org.opendaylight.controller.northbound.commons.query,
               org.opendaylight.controller.sal.authorization,
               org.slf4j,
               javax.ws.rs,
+              javax.ws.rs.ext,
               javax.ws.rs.core,
               javax.xml.bind.annotation,
               javax.xml.bind,
index e765af524d5a6e215531bc7682a644b3d277339c..20f6cb40a56cb812fa5370a5dd01cc6bf2ef85e8 100644 (file)
@@ -19,11 +19,13 @@ 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.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.SecurityContext;
 import javax.ws.rs.core.UriInfo;
+import javax.ws.rs.ext.ContextResolver;
 
 import org.codehaus.enunciate.jaxrs.ResponseCode;
 import org.codehaus.enunciate.jaxrs.StatusCodes;
@@ -37,6 +39,7 @@ import org.opendaylight.controller.northbound.commons.exception.NotAcceptableExc
 import org.opendaylight.controller.northbound.commons.exception.ResourceConflictException;
 import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException;
 import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException;
+import org.opendaylight.controller.northbound.commons.query.QueryContext;
 import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils;
 import org.opendaylight.controller.sal.authorization.Privilege;
 import org.opendaylight.controller.sal.utils.GlobalConstants;
@@ -74,6 +77,14 @@ import org.opendaylight.controller.sal.utils.Status;
 public class StaticRoutingNorthbound {
 
     private String username;
+    private QueryContext queryContext;
+
+    @Context
+    public void setQueryContext(ContextResolver<QueryContext> queryCtxResolver) {
+      if (queryCtxResolver != null) {
+        queryContext = queryCtxResolver.getContext(QueryContext.class);
+      }
+    }
 
     @Context
     public void setSecurityContext(SecurityContext context) {
@@ -148,7 +159,8 @@ public class StaticRoutingNorthbound {
             @ResponseCode(code = 200, condition = "Operation successful"),
             @ResponseCode(code = 404, condition = "The containerName passed was not found") })
     public StaticRoutes getStaticRoutes(
-            @PathParam("containerName") String containerName) {
+            @PathParam("containerName") String containerName,
+            @QueryParam("_q") String queryString) {
 
         if(!NorthboundUtils.isAuthorized(getUserName(), containerName,
                 Privilege.WRITE, this)){
@@ -156,7 +168,12 @@ public class StaticRoutingNorthbound {
                 UnauthorizedException("User is not authorized to perform this operation on container "
                             + containerName);
         }
-        return new StaticRoutes(getStaticRoutesInternal(containerName));
+        StaticRoutes result = new StaticRoutes(getStaticRoutesInternal(containerName));
+        if (queryString != null) {
+            queryContext.createQuery(queryString, StaticRoutes.class)
+                .filter(result, StaticRoute.class);
+        }
+        return result;
     }
 
     /**
index 76ce062424b32568f9838e8ab05476ace1201439..7e2919bc44c1a7f698f2afe77c31d3347de3fc4a 100644 (file)
@@ -64,7 +64,9 @@
                 org.opendaylight.controller.northbound.commons,
                 org.opendaylight.controller.northbound.commons.exception,
                 org.opendaylight.controller.northbound.commons.utils,
+                org.opendaylight.controller.northbound.commons.query,
                 javax.ws.rs,
+                javax.ws.rs.ext,
                 javax.ws.rs.core,
                 javax.xml.bind.annotation,
                 javax.xml.bind,
index 5338849a62626ed740c6d930d72064efa1dca4d2..4175f1e3c49984c7d90ac03b2207df946c9f7e3a 100644 (file)
@@ -15,9 +15,11 @@ import javax.ws.rs.GET;
 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.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.SecurityContext;
+import javax.ws.rs.ext.ContextResolver;
 
 import org.codehaus.enunciate.jaxrs.ResponseCode;
 import org.codehaus.enunciate.jaxrs.StatusCodes;
@@ -29,6 +31,7 @@ import org.opendaylight.controller.northbound.commons.exception.ResourceConflict
 import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException;
 import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException;
 import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException;
+import org.opendaylight.controller.northbound.commons.query.QueryContext;
 import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils;
 import org.opendaylight.controller.sal.authorization.Privilege;
 import org.opendaylight.controller.sal.core.Node;
@@ -57,7 +60,14 @@ import org.opendaylight.controller.switchmanager.ISwitchManager;
 public class StatisticsNorthbound {
 
     private String username;
+    private QueryContext queryContext;
 
+    @Context
+    public void setQueryContext(ContextResolver<QueryContext> queryCtxResolver) {
+      if (queryCtxResolver != null) {
+        queryContext = queryCtxResolver.getContext(QueryContext.class);
+      }
+    }
     @Context
     public void setSecurityContext(SecurityContext context) {
         if (context != null && context.getUserPrincipal() != null) username = context.getUserPrincipal().getName();
@@ -234,7 +244,8 @@ public class StatisticsNorthbound {
         @ResponseCode(code = 404, condition = "The containerName is not found"),
         @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
     public AllFlowStatistics getFlowStatistics(
-            @PathParam("containerName") String containerName) {
+            @PathParam("containerName") String containerName,
+            @QueryParam("_q") String queryString) {
         if (!NorthboundUtils.isAuthorized(
                 getUserName(), containerName, Privilege.READ, this)) {
             throw new UnauthorizedException(
@@ -265,7 +276,12 @@ public class StatisticsNorthbound {
             FlowStatistics stat = new FlowStatistics(node, flowStats);
             statistics.add(stat);
         }
-        return new AllFlowStatistics(statistics);
+        AllFlowStatistics result = new AllFlowStatistics(statistics);
+        if (queryString != null) {
+            queryContext.createQuery(queryString, AllFlowStatistics.class)
+                .filter(result, FlowStatistics.class);
+        }
+        return result;
     }
 
     /**
@@ -610,7 +626,8 @@ public class StatisticsNorthbound {
         @ResponseCode(code = 404, condition = "The containerName is not found"),
         @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
     public AllPortStatistics getPortStatistics(
-            @PathParam("containerName") String containerName) {
+            @PathParam("containerName") String containerName,
+            @QueryParam("_q") String queryString) {
 
         if (!NorthboundUtils.isAuthorized(
                 getUserName(), containerName, Privilege.READ, this)) {
@@ -638,7 +655,13 @@ public class StatisticsNorthbound {
             PortStatistics portStat = new PortStatistics(node, stat);
             statistics.add(portStat);
         }
-        return new AllPortStatistics(statistics);
+
+        AllPortStatistics result = new AllPortStatistics(statistics);
+        if (queryString != null) {
+            queryContext.createQuery(queryString, AllPortStatistics.class)
+                .filter(result, PortStatistics.class);
+        }
+        return result;
     }
 
     /**
@@ -924,7 +947,8 @@ public class StatisticsNorthbound {
         @ResponseCode(code = 404, condition = "The containerName is not found"),
         @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
     public AllTableStatistics getTableStatistics(
-            @PathParam("containerName") String containerName) {
+            @PathParam("containerName") String containerName,
+            @QueryParam("_q") String queryString) {
 
         if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
             throw new UnauthorizedException("User is not authorized to perform this operation on container "
@@ -952,7 +976,12 @@ public class StatisticsNorthbound {
             TableStatistics tableStat = new TableStatistics(node, stat);
             statistics.add(tableStat);
         }
-        return new AllTableStatistics(statistics);
+        AllTableStatistics allstats = new AllTableStatistics(statistics);
+        if (queryString != null) {
+            queryContext.createQuery(queryString, AllTableStatistics.class)
+                .filter(allstats, TableStatistics.class);
+        }
+        return allstats;
     }
 
     /**
index 5aa2f7f202a00c30eff3937d0f7bb34efb76cf0c..630221fcc2dac2b0c53a945cbeaf41ef63c9a1cd 100644 (file)
               org.opendaylight.controller.switchmanager,
               org.opendaylight.controller.northbound.commons,
               org.opendaylight.controller.northbound.commons.exception,
+              org.opendaylight.controller.northbound.commons.query,
               org.opendaylight.controller.northbound.commons.utils,
               com.sun.jersey.spi.container.servlet,
               org.opendaylight.controller.sal.authorization,
               org.opendaylight.controller.usermanager,
               javax.ws.rs,
               javax.ws.rs.core,
+              javax.ws.rs.ext,
               javax.xml.bind,
               javax.xml.bind.annotation,
               org.slf4j,
index 3465dc95addd727ade9243e3410208cc7735ec40..b6274795df9279275e1b1d7e145aa2fa3055914b 100644 (file)
@@ -19,11 +19,13 @@ 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.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.SecurityContext;
 import javax.ws.rs.core.UriInfo;
+import javax.ws.rs.ext.ContextResolver;
 
 import org.codehaus.enunciate.jaxrs.ResponseCode;
 import org.codehaus.enunciate.jaxrs.StatusCodes;
@@ -35,6 +37,7 @@ import org.opendaylight.controller.northbound.commons.exception.ResourceConflict
 import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException;
 import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException;
 import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException;
+import org.opendaylight.controller.northbound.commons.query.QueryContext;
 import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils;
 import org.opendaylight.controller.sal.authorization.Privilege;
 import org.opendaylight.controller.sal.core.NodeConnector;
@@ -63,6 +66,14 @@ public class SubnetsNorthbound {
     protected static final Logger logger = LoggerFactory.getLogger(SubnetsNorthbound.class);
 
     private String username;
+    private QueryContext queryContext;
+
+    @Context
+    public void setQueryContext(ContextResolver<QueryContext> queryCtxResolver) {
+      if (queryCtxResolver != null) {
+        queryContext = queryCtxResolver.getContext(QueryContext.class);
+      }
+    }
 
     @Context
     public void setSecurityContext(SecurityContext context) {
@@ -160,9 +171,11 @@ public class SubnetsNorthbound {
     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
     @StatusCodes({ @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
         @ResponseCode(code = 404, condition = "The containerName passed was not found"),
-        @ResponseCode(code = 503, condition = "Service unavailable") })
+        @ResponseCode(code = 503, condition = "Service unavailable"),
+        @ResponseCode(code = 400, condition = "Incorrect query syntex") })
     @TypeHint(SubnetConfigs.class)
-    public SubnetConfigs listSubnets(@PathParam("containerName") String containerName) {
+    public SubnetConfigs listSubnets(@PathParam("containerName") String containerName,
+        @QueryParam("_q") String queryString) {
 
         handleContainerDoesNotExist(containerName);
         if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
@@ -174,7 +187,13 @@ public class SubnetsNorthbound {
         if (switchManager == null) {
             throw new ServiceUnavailableException("SwitchManager " + RestMessages.SERVICEUNAVAILABLE.toString());
         }
-        return new SubnetConfigs(switchManager.getSubnetsConfigList());
+        List<SubnetConfig> subnets = switchManager.getSubnetsConfigList();
+        if (queryString != null) {
+            subnets = queryContext.createQuery(queryString, SubnetConfig.class)
+                    .find(subnets);
+
+        }
+        return new SubnetConfigs(subnets);
     }
 
     /**
index 590f0bb533dbf610990fb4082a10f8b220a86023..614ec8847658d87800de3f6319c076357020d269 100644 (file)
@@ -58,7 +58,9 @@
               org.opendaylight.controller.northbound.commons.exception,
               org.opendaylight.controller.northbound.commons.utils,
               org.opendaylight.controller.sal.authorization,
+              org.opendaylight.controller.northbound.commons.query,
               javax.ws.rs,
+              javax.ws.rs.ext,
               javax.ws.rs.core,
               javax.xml.bind.annotation,
               javax.xml.bind,
index e30dad24ab18866b1c455a8facf7bf347a0d22b2..dab5d7d1b26785b6f2564d1d0ebb3fbecda861e5 100644 (file)
@@ -23,11 +23,13 @@ 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.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.SecurityContext;
 import javax.ws.rs.core.UriInfo;
+import javax.ws.rs.ext.ContextResolver;
 
 import org.codehaus.enunciate.jaxrs.ResponseCode;
 import org.codehaus.enunciate.jaxrs.StatusCodes;
@@ -38,6 +40,7 @@ import org.opendaylight.controller.northbound.commons.exception.InternalServerEr
 import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException;
 import org.opendaylight.controller.northbound.commons.exception.ServiceUnavailableException;
 import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException;
+import org.opendaylight.controller.northbound.commons.query.QueryContext;
 import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils;
 import org.opendaylight.controller.sal.authorization.Privilege;
 import org.opendaylight.controller.sal.core.Node;
@@ -60,6 +63,14 @@ import org.opendaylight.controller.switchmanager.SwitchConfig;
 public class SwitchNorthbound {
 
     private String username;
+    private QueryContext queryContext;
+
+    @Context
+    public void setQueryContext(ContextResolver<QueryContext> queryCtxResolver) {
+      if (queryCtxResolver != null) {
+        queryContext = queryCtxResolver.getContext(QueryContext.class);
+      }
+    }
 
     @Context
     public void setSecurityContext(SecurityContext context) {
@@ -200,8 +211,9 @@ public class SwitchNorthbound {
     @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"),
         @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
         @ResponseCode(code = 404, condition = "The containerName is not found"),
-        @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
-    public Nodes getNodes(@PathParam("containerName") String containerName) {
+        @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable"),
+        @ResponseCode(code = 400, condition = "Incorrect query syntex") })
+    public Nodes getNodes(@PathParam("containerName") String containerName, @QueryParam("_q") String queryString) {
 
         if (!isValidContainer(containerName)) {
             throw new ResourceNotFoundException("Container " + containerName + " does not exist.");
@@ -233,8 +245,12 @@ public class SwitchNorthbound {
             NodeProperties nodeProps = new NodeProperties(node, props);
             res.add(nodeProps);
         }
-
-        return new Nodes(res);
+        Nodes result = new Nodes(res);
+        if (queryString != null) {
+            queryContext.createQuery(queryString, Nodes.class)
+                .filter(result, NodeProperties.class);
+        }
+        return result;
     }
 
     /**
@@ -564,9 +580,11 @@ public class SwitchNorthbound {
     @StatusCodes({ @ResponseCode(code = 200, condition = "Operation successful"),
         @ResponseCode(code = 401, condition = "User not authorized to perform this operation"),
         @ResponseCode(code = 404, condition = "The containerName is not found"),
-        @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable") })
+        @ResponseCode(code = 503, condition = "One or more of Controller Services are unavailable"),
+        @ResponseCode(code = 400, condition = "Incorrect query syntex") })
     public NodeConnectors getNodeConnectors(@PathParam("containerName") String containerName,
-            @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId) {
+            @PathParam("nodeType") String nodeType, @PathParam("nodeId") String nodeId,
+            @QueryParam("_q") String queryString) {
 
         if (!isValidContainer(containerName)) {
             throw new ResourceNotFoundException("Container " + containerName + " does not exist.");
@@ -598,8 +616,12 @@ public class SwitchNorthbound {
             NodeConnectorProperties ncProps = new NodeConnectorProperties(nc, props);
             res.add(ncProps);
         }
-
-        return new NodeConnectors(res);
+        NodeConnectors result = new NodeConnectors(res);
+        if (queryString != null) {
+            queryContext.createQuery(queryString, NodeConnectors.class)
+                .filter(result, NodeConnectorProperties.class);
+        }
+        return result;
     }
 
     /**
index 4a1142bb1813784fd7b5108a807ac9fde26bc6c5..3f1a7701102467edf00dd974c254407728049176 100644 (file)
@@ -51,6 +51,7 @@
               org.opendaylight.controller.northbound.commons,
               org.opendaylight.controller.northbound.commons.exception,
               org.opendaylight.controller.northbound.commons.utils,
+              org.opendaylight.controller.northbound.commons.query,
               org.opendaylight.controller.sal.core,
               org.opendaylight.controller.sal.packet,
               org.opendaylight.controller.sal.authorization,
@@ -62,6 +63,7 @@
               com.sun.jersey.spi.container.servlet,
               com.fasterxml.jackson.annotation,
               javax.ws.rs,
+              javax.ws.rs.ext,
               javax.ws.rs.core,
               javax.xml.bind,
               javax.xml.bind.annotation,
index 427aa1c1deaaf98c86fa3ecd072757bc6331892c..3773070504a0fa4be1e107e422793b52085217d2 100644 (file)
@@ -21,10 +21,12 @@ 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.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import javax.ws.rs.core.SecurityContext;
+import javax.ws.rs.ext.ContextResolver;
 
 import org.codehaus.enunciate.jaxrs.ResponseCode;
 import org.codehaus.enunciate.jaxrs.StatusCodes;
@@ -33,6 +35,7 @@ import org.opendaylight.controller.northbound.commons.RestMessages;
 import org.opendaylight.controller.northbound.commons.exception.InternalServerErrorException;
 import org.opendaylight.controller.northbound.commons.exception.ResourceNotFoundException;
 import org.opendaylight.controller.northbound.commons.exception.UnauthorizedException;
+import org.opendaylight.controller.northbound.commons.query.QueryContext;
 import org.opendaylight.controller.northbound.commons.utils.NorthboundUtils;
 import org.opendaylight.controller.sal.authorization.Privilege;
 import org.opendaylight.controller.sal.core.Edge;
@@ -59,7 +62,14 @@ import org.opendaylight.controller.topologymanager.TopologyUserLinkConfig;
 public class TopologyNorthboundJAXRS {
 
     private String username;
+    private QueryContext queryContext;
 
+    @Context
+    public void setQueryContext(ContextResolver<QueryContext> queryCtxResolver) {
+      if (queryCtxResolver != null) {
+        queryContext = queryCtxResolver.getContext(QueryContext.class);
+      }
+    }
     @Context
     public void setSecurityContext(SecurityContext context) {
         if (context != null && context.getUserPrincipal() != null) {
@@ -240,7 +250,8 @@ public class TopologyNorthboundJAXRS {
     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
     @TypeHint(Topology.class)
     @StatusCodes({ @ResponseCode(code = 404, condition = "The Container Name was not found") })
-    public Topology getTopology(@PathParam("containerName") String containerName) {
+    public Topology getTopology(@PathParam("containerName") String containerName,
+        @QueryParam("_q") String queryString) {
 
         if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
             throw new UnauthorizedException("User is not authorized to perform this operation on container "
@@ -253,16 +264,21 @@ public class TopologyNorthboundJAXRS {
         }
 
         Map<Edge, Set<Property>> topo = topologyManager.getEdges();
-        if (topo != null) {
-            List<EdgeProperties> res = new ArrayList<EdgeProperties>();
-            for (Map.Entry<Edge, Set<Property>> entry : topo.entrySet()) {
-                EdgeProperties el = new EdgeProperties(entry.getKey(), entry.getValue());
-                res.add(el);
-            }
-            return new Topology(res);
+        if (topo == null) {
+            return null;
+        }
+        List<EdgeProperties> res = new ArrayList<EdgeProperties>();
+        for (Map.Entry<Edge, Set<Property>> entry : topo.entrySet()) {
+            EdgeProperties el = new EdgeProperties(entry.getKey(), entry.getValue());
+            res.add(el);
         }
+        Topology result = new Topology(res);
 
-        return null;
+        if (queryString != null) {
+            queryContext.createQuery(queryString, Topology.class)
+                .filter(result, EdgeProperties.class);
+        }
+        return result;
     }
 
     /**
@@ -311,7 +327,8 @@ public class TopologyNorthboundJAXRS {
     @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
     @TypeHint(TopologyUserLinks.class)
     @StatusCodes({ @ResponseCode(code = 404, condition = "The Container Name was not found") })
-    public TopologyUserLinks getUserLinks(@PathParam("containerName") String containerName) {
+    public TopologyUserLinks getUserLinks(@PathParam("containerName") String containerName,
+        @QueryParam("_q") String queryString) {
 
         if (!NorthboundUtils.isAuthorized(getUserName(), containerName, Privilege.READ, this)) {
             throw new UnauthorizedException("User is not authorized to perform this operation on container "
@@ -324,12 +341,16 @@ public class TopologyNorthboundJAXRS {
         }
 
         ConcurrentMap<String, TopologyUserLinkConfig> userLinks = topologyManager.getUserLinks();
-        if ((userLinks != null) && (userLinks.values() != null)) {
-            List<TopologyUserLinkConfig> res = new ArrayList<TopologyUserLinkConfig>(userLinks.values());
-            return new TopologyUserLinks(res);
+        if ((userLinks == null) || (userLinks.values() == null)) {
+            return null;
         }
-
-        return null;
+        TopologyUserLinks result = new TopologyUserLinks(
+                new ArrayList<TopologyUserLinkConfig>(userLinks.values()));
+        if (queryString != null) {
+            queryContext.createQuery(queryString, TopologyUserLinks.class)
+                .filter(result, TopologyUserLinkConfig.class);
+        }
+        return result;
     }
 
     /**
index 5c2af6d8b430471d25f68a68c25e8915c9d02e97..932ac4e20be37f8d5ea1234265054209ceda120f 100644 (file)
@@ -32,11 +32,15 @@ import org.opendaylight.controller.sal.core.Node;
 import org.opendaylight.controller.sal.core.NodeConnector;
 import org.opendaylight.controller.sal.core.Property;
 import org.opendaylight.controller.sal.core.UpdateType;
+import org.opendaylight.controller.sal.match.Match;
+import org.opendaylight.controller.sal.packet.Ethernet;
 import org.opendaylight.controller.sal.packet.IPluginOutDataPacketService;
+import org.opendaylight.controller.sal.packet.PacketException;
 import org.opendaylight.controller.sal.packet.PacketResult;
 import org.opendaylight.controller.sal.packet.RawPacket;
 import org.opendaylight.controller.sal.utils.GlobalConstants;
 import org.opendaylight.controller.sal.utils.HexEncode;
+import org.opendaylight.controller.sal.utils.NetUtils;
 import org.openflow.protocol.OFMessage;
 import org.openflow.protocol.OFPacketIn;
 import org.openflow.protocol.OFPacketOut;
@@ -169,12 +173,10 @@ public class DataPacketMuxDemux implements IContainerListener,
 
     @Override
     public void receive(ISwitch sw, OFMessage msg) {
-        if (sw == null || msg == null
-                || this.pluginOutDataPacketServices == null) {
+        if (sw == null || msg == null || this.pluginOutDataPacketServices == null) {
             // Something fishy, we cannot do anything
-            logger.debug(
-                    "sw: {} and/or msg: {} and/or pluginOutDataPacketServices: {} is null!",
-                    new Object[] { sw, msg, this.pluginOutDataPacketServices });
+            logger.debug("sw: {} and/or msg: {} and/or pluginOutDataPacketServices: {} is null!", new Object[] { sw,
+                    msg, this.pluginOutDataPacketServices });
             return;
         }
 
@@ -185,8 +187,7 @@ public class DataPacketMuxDemux implements IContainerListener,
                 logger.debug("Connection service refused DataPacketMuxDemux receive {} {}", sw, msg);
                 return;
             }
-        }
-        catch (Exception e) {
+        } catch (Exception e) {
             return;
         }
 
@@ -204,63 +205,72 @@ public class DataPacketMuxDemux implements IContainerListener,
                 // pass the parsed packet simply because once the
                 // packet infra is settled all the packets will passed
                 // around as parsed and read-only
-                for (int i = 0; i < this.iDataPacketListen.size(); i++) {
-                    IDataPacketListen s = this.iDataPacketListen.get(i);
-                    if (s.receiveDataPacket(dataPacket).equals(
-                            PacketResult.CONSUME)) {
+                for (IDataPacketListen s : this.iDataPacketListen) {
+                      if (s.receiveDataPacket(dataPacket).equals(PacketResult.CONSUME)) {
                         logger.trace("Consumed locally data packet");
                         return;
                     }
                 }
 
-                // Now dispatch the packet toward SAL at least for
-                // default container, we need to revisit this in a general
-                // slicing architecture refresh
-                IPluginOutDataPacketService defaultOutService = this.pluginOutDataPacketServices
-                        .get(GlobalConstants.DEFAULT.toString());
-                if (defaultOutService != null) {
-                    defaultOutService.receiveDataPacket(dataPacket);
-                    if (logger.isTraceEnabled()) {
-                      logger.trace(
-                              "Dispatched to apps a frame of size: {} on " +
-                              "container: {}: {}", new Object[] {
-                                    ofPacket.getPacketData().length,
-                                    GlobalConstants.DEFAULT.toString(),
-                                    HexEncode.bytesToHexString(dataPacket
-                                            .getPacketData()) });
-                    }
-                }
+                boolean dispatched_to_container = false;
+
                 // Now check the mapping between nodeConnector and
                 // Container and later on optimally filter based on
                 // flowSpec
                 List<String> containersRX = this.nc2Container.get(p);
                 if (containersRX != null) {
-                    for (int i = 0; i < containersRX.size(); i++) {
-                        String container = containersRX.get(i);
-                        IPluginOutDataPacketService s = this.pluginOutDataPacketServices
-                                .get(container);
-                        if (s != null) {
-                            // TODO add filtering on a per-flowSpec base
-                            s.receiveDataPacket(dataPacket);
-                            if (logger.isTraceEnabled()) {
-                              logger.trace(
-                                      "Dispatched to apps a frame of size: {}" +
-                                      " on container: {}: {}", new Object[] {
-                                            ofPacket.getPacketData().length,
-                                            container,
-                                            HexEncode.bytesToHexString(dataPacket
-                                                    .getPacketData()) });
+                    Ethernet frame = new Ethernet();
+                    byte data[] = dataPacket.getPacketData();
+                    frame.deserialize(data, 0, data.length * NetUtils.NumBitsInAByte);
+                    Match packetMatch = frame.getMatch();
+                    for (String container : containersRX) {
+                        boolean notify = true;
+                        List<ContainerFlow> containerFlows = this.container2FlowSpecs.get(container);
+                        if (containerFlows != null) {
+                            notify = false;
+                            for (ContainerFlow cFlow : containerFlows) {
+                                if (cFlow.allowsMatch(packetMatch)) {
+                                    notify = true;
+                                    break;
+                                }
+                            }
+                            if (notify) {
+                                IPluginOutDataPacketService s = this.pluginOutDataPacketServices.get(container);
+                                if (s != null) {
+                                    s.receiveDataPacket(dataPacket);
+                                    if (logger.isTraceEnabled()) {
+                                        logger.trace(
+                                                "Dispatched to apps a frame of size: {}" + " on container: {}: {}",
+                                                new Object[] { ofPacket.getPacketData().length, container,
+                                                        HexEncode.bytesToHexString(dataPacket.getPacketData()) });
+                                    }
+                                }
+                                dispatched_to_container = true;
                             }
                         }
                     }
                 }
-
+                if (!dispatched_to_container) {
+                    // Now dispatch the packet toward SAL for default container
+                    IPluginOutDataPacketService defaultOutService = this.pluginOutDataPacketServices
+                        .get(GlobalConstants.DEFAULT.toString());
+                    if (defaultOutService != null) {
+                        defaultOutService.receiveDataPacket(dataPacket);
+                        if (logger.isTraceEnabled()) {
+                            logger.trace("Dispatched to apps a frame of size: {} on " + "container: {}: {}",
+                                         new Object[] { ofPacket.getPacketData().length,
+                                                        GlobalConstants.DEFAULT.toString(),
+                                                        HexEncode.bytesToHexString(dataPacket.getPacketData()) });
+                        }
+                    }
+                }
                 // This is supposed to be the catch all for all the
                 // DataPacket hence we will assume it has been handled
                 return;
             } catch (ConstructionException cex) {
+            } catch (PacketException e) {
+                logger.debug("Failed to deserialize raw packet: ", e.getMessage());
             }
-
             // If we reach this point something went wrong.
             return;
         } else {
index 8fc0d625ebe0dd5b08bff4df864efe6a2e3068bd..21c17b366c04c025683b5c032981f043428e326a 100644 (file)
@@ -1,6 +1,6 @@
 
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013-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,
@@ -258,18 +258,23 @@ public class ARP extends Packet {
 
     @Override
     public boolean equals(Object obj) {
-        if (this == obj)
+        if (this == obj) {
             return true;
-        if (!super.equals(obj))
+        }
+        if (!super.equals(obj)) {
             return false;
-        if (getClass() != obj.getClass())
+        }
+        if (getClass() != obj.getClass()) {
             return false;
+        }
         ARP other = (ARP) obj;
         if (fieldValues == null) {
-            if (other.fieldValues != null)
+            if (other.fieldValues != null) {
                 return false;
-        } else if (!fieldValues.equals(other.fieldValues))
+            }
+        } else if (!fieldValues.equals(other.fieldValues)) {
             return false;
+        }
         return true;
     }
 }
index d0068564a93b29a326395b1e6cae9eeacf968a53..235e71a760faa01eb9cf9d2acf92a73c8acf00ce 100644 (file)
@@ -15,6 +15,8 @@ import java.util.Map;
 
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.apache.commons.lang3.tuple.Pair;
+import org.opendaylight.controller.sal.match.Match;
+import org.opendaylight.controller.sal.match.MatchType;
 import org.opendaylight.controller.sal.utils.EtherTypes;
 import org.opendaylight.controller.sal.utils.NetUtils;
 
@@ -139,4 +141,10 @@ public class Ethernet extends Packet {
         return this;
     }
 
+    @Override
+    public void populateMatch(Match match) {
+        match.setField(MatchType.DL_SRC, this.getSourceMACAddress());
+        match.setField(MatchType.DL_DST, this.getDestinationMACAddress());
+        match.setField(MatchType.DL_TYPE, this.getEtherType());
+    }
 }
index 39c7d386bc1fe3ccf5ff397ebfcc491fe108aad6..4c0c94ccb82a50d5027b1be6ea23718939cc3a28 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013-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,
@@ -11,8 +11,11 @@ package org.opendaylight.controller.sal.packet;
 import java.util.HashMap;
 import java.util.LinkedHashMap;
 import java.util.Map;
+
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.apache.commons.lang3.tuple.Pair;
+import org.opendaylight.controller.sal.match.Match;
+import org.opendaylight.controller.sal.match.MatchType;
 
 /**
  * Class that represents the IEEE 802.1Q objects
@@ -148,4 +151,20 @@ public class IEEE8021Q extends Packet {
         return this;
     }
 
+    @Override
+    public void populateMatch(Match match) {
+        match.setField(MatchType.DL_VLAN, this.getVid());
+        match.setField(MatchType.DL_VLAN_PR, this.getPcp());
+        match.setField(MatchType.DL_TYPE, this.getEtherType());
+    }
+
+    /**
+     * Gets the header size in bits
+     * @return The .1Q header size in bits
+     */
+    @Override
+    public int getHeaderSize() {
+        return 32;
+    }
+
 }
index 559acd633ab7e56b6cb22042f7d3974a1e217212..3363f423d695f1b2f090e6c5274715f47d765e3c 100644 (file)
@@ -1,6 +1,6 @@
 
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013-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,
@@ -20,6 +20,8 @@ import java.util.Random;
 
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.apache.commons.lang3.tuple.Pair;
+import org.opendaylight.controller.sal.match.Match;
+import org.opendaylight.controller.sal.match.MatchType;
 import org.opendaylight.controller.sal.utils.IPProtocols;
 import org.opendaylight.controller.sal.utils.NetUtils;
 import org.slf4j.Logger;
@@ -577,4 +579,12 @@ public class IPv4 extends Packet {
             corrupted = true;
         }
     }
+
+    @Override
+    public void populateMatch(Match match) {
+        match.setField(MatchType.NW_SRC, NetUtils.getInetAddress(this.getSourceAddress()));
+        match.setField(MatchType.NW_DST, NetUtils.getInetAddress(this.getDestinationAddress()));
+        match.setField(MatchType.NW_PROTO, this.getProtocol());
+        match.setField(MatchType.NW_TOS, this.getDiffServ());
+    }
 }
index 6f5cf04a529ed5a2872ff1d7c299eac71a1e060a..9b5dc082bb2303084775026131a11552b5614add 100644 (file)
@@ -12,6 +12,7 @@ import java.util.ArrayList;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
+
 import org.opendaylight.controller.sal.utils.HexEncode;
 import org.opendaylight.controller.sal.utils.NetUtils;
 
index efb938e37f50745aae8f1f560b0d85f2bb7e7c07..35244ea697d871617b09db6e232da95af0d51ebf 100644 (file)
@@ -151,18 +151,23 @@ public class LLDPTLV extends Packet {
 
     @Override
     public boolean equals(Object obj) {
-        if (this == obj)
+        if (this == obj) {
             return true;
-        if (!super.equals(obj))
+        }
+        if (!super.equals(obj)) {
             return false;
-        if (getClass() != obj.getClass())
+        }
+        if (getClass() != obj.getClass()) {
             return false;
+        }
         LLDPTLV other = (LLDPTLV) obj;
         if (fieldValues == null) {
-            if (other.fieldValues != null)
+            if (other.fieldValues != null) {
                 return false;
-        } else if (!fieldValues.equals(other.fieldValues))
+            }
+        } else if (!fieldValues.equals(other.fieldValues)) {
             return false;
+        }
         return true;
     }
 
index 58b5d3914aa2dc199111dd2f2dc1ff8d5289dcc0..789aa126533c93c16660e5eafcfc995dc510fab1 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013-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,
@@ -13,6 +13,7 @@ import java.util.Map;
 import java.util.Map.Entry;
 
 import org.apache.commons.lang3.tuple.Pair;
+import org.opendaylight.controller.sal.match.Match;
 import org.opendaylight.controller.sal.utils.HexEncode;
 import org.opendaylight.controller.sal.utils.NetUtils;
 import org.slf4j.Logger;
@@ -364,4 +365,31 @@ public abstract class Packet {
         return true;
     }
 
+    /**
+     * Adds to the passed Match this packet's header fields
+     *
+     * @param match
+     *            The Match object to populate
+     */
+    public void populateMatch(Match match) {
+        // To be overridden by derived packet classes which have well known
+        // header fields so that Packet.getMatch would return desired result
+    }
+
+    /**
+     * Returns the Match object containing this packet and its payload
+     * encapsulated packets' header fields
+     *
+     * @return The Match containing the header fields of this packet and of its
+     *         payload encapsulated packets
+     */
+    public Match getMatch() {
+        Match match = new Match();
+        Packet packet = this;
+        while (packet != null) {
+            packet.populateMatch(match);
+            packet = packet.getPayload();
+        }
+        return match;
+    }
 }
index 8253ac46d3f5405ace57da8022be90a183645a68..d27494599c280418044e4ef78210678562852cc0 100644 (file)
@@ -1,6 +1,6 @@
 
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013-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,
@@ -15,6 +15,8 @@ import java.util.Map;
 
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.apache.commons.lang3.tuple.Pair;
+import org.opendaylight.controller.sal.match.Match;
+import org.opendaylight.controller.sal.match.MatchType;
 
 /**
  * Class that represents the TCP segment objects
@@ -238,4 +240,9 @@ public class TCP extends Packet {
         return (BitBufferHelper.getShort(fieldValues.get(CHECKSUM)));
     }
 
+    @Override
+    public void populateMatch(Match match) {
+        match.setField(MatchType.TP_SRC, this.getSourcePort());
+        match.setField(MatchType.TP_DST, this.getDestinationPort());
+    }
 }
index f82ed8fcaee00115bef01f4a6b03813389bf1a0c..069a277f89d9ee44df2e4ca22d9783fb9b9a6404 100644 (file)
@@ -1,6 +1,6 @@
 
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013-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,
@@ -15,6 +15,8 @@ import java.util.Map;
 
 import org.apache.commons.lang3.tuple.ImmutablePair;
 import org.apache.commons.lang3.tuple.Pair;
+import org.opendaylight.controller.sal.match.Match;
+import org.opendaylight.controller.sal.match.MatchType;
 
 /**
  * Class that represents the UDP datagram objects
@@ -156,4 +158,10 @@ public class UDP extends Packet {
         fieldValues.put(CHECKSUM, checksum);
         return this;
     }
+
+    @Override
+    public void populateMatch(Match match) {
+        match.setField(MatchType.TP_SRC, this.getSourcePort());
+        match.setField(MatchType.TP_DST, this.getDestinationPort());
+    }
 }
index a3ebd7ee0d164163b18f8091199f63bc89c4e30a..10bd535eb2790a1876fe2f9cfa29afb681b4ed1b 100644 (file)
@@ -1,6 +1,6 @@
 
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013-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,
index 2494eb6b2d459460c0ab825e9b18c0fc15d30029..494dd2abf28c0d0e660debeb6a9936c3c752315a 100644 (file)
@@ -1,6 +1,6 @@
 
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013-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,
@@ -9,9 +9,14 @@
 
 package org.opendaylight.controller.sal.packet;
 
+import java.util.Arrays;
+
 import junit.framework.Assert;
 
 import org.junit.Test;
+import org.opendaylight.controller.sal.match.Match;
+import org.opendaylight.controller.sal.match.MatchType;
+import org.opendaylight.controller.sal.utils.EtherTypes;
 
 public class EthernetTest {
 
@@ -95,4 +100,22 @@ public class EthernetTest {
 
     }
 
+    @Test
+    public void testGetMatch() throws Exception {
+        Ethernet eth = new Ethernet();
+        byte smac[] = { (byte) 0xf0, (byte) 0xde, (byte) 0xf1, (byte) 0x71, (byte) 0x72, (byte) 0x8d };
+        byte dmac[] = { (byte) 0xde, (byte) 0x28, (byte) 0xdb, (byte) 0xb3, (byte) 0x7c, (byte) 0xf8 };
+        short ethType = EtherTypes.IPv4.shortValue();
+        eth.setDestinationMACAddress(dmac);
+        eth.setSourceMACAddress(smac);
+        eth.setEtherType(ethType);
+
+        Match match = eth.getMatch();
+
+        Assert.assertTrue(Arrays.equals(smac, (byte[]) match.getField(MatchType.DL_SRC).getValue()));
+        Assert.assertTrue(Arrays.equals(dmac, (byte[]) match.getField(MatchType.DL_DST).getValue()));
+        Assert.assertEquals(ethType, (short) match.getField(MatchType.DL_TYPE).getValue());
+
+    }
+
 }
index a4c6c1fc4b335472d302c655ffd52e1544767e36..2443b491c7e8a7fb69fba50c65681a6bd691f597 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013-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,
@@ -9,7 +9,11 @@
 package org.opendaylight.controller.sal.packet;
 
 import junit.framework.Assert;
+
 import org.junit.Test;
+import org.opendaylight.controller.sal.match.Match;
+import org.opendaylight.controller.sal.match.MatchType;
+import org.opendaylight.controller.sal.utils.EtherTypes;
 import org.opendaylight.controller.sal.utils.NetUtils;
 
 public class IEEE8021QTest {
@@ -212,4 +216,21 @@ public class IEEE8021QTest {
         Assert.assertTrue(data[44] == (byte) 0x09);
         Assert.assertTrue(data[45] == (byte) 0xFE);
     }
+
+    @Test
+    public void testGetMatchFullPacket() throws Exception {
+        IEEE8021Q dot1q = new IEEE8021Q();
+        byte priority = 4;
+        short vlanId = 59;
+        short ethType = EtherTypes.IPv4.shortValue();
+        dot1q.setPcp(priority);
+        dot1q.setVid(vlanId);
+        dot1q.setEtherType(ethType);
+
+        Match match = dot1q.getMatch();
+
+        Assert.assertEquals(priority, (byte) match.getField(MatchType.DL_VLAN_PR).getValue());
+        Assert.assertEquals(vlanId, (short) match.getField(MatchType.DL_VLAN).getValue());
+        Assert.assertEquals(ethType, (short) match.getField(MatchType.DL_TYPE).getValue());
+    }
 }
index 5afcd8be7dc4f47d79270dd00b6c3c8870c07631..f5298711b677a64ef9c80863580743ce2c394e52 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013-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,
@@ -15,6 +15,8 @@ import java.util.Arrays;
 import junit.framework.Assert;
 
 import org.junit.Test;
+import org.opendaylight.controller.sal.match.Match;
+import org.opendaylight.controller.sal.match.MatchType;
 import org.opendaylight.controller.sal.utils.EtherTypes;
 import org.opendaylight.controller.sal.utils.IPProtocols;
 import org.opendaylight.controller.sal.utils.NetUtils;
@@ -452,4 +454,31 @@ public class IPv4Test {
         Assert.assertFalse(decIcmp.isCorrupted());
         Assert.assertTrue(Arrays.equals(icmpRawPayload, decIcmp.getRawPayload()));
     }
+
+    @Test
+    public void testGetMatch() throws Exception {
+        IPv4 ip = new IPv4();
+        InetAddress sourceAddress = InetAddress.getByName("172.168.190.15");
+        InetAddress destintationAddress = InetAddress.getByName("23.128.0.11");
+        byte protocol = IPProtocols.TCP.byteValue();
+        byte tos = 7;
+        ip.setVersion((byte) 4);
+        ip.setIdentification((short) 5);
+        ip.setDiffServ(tos);
+        ip.setECN((byte) 0);
+        ip.setTotalLength((short) 84);
+        ip.setFlags((byte) 2);
+        ip.setFragmentOffset((short) 0);
+        ip.setTtl((byte) 64);
+        ip.setProtocol(protocol);
+        ip.setDestinationAddress(destintationAddress);
+        ip.setSourceAddress(sourceAddress);
+
+        Match match = ip.getMatch();
+
+        Assert.assertEquals(sourceAddress, match.getField(MatchType.NW_SRC).getValue());
+        Assert.assertEquals(destintationAddress, match.getField(MatchType.NW_DST).getValue());
+        Assert.assertEquals(protocol, (byte) match.getField(MatchType.NW_PROTO).getValue());
+        Assert.assertEquals(tos, (byte) match.getField(MatchType.NW_TOS).getValue());
+    }
 }
index 8f3b283b2ea020a175b53e952d08f41cd7ca1c69..95eff32ef1899f39a3838f2f46fea8c0f51923fa 100644 (file)
@@ -1,6 +1,6 @@
 
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013-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,
@@ -9,11 +9,17 @@
 
 package org.opendaylight.controller.sal.packet;
 
+import java.net.InetAddress;
+import java.util.Arrays;
 import java.util.Map;
 
 import junit.framework.Assert;
 
 import org.junit.Test;
+import org.opendaylight.controller.sal.match.Match;
+import org.opendaylight.controller.sal.match.MatchType;
+import org.opendaylight.controller.sal.utils.EtherTypes;
+import org.opendaylight.controller.sal.utils.IPProtocols;
 
 public class PacketTest {
 
@@ -120,9 +126,9 @@ public class PacketTest {
         eth.setSourceMACAddress(sMAC);
         eth.setEtherType(etherType);
 
-        dMACdata = (byte[]) fCValues.get("DestinationMACAddress");
-        sMACdata = (byte[]) fCValues.get("SourceMACAddress");
-        etherTypedata = (byte[]) fCValues.get("EtherType");
+        dMACdata = fCValues.get("DestinationMACAddress");
+        sMACdata = fCValues.get("SourceMACAddress");
+        etherTypedata = fCValues.get("EtherType");
 
         Assert.assertTrue(dMACdata[0] == 10);
         Assert.assertTrue(dMACdata[1] == 12);
@@ -160,4 +166,62 @@ public class PacketTest {
         Assert.assertTrue(data[13] == 6);
 
     }
+
+    @Test
+    public void testGetMatch() throws Exception {
+        TCP tcp = new TCP();
+        short sport = (short) 11093;
+        short dport = (short) 23;
+        tcp.setSourcePort(sport);
+        tcp.setDestinationPort(dport);
+
+        IPv4 ip = new IPv4();
+        InetAddress sourceAddress = InetAddress.getByName("192.168.100.100");
+        InetAddress destintationAddress = InetAddress.getByName("192.168.100.101");
+        byte protocol = IPProtocols.TCP.byteValue();
+        byte tos = 5;
+        ip.setVersion((byte) 4);
+        ip.setIdentification((short) 5);
+        ip.setDiffServ(tos);
+        ip.setECN((byte) 0);
+        ip.setTotalLength((short) 84);
+        ip.setFlags((byte) 2);
+        ip.setFragmentOffset((short) 0);
+        ip.setTtl((byte) 64);
+        ip.setProtocol(protocol);
+        ip.setDestinationAddress(destintationAddress);
+        ip.setSourceAddress(sourceAddress);
+        ip.setPayload(tcp);
+
+        IEEE8021Q dot1q = new IEEE8021Q();
+        byte priority = 4;
+        short vlanId = 59;
+        short ethType = EtherTypes.IPv4.shortValue();
+        dot1q.setPcp(priority);
+        dot1q.setVid(vlanId);
+        dot1q.setEtherType(ethType);
+        dot1q.setPayload(ip);
+
+        Ethernet eth = new Ethernet();
+        byte smac[] = { (byte) 0xf0, (byte) 0xde, (byte) 0xf1, (byte) 0x71, (byte) 0x72, (byte) 0x8d };
+        byte dmac[] = { (byte) 0xde, (byte) 0x28, (byte) 0xdb, (byte) 0xb3, (byte) 0x7c, (byte) 0xf8 };
+        eth.setDestinationMACAddress(dmac);
+        eth.setSourceMACAddress(smac);
+        eth.setEtherType(EtherTypes.VLANTAGGED.shortValue());
+        eth.setPayload(dot1q);
+
+        Match match = eth.getMatch();
+
+        Assert.assertTrue(Arrays.equals(smac, (byte[]) match.getField(MatchType.DL_SRC).getValue()));
+        Assert.assertTrue(Arrays.equals(dmac, (byte[]) match.getField(MatchType.DL_DST).getValue()));
+        Assert.assertEquals(priority, (byte) match.getField(MatchType.DL_VLAN_PR).getValue());
+        Assert.assertEquals(vlanId, (short) match.getField(MatchType.DL_VLAN).getValue());
+        Assert.assertEquals(ethType, (short) match.getField(MatchType.DL_TYPE).getValue());
+        Assert.assertEquals(sourceAddress, match.getField(MatchType.NW_SRC).getValue());
+        Assert.assertEquals(destintationAddress, match.getField(MatchType.NW_DST).getValue());
+        Assert.assertEquals(protocol, (byte) match.getField(MatchType.NW_PROTO).getValue());
+        Assert.assertEquals(tos, (byte) match.getField(MatchType.NW_TOS).getValue());
+        Assert.assertEquals(sport, (short) match.getField(MatchType.TP_SRC).getValue());
+        Assert.assertEquals(dport, (short) match.getField(MatchType.TP_DST).getValue());
+    }
 }
index 3e18aedfdb38b7238ef9a72c9d49bff151aec685..e56f41e5c1b301cf78eb8e1e5df3f29fcbe1e7e2 100644 (file)
@@ -1,6 +1,6 @@
 
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013-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,
@@ -12,6 +12,8 @@ package org.opendaylight.controller.sal.packet;
 import junit.framework.Assert;
 
 import org.junit.Test;
+import org.opendaylight.controller.sal.match.Match;
+import org.opendaylight.controller.sal.match.MatchType;
 
 public class TCPTest {
 
@@ -113,4 +115,18 @@ public class TCPTest {
         short checksum = tcp.getChecksum();
         Assert.assertTrue(checksum == 200);
     }
+
+    @Test
+    public void testGetMatch() throws Exception {
+        TCP tcp = new TCP();
+        short sport = (short) 52012;
+        short dport = (short) 40345;
+        tcp.setSourcePort(sport);
+        tcp.setDestinationPort(dport);
+
+        Match match = tcp.getMatch();
+
+        Assert.assertEquals(sport, (short) match.getField(MatchType.TP_SRC).getValue());
+        Assert.assertEquals(dport, (short) match.getField(MatchType.TP_DST).getValue());
+    }
 }
index 8d5be849a034d5a147998d7adcf5099481acb552..a3a597a82d0fcb4524da02f174c9ca0419174c81 100644 (file)
@@ -1,6 +1,6 @@
 
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013-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,
@@ -12,6 +12,8 @@ package org.opendaylight.controller.sal.packet;
 import junit.framework.Assert;
 
 import org.junit.Test;
+import org.opendaylight.controller.sal.match.Match;
+import org.opendaylight.controller.sal.match.MatchType;
 
 public class UDPTest {
 
@@ -95,4 +97,19 @@ public class UDPTest {
 
     }
 
+    @Test
+    public void testGetMatch() throws Exception {
+        UDP udp = new UDP();
+        short sport = (short) 33000;
+        short dport = (short) 843;
+        udp.setSourcePort(sport);
+        udp.setDestinationPort(dport);
+
+        Match match = udp.getMatch();
+
+        Assert.assertEquals(sport, (short) match.getField(MatchType.TP_SRC).getValue());
+        Assert.assertEquals(dport, (short) match.getField(MatchType.TP_DST).getValue());
+
+    }
+
 }
diff --git a/pom.xml b/pom.xml
index c54d9a930f28ad39ad680f30314508248bd2eea5..242ab8eb89fce53b5ee7396b02790df9e96b781b 100644 (file)
--- a/pom.xml
+++ b/pom.xml
     <!-- Karaf Distribution -->
     <module>features/base</module>
     <module>features/controller</module>
+    <module>features/adsal</module>
+    <module>features/extras</module>
     <module>opendaylight/dummy-console</module>
     <module>opendaylight/karaf-branding</module>
     <module>opendaylight/distribution/opendaylight-karaf</module>
+    <module>features</module>
   </modules>
   <scm>
     <connection>scm:git:ssh://git.opendaylight.org:29418/controller.git</connection>