Merge "Bug 1380 - Fix NullPointerException when match is null"
authorDevin Avery <devin.avery@brocade.com>
Thu, 17 Jul 2014 14:12:46 +0000 (14:12 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Thu, 17 Jul 2014 14:12:46 +0000 (14:12 +0000)
210 files changed:
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/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/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/config/config-manager/src/main/java/org/opendaylight/controller/config/manager/impl/dynamicmbean/DynamicWritableWrapper.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/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/src/main/resources/configuration/config.ini
opendaylight/distribution/opendaylight/src/main/resources/configuration/cors-config.xml
opendaylight/distribution/opendaylight/src/main/resources/configuration/logback.xml
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/adsal/FlowServiceAdapter.java
opendaylight/md-sal/compatibility/sal-compatibility/src/main/java/org/opendaylight/controller/sal/compatibility/adsal/FlowStatisticsAdapter.java
opendaylight/md-sal/model/model-inventory/src/main/yang/opendaylight-inventory.yang
opendaylight/md-sal/pom.xml
opendaylight/md-sal/sal-binding-broker/pom.xml
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/ForwardedBackwardsCompatibleDataBroker.java
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/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/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/util/MapUtils.java [deleted file]
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
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/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-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/connect/dom/CrossBrokerRpcTest.java
opendaylight/md-sal/sal-binding-dom-it/src/test/java/org/opendaylight/controller/sal/binding/test/connect/dom/DOMRpcServiceTestBugfix560.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-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-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-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/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/SchemaAwareRpcBroker.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-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/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/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/NetconfToRpcRequestTest.java [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-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
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
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/XmlToCompositeNodeReader.java
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/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/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/MultipleEqualNamesForDataNodesTest.java
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/full-versions/test-module/test-module
opendaylight/md-sal/sal-test-model/pom.xml
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-test-routed-rpc.yang [new file with mode: 0644]
opendaylight/md-sal/samples/toaster-consumer/src/main/java/org/opendaylight/controller/sample/kitchen/impl/KitchenServiceImpl.java
opendaylight/md-sal/samples/toaster-provider/src/main/java/org/opendaylight/controller/sample/toaster/provider/OpendaylightToaster.java
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/test/java/org/opendaylight/controller/netconf/confignetconfconnector/operations/editconfig/MergeEditConfigStrategyTest.java [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-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/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/sal/api/src/main/java/org/opendaylight/controller/sal/packet/IEEE8021Q.java
pom.xml

index 60286175c18e0a6455dedcc19f23018216b406dd..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>
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
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 fe456f3f8ebe6f6237352cb09f5b6a7dc8056398..4efcada2f8ed9ef7fd0d2774c5b41cfb6e265ba1 100644 (file)
@@ -695,6 +695,8 @@ public class ArpHandler implements IHostFinder, IListenDataPacket, ICacheUpdateA
             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);
         }
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 bf84183b75b755b9099374d3d2365432a9621288..163c64ed520bb1782bf0d1778f087913f0a4b86a 100644 (file)
@@ -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>
         <artifactId>sal-restconf-broker</artifactId>
         <version>${mdsal.version}</version>
       </dependency>
+      <dependency>
+        <groupId>org.opendaylight.controller</groupId>
+        <artifactId>sal-test-model</artifactId>
+        <version>${mdsal.version}</version>
+      </dependency>
 
       <!-- SAL Extension bundles -->
       <dependency>
       <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>
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 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 4cf766a8120ef4c559eb45a9883c7583c1983f8b..bc188515538485f9a13f87366a281a893a5984ae 100644 (file)
@@ -9,6 +9,7 @@ package org.opendaylight.controller.config.util;
 
 import java.util.Map;
 import java.util.Set;
+
 import javax.management.Attribute;
 import javax.management.InstanceAlreadyExistsException;
 import javax.management.InstanceNotFoundException;
@@ -17,6 +18,7 @@ import javax.management.JMX;
 import javax.management.MBeanException;
 import javax.management.MBeanServer;
 import javax.management.ObjectName;
+
 import org.opendaylight.controller.config.api.ConflictingVersionException;
 import org.opendaylight.controller.config.api.ValidationException;
 import org.opendaylight.controller.config.api.jmx.CommitStatus;
@@ -270,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 a84a743..0000000
+++ /dev/null
@@ -1,28 +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-util/${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 a8a4c87a4eaa9f28a3e6656390bb27accbdd1f67..66bb01f051fa1042e9fc08d4019a236f1e07bb04 100644 (file)
@@ -39,7 +39,6 @@
     <module>shutdown-impl</module>
     <module>netconf-config-dispatcher</module>
     <module>config-module-archetype</module>
-    <module>feature</module>
   </modules>
 
   <dependencies>
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 221bfa78e8972822b43894cd039b306456839e3b..4ef0b8e86bf926062ff0e7071775efd79d0f531a 100644 (file)
       <type>kar</type>
       <scope>runtime</scope>
     </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>features-odl-protocol-framework</artifactId>
+      <version>${protocol-framework.version}</version>
+      <classifier>features</classifier>
+      <type>xml</type>
+      <scope>runtime</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.opendaylight.controller</groupId>
+      <artifactId>netconf-features</artifactId>
+      <version>${netconf.version}</version>
+      <classifier>features</classifier>
+      <type>xml</type>
+      <scope>runtime</scope>
+    </dependency>
     <dependency>
       <groupId>org.opendaylight.controller</groupId>
       <artifactId>config-features</artifactId>
       <type>xml</type>
       <scope>runtime</scope>
     </dependency>
-    <dependency>
-      <groupId>org.opendaylight.yangtools</groupId>
-      <artifactId>features-yangtools</artifactId>
-      <version>${yangtools.version}</version>
-      <classifier>features</classifier>
-      <type>xml</type>
-      <scope>runtime</scope>
-    </dependency>
   </dependencies>
 
   <build>
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 f4bf4835796aa5536d8cc9b7f4c4bdeda826a373..b2fc3cb386ffa4525fb42dd3fae685c7b6a39e97 100644 (file)
@@ -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 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"/-->
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 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 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 d3f6d2d005a93ce5ffa0c30cddd8190976bc6309..1cfd5a66399eb4991fedb3cb59098aa62e1d8249 100644 (file)
@@ -63,9 +63,6 @@
     <!--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>
index 8e286391deb31fb1d81ad56be4b69e8c509df229..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>
index 8723fdf82a931b846482914fd5e85e69e8c10cf1..d275c838f25adacc554898b36db32aa47b7cfaa6 100644 (file)
@@ -8,12 +8,11 @@
 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.HashSet;
 import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
 import java.util.Map.Entry;
+import java.util.Set;
 
 import javax.annotation.Nullable;
 
@@ -21,13 +20,13 @@ import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizat
 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;
@@ -40,6 +39,9 @@ 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;
@@ -48,7 +50,7 @@ import org.slf4j.LoggerFactory;
 import com.google.common.base.Function;
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
-import com.google.common.base.Supplier;
+import com.google.common.base.Predicate;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 
@@ -99,8 +101,8 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
                 if (child instanceof AugmentationNode) {
                     ImmutableList<PathArgument> childArgs = ImmutableList.<PathArgument> builder()
                             .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);
+                    org.opendaylight.yangtools.yang.data.api.InstanceIdentifier childPath = org.opendaylight.yangtools.yang.data.api.InstanceIdentifier
+                            .create(childArgs);
                     return toDOMEntry(childPath, child);
                 }
             }
@@ -121,7 +123,7 @@ 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.getPathArguments());
         // Used instance-identifier codec do not support serialization of last
@@ -138,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
@@ -188,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 {
@@ -207,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;
@@ -218,7 +220,7 @@ 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.getPathArguments()) {
             current = current.getChild(arg);
@@ -234,10 +236,9 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
     }
 
     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);
+            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)
@@ -263,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();
@@ -290,27 +291,155 @@ 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 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 processed;
+        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.getPathArguments()) {
@@ -319,7 +448,7 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
                 foundPosition = position;
             }
         }
-        if (foundPosition > 0) {
+        if (foundPosition > 0 && foundPosition > parentSize) {
             Iterable<PathArgument> shortened = Iterables.limit(normalized.getPathArguments(), foundPosition);
             return org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.create(shortened);
         }
@@ -348,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);
     }
@@ -418,26 +491,26 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
 
     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++;
             }
-
         }
         return count;
     }
 
     private static int getAugmentationCount(final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier potential) {
         int count = 0;
-        for(PathArgument arg : potential.getPathArguments()) {
-            if(arg instanceof AugmentationIdentifier) {
+        for (PathArgument arg : potential.getPathArguments()) {
+            if (arg instanceof AugmentationIdentifier) {
                 count++;
             }
         }
         return count;
     }
 
-    public Function<Optional<NormalizedNode<?, ?>>, Optional<DataObject>>  deserializeFunction(final InstanceIdentifier<?> path) {
+    public Function<Optional<NormalizedNode<?, ?>>, Optional<DataObject>> deserializeFunction(
+            final InstanceIdentifier<?> path) {
         return new DeserializeFunction(this, path);
     }
 
@@ -475,7 +548,8 @@ public class BindingToNormalizedNodeCodec implements SchemaContextListener {
     /**
      * Returns an default object according to YANG schema for supplied path.
      *
-     * @param path DOM Path
+     * @param path
+     *            DOM Path
      * @return Node with defaults set on.
      */
     public NormalizedNode<?, ?> getDefaultNodeFor(final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier path) {
index 1c6447a4e741615b714657c9356dc6b756fe44c0..b45450ae3a54554243fe6a3c5097f362fb82779b 100644 (file)
@@ -33,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;
@@ -42,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;
@@ -163,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());
             }
         });
 
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 542dfa7e7bca61a0fc4ff33e31239c3c3872e73b..952d84d885c41e73fe2312bf22c723f62cc44b35 100644 (file)
@@ -7,6 +7,15 @@
  */
 package org.opendaylight.controller.sal.binding.impl;
 
+import static com.google.common.base.Preconditions.checkState;
+
+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,15 +37,6 @@ 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<?>> {
@@ -60,19 +60,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,7 +92,7 @@ public class RpcProviderRegistryImpl implements //
 
     @SuppressWarnings("unchecked")
     @Override
-    public final <T extends RpcService> T getRpcService(Class<T> type) {
+    public final <T extends RpcService> T getRpcService(final Class<T> type) {
 
         T potentialProxy = (T) publicProxies.get(type);
         if (potentialProxy != null) {
@@ -115,8 +115,8 @@ public class RpcProviderRegistryImpl implements //
         }
     }
 
-    @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 +140,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 +151,7 @@ public class RpcProviderRegistryImpl implements //
 
     }
 
-    private void notifyListenersRoutedCreated(RpcRouter<?> router) {
+    private void notifyListenersRoutedCreated(final RpcRouter<?> router) {
 
         for (ListenerRegistration<RouterInstantiationListener> listener : routerInstantiationListener) {
             try {
@@ -164,7 +164,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 +176,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 +187,7 @@ public class RpcProviderRegistryImpl implements //
         return rpcFactory;
     }
 
-    public void setRpcFactory(RuntimeCodeGenerator rpcFactory) {
+    public void setRpcFactory(final RuntimeCodeGenerator rpcFactory) {
         this.rpcFactory = rpcFactory;
     }
 
@@ -194,7 +195,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);
     }
 
@@ -209,12 +210,12 @@ public class RpcProviderRegistryImpl implements //
 
         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()) {
@@ -245,7 +246,7 @@ public class RpcProviderRegistryImpl implements //
         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 6e4b2d8d99b69c2f417fd96a6532c404e37b8b0d..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.RpcRegistrationListener;
-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.CompositeObjectRegistration;
-import org.opendaylight.yangtools.concepts.CompositeObjectRegistration.CompositeObjectRegistrationBuilder;
 import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.concepts.ObjectRegistration;
 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.base.Optional;
-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;
 
@@ -150,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
@@ -195,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;
     }
@@ -280,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() {
@@ -288,6 +139,7 @@ public class BindingIndependentConnector implements //
 
     protected void setBindingDataService(final DataProviderService baDataService) {
         this.baDataService = baDataService;
+        domToBindingCommitHandler.setBindingAwareDataService(this.baDataService);
     }
 
     public RpcProviderRegistry getRpcRegistry() {
@@ -323,10 +175,12 @@ 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");
-            final DomToBindingRpcForwardingManager biFwdManager = new DomToBindingRpcForwardingManager();
+            final DomToBindingRpcForwardingManager biFwdManager = new DomToBindingRpcForwardingManager(mappingService, biRpcRegistry, baRpcRegistry);
 
             domToBindingRpcManager = baRpcRegistry.registerRouteChangeListener(biFwdManager);
             biRpcRegistry.addRpcRegistrationListener(biFwdManager);
@@ -334,6 +188,7 @@ public class BindingIndependentConnector implements //
                 baRpcRegistryImpl = (RpcProviderRegistryImpl) baRpcRegistry;
                 baRpcRegistryImpl.registerRouterInstantiationListener(domToBindingRpcManager.getInstance());
                 baRpcRegistryImpl.registerGlobalRpcRegistrationListener(domToBindingRpcManager.getInstance());
+                biFwdManager.setRegistryImpl(baRpcRegistryImpl);
             }
             rpcForwarding = true;
         }
@@ -341,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
@@ -364,458 +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) {
-
-            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, RpcRegistrationListener {
-
-        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).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 (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;
-        }
-
-        @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) {
-
-        }
-    }
-
-    private class DomToBindingRpcForwarder implements RpcImplementation, InvocationHandler {
-
-        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;
-
-        public DomToBindingRpcForwarder(final Class<? extends RpcService> service) {
-            this.rpcServiceType = new WeakReference<Class<? extends RpcService>>(service);
-            this.supportedRpcs = mappingService.getRpcQNamesFor(service);
-
-            Class<?> cls = rpcServiceType.get();
-            ClassLoader clsLoader = cls.getClassLoader();
-            proxy =(RpcService) Proxy.newProxyInstance(clsLoader, new Class<?>[] { cls }, this);
-            createStrategies();
-        }
-
-        /**
-         * Constructor for Routed RPC Forwareder.
-         *
-         * @param service
-         * @param context
-         */
-        public DomToBindingRpcForwarder(final Class<? extends RpcService> service,
-                                        final Class<? extends BaseIdentity> context) {
-            this(service);
-            Builder<RoutedRpcRegistration> registrationsBuilder = ImmutableSet
-                    .<org.opendaylight.controller.sal.core.api.Broker.RoutedRpcRegistration> 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() {
-            try {
-                for (QName rpc : supportedRpcs) {
-                    RpcInvocationStrategy strategy = createInvocationStrategy(rpc, rpcServiceType.get());
-                    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;
-                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) 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;
-               }
-            }
-        }
     }
 
     public boolean isRpcForwarding() {
@@ -842,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..ee06283
--- /dev/null
@@ -0,0 +1,99 @@
+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;
+
+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(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/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..395af8f
--- /dev/null
@@ -0,0 +1,135 @@
+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;
+
+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(DataProviderService baDataService) {
+        this.baDataService = baDataService;
+    }
+
+    public void setMappingService(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/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/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);
+
+
+    }
+
+}
index ad6e1a77cea9c5294852fe7524c5ef6606c65d95..43e951423c0a2bfdecef87969abd01c51816d28e 100644 (file)
@@ -12,42 +12,29 @@ import static org.junit.Assert.assertEquals;
 import java.util.concurrent.ExecutionException;
 
 import org.junit.Test;
-import org.opendaylight.controller.md.sal.binding.api.DataBroker;
 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.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.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.NodeBuilder;
-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.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 AbstractDataServiceTest {
+public class WriteTransactionTest extends AbstractDataBrokerTest {
 
-    private DataBroker dataBroker;
-
-    private static final InstanceIdentifier<Nodes> NODES_PATH = InstanceIdentifier.create(Nodes.class);
-
-    private static final NodeKey NODE_KEY = new NodeKey(new NodeId("foo"));
-
-    private static final InstanceIdentifier<Node> NODE_PATH = NODES_PATH.child(Node.class, NODE_KEY);
-
-    @Override
-    public void setUp() {
-        super.setUp();
-
-        dataBroker = testContext.getDataBroker();
-    }
+    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 = dataBroker.newWriteOnlyTransaction();
-        writeTx.put(LogicalDatastoreType.OPERATIONAL, NODES_PATH, new NodesBuilder().build());
-        writeTx.put(LogicalDatastoreType.OPERATIONAL, NODE_PATH, new NodeBuilder().setKey(NODE_KEY).build());
+        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 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 8ba709ad30c461e5b69c50b0d34c9b2d78579fbb..f5e902c775a9320857e9665ff79792f71b0a628c 100644 (file)
@@ -9,9 +9,6 @@ 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;
 
@@ -41,36 +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
@@ -86,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;
@@ -108,6 +97,7 @@ public class BindingTestContext implements AutoCloseable {
 
     private BackwardsCompatibleDataBroker biCompatibleBroker;
 
+    @SuppressWarnings("deprecation")
     private DataProviderService baData;
 
     private DOMDataBroker newDOMDataBroker;
@@ -128,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();
@@ -213,6 +184,7 @@ public class BindingTestContext implements AutoCloseable {
 
     private ProviderSession createMockContext() {
 
+        @SuppressWarnings("deprecation")
         final ClassToInstanceMap<BrokerService> domBrokerServices = ImmutableClassToInstanceMap
                 .<BrokerService> builder()
                 //
@@ -277,47 +249,14 @@ 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() {
@@ -363,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();
     }
index 75d48612b831be05ad4a36ed244c2a6a1ff3db10..bddbc4e95400965da7533b3d66dfee72fa6c3710 100644 (file)
@@ -54,7 +54,6 @@ public class DOMCodecBug02Test extends AbstractDataServiceTest {
 
         baDataService = testContext.getBindingDataBroker();
         biDataService = testContext.getDomDataBroker();
-        dataStore = testContext.getDomDataStore();
         mappingService = testContext.getBindingToDomMappingService();
     };
 
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);
     }
 
index c87b93625f4e4a0bc653b8e169eec56fe244f22f..0c123ebe66aac8a77de4bc62b17920d6d0003a93 100644 (file)
@@ -25,7 +25,6 @@ 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.common.util.Rpcs;
 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;
@@ -39,6 +38,7 @@ 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;
@@ -135,8 +135,8 @@ public class DOMRpcServiceTestBugfix560 {
             public ListenableFuture<RpcResult<CompositeNode>> invokeRpc(
                     final QName rpc, final CompositeNode input) {
 
-                return Futures.immediateFuture(Rpcs
-                        .<CompositeNode> getRpcResult(true));
+                return Futures.immediateFuture(RpcResultBuilder
+                        .<CompositeNode> success().build());
             }
 
             @Override
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 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 2b9694bed71d87dfb8d48e04024b94f619e5c049..617697710449b32602682802d10dd2022f551ee2 100644 (file)
@@ -10,11 +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;
@@ -52,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() {
@@ -88,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
@@ -127,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
@@ -141,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
@@ -160,8 +172,8 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
     private static abstract class CompositeNodeNormalizationOperation<T extends PathArgument> extends
     DataNormalizationOperation<T> {
 
-        protected CompositeNodeNormalizationOperation(final T identifier) {
-            super(identifier);
+        protected CompositeNodeNormalizationOperation(final T identifier, final DataSchemaNode schema) {
+            super(identifier,schema);
         }
 
         @SuppressWarnings({ "rawtypes", "unchecked" })
@@ -226,8 +238,8 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
         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<>();
@@ -283,7 +295,7 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
         private final List<QName> keyDefinition;
 
         protected ListItemNormalization(final NodeIdentifierWithPredicates identifier, final ListSchemaNode schema) {
-            super(identifier, schema);
+            super(identifier, schema,schema);
             keyDefinition = schema.getKeyDefinition();
         }
 
@@ -324,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
@@ -342,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
@@ -360,8 +372,8 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
     private static abstract class MixinNormalizationOp<T extends PathArgument> extends
     CompositeNodeNormalizationOperation<T> {
 
-        protected MixinNormalizationOp(final T identifier) {
-            super(identifier);
+        protected MixinNormalizationOp(final T identifier, final DataSchemaNode schema) {
+            super(identifier,schema);
         }
 
         @Override
@@ -395,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);
         }
 
@@ -430,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
@@ -479,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);
         }
@@ -519,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);
         }
 
@@ -577,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();
 
@@ -617,8 +629,8 @@ public abstract class DataNormalizationOperation<T extends PathArgument> impleme
 
     private static class AnyXmlNormalization extends DataNormalizationOperation<NodeIdentifier> {
 
-        protected AnyXmlNormalization( final NodeIdentifier identifier ) {
-            super( identifier );
+        protected AnyXmlNormalization( final AnyXmlSchemaNode schema) {
+            super( new NodeIdentifier(schema.getQName()), schema);
         }
 
         @Override
@@ -746,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 113d3dc9f762ec1f0f2f6d4c7307ae3f04e0d19b..e2a960a67aae708d34a4145479b8797fe535d0d6 100644 (file)
@@ -9,12 +9,6 @@ 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;
@@ -38,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;
@@ -72,6 +72,16 @@ public class DataNormalizer {
         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(
             final Map.Entry<InstanceIdentifier, CompositeNode> legacy) {
         return toNormalized(legacy.getKey(), legacy.getValue());
@@ -120,7 +130,7 @@ public class DataNormalizer {
         DataNormalizationOperation<?> currentOp = operation;
         for (PathArgument normalizedArg : normalized.getPathArguments()) {
             currentOp = currentOp.getChild(normalizedArg);
-            if(!currentOp.isMixin()) {
+            if (!currentOp.isMixin()) {
                 legacyArgs.add(normalizedArg);
             }
         }
@@ -134,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;
     }
@@ -169,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 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) {
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();
         }
 
         /**
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 32139308b11230b806467f95d078c1608077a1f6..7bc827dcb0329d41825638efa9b5d1748ac0c83c 100644 (file)
@@ -14,10 +14,10 @@ import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 
-import com.google.common.base.Preconditions;
 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;
@@ -25,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;
@@ -33,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;
@@ -53,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<>();
 
@@ -65,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;
@@ -75,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;
     }
 
@@ -83,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;
     }
 
@@ -92,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;
@@ -114,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);
@@ -133,13 +127,13 @@ 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);
         final RpcImplementation previous = implementations.putIfAbsent(rpcType, implementation);
         Preconditions.checkState(previous == null, "Rpc %s is already registered.",rpcType);
@@ -147,7 +141,7 @@ public class SchemaAwareRpcBroker implements RpcRouter, Identifiable<String>, Ro
         return reg;
     }
 
-    private void notifyRpcAdded(QName rpcType) {
+    private void notifyRpcAdded(final QName rpcType) {
         for (ListenerRegistration<RpcRegistrationListener> listener : rpcRegistrationListeners) {
             try {
                 listener.getInstance().onRpcImplementationAdded(rpcType);
@@ -158,12 +152,8 @@ public class SchemaAwareRpcBroker implements RpcRouter, Identifiable<String>, Ro
         }
     }
 
-    private boolean isRoutedRpc(RpcDefinition definition) {
-        return getRoutingStrategy(definition) instanceof RoutedRpcStrategy;
-    }
-
     @Override
-    public ListenerRegistration<RpcRegistrationListener> addRpcRegistrationListener(RpcRegistrationListener listener) {
+    public ListenerRegistration<RpcRegistrationListener> addRpcRegistrationListener(final RpcRegistrationListener listener) {
         ListenerRegistration<RpcRegistrationListener> reg = rpcRegistrationListeners.register(listener);
         for (QName impl : implementations.keySet()) {
             listener.onRpcImplementationAdded(impl);
@@ -182,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) {
@@ -201,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();
@@ -215,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())) {
@@ -225,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);
-    }
-
-    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;
-        }
+    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 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) {
@@ -451,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) {
@@ -473,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 {
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 9fa68eeea6f87c7f1a4cb4634b0759a61cc2f83e..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;
@@ -26,16 +25,14 @@ import org.opendaylight.controller.netconf.client.conf.NetconfClientConfiguratio
 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;
 
@@ -86,9 +83,9 @@ public class NetconfDeviceCommunicator implements NetconfClientSessionListener,
                                            final NetconfClientConfiguration config) {
         if(config instanceof NetconfReconnectingClientConfiguration) {
             dispatch.createReconnectingClient((NetconfReconnectingClientConfiguration) config);
+        } else {
+            dispatch.createClient(config);
         }
-
-        dispatch.createClient(config);
     }
 
     private void tearDown( String reason ) {
@@ -140,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
@@ -208,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;
             }
 
@@ -220,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 8b6ac7d5671643cdad49babaecd0026de338f9c6..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;
@@ -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 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 1737b8234a610267c9aa7f82eddd7a1f9912f502..0ef76d330dbab15d908401a695e61ba25b0d1802 100644 (file)
@@ -33,14 +33,13 @@ 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;
@@ -211,8 +210,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 f9e6239bed3dd4ed03cceacbfb0cb8fde1228bd9..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;
@@ -90,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();
         }
     }
 
@@ -114,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 0ea3d6a35ac74c873d3965a3a1d90e7c514aa99b..0aeec64690d971abfa7f74b1bd58385e669163fe 100644 (file)
@@ -27,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;
@@ -140,9 +140,14 @@ public class NetconfMessageTransformUtil {
             }
         }
 
-        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( final NetconfDocumentedException.ErrorSeverity severity ) {
@@ -181,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 c1b9f7b47ba8b8009b620655a729703e1809346f..ec2a820daab098618461d617155fa6804a369326 100644 (file)
@@ -27,7 +27,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 +37,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 +64,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";
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/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
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 2f11d8ed7d72d40282c37ac437de530351efc151..a6c4ea5ab8d7877930983ed782d4cbc318def278 100644 (file)
@@ -25,23 +25,20 @@ 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.
+ * 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)}
+ * <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><b>/operations</b> - {@link #invokeRpc(String, CompositeNode)} {@link #invokeRpc(String, CompositeNode)}
  * <li>/version (field)
  * </ul>
  * </ul>
@@ -93,7 +90,8 @@ public interface RestconfService {
     @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);
+    public StructuredData invokeRpc(@Encoded @PathParam("identifier") String identifier, CompositeNode payload,
+            @Context UriInfo uriInfo);
 
     @POST
     @Path("/operations/{identifier:.+}")
@@ -114,7 +112,8 @@ public interface RestconfService {
     @Path("/operational/{identifier:.+}")
     @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 uriInfo);
+    public StructuredData readOperationalData(@Encoded @PathParam("identifier") String identifier,
+            @Context UriInfo uriInfo);
 
     @PUT
     @Path("/config/{identifier:.+}")
index f3b61de45768aaf63a992e883c0cbf19b25fec74..a784be2adca3128cfc74134a3dcd9267528f5538 100644 (file)
@@ -22,8 +22,8 @@ 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."
+ * 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 {
index 85b4b2dee071aff3be08fb82b11690a8793d7014..4b4cef9f70873b2c34858de93e529d91d0ea7a5e 100644 (file)
@@ -11,16 +11,13 @@ 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;
@@ -80,100 +77,95 @@ class JsonMapper {
         writer.endObject();
     }
 
-    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);
 
         final Set<QName> foundLists = new HashSet<>();
 
-        Set<DataSchemaNode> parentSchemaChildNodes = parentSchema == null ?
-                Collections.<DataSchemaNode>emptySet() : parentSchema.getChildNodes();
-
+        Set<DataSchemaNode> parentSchemaChildNodes = parentSchema == null ? Collections.<DataSchemaNode> emptySet()
+                : parentSchema.getChildNodes();
 
-                for (Node<?> child : parent.getValue()) {
-                    DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchemaChildNodes);
+        for (Node<?> child : parent.getValue()) {
+            DataSchemaNode childSchema = findFirstSchemaForNode(child, parentSchemaChildNodes);
 
-                    if (childSchema == null) {
-                        // Node may not conform to schema or allows "anyxml" - we'll process it.
+            if (childSchema == null) {
+                // Node may not conform to schema or allows "anyxml" - we'll process it.
 
-                        LOG.debug("No schema found for data node \"{}\"", child.getNodeType());
+                LOG.debug("No schema found for data node \"{}\"", child.getNodeType());
 
-                        if( !foundLists.contains( child.getNodeType() ) ) {
-                            handleNoSchemaFound( writer, child, parent );
+                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.
+                    // 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 - %s", child.getNodeType());
-                        writeContainer(writer, (CompositeNode) child, (ContainerSchemaNode) childSchema);
-                    } else if (childSchema instanceof ListSchemaNode) {
-                        if (!foundLists.contains( child.getNodeType() ) ) {
-                            Preconditions.checkState(child instanceof CompositeNode,
-                                    "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 (!foundLists.contains( child.getNodeType() ) ) {
-                            Preconditions.checkState(child instanceof SimpleNode<?>,
-                                    "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 - %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.");
-                    }
+                    foundLists.add(child.getNodeType());
+                }
+            } else if (childSchema instanceof ContainerSchemaNode) {
+                Preconditions.checkState(child instanceof CompositeNode,
+                        "Data representation of Container should be CompositeNode - %s", child.getNodeType());
+                writeContainer(writer, (CompositeNode) child, (ContainerSchemaNode) childSchema);
+            } else if (childSchema instanceof ListSchemaNode) {
+                if (!foundLists.contains(child.getNodeType())) {
+                    Preconditions.checkState(child instanceof CompositeNode,
+                            "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 (!foundLists.contains(child.getNodeType())) {
+                    Preconditions.checkState(child instanceof SimpleNode<?>,
+                            "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 - %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.");
+            }
+        }
     }
 
     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<?> ) {
-            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 );
+    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() );
+                for (SimpleNode<?> leafNode : nodeLeafList) {
+                    writeValue(writer, leafNode.getValue());
                 }
 
                 writer.endArray();
             }
         } else { // CompositeNode
-            Preconditions.checkState( node instanceof CompositeNode,
+            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 );
+            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);
             }
         }
     }
@@ -195,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();
 
@@ -235,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)) {
-            LOG.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) {
@@ -292,7 +286,8 @@ class JsonMapper {
         }
     }
 
-    private static 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('/');
@@ -327,12 +322,11 @@ class JsonMapper {
         result.append(identityValue.getValue());
     }
 
-    private static 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();
-        LOG.debug("Value of {}:{} is not instance of {} but is {}",
-                baseType.getQName().getNamespace(), baseType.getQName().getLocalName(),
-                requiredType.getClass(), 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 {
@@ -348,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) {
index 211e7e818a90bf2b3af9af67a5c693d86fb32ab7..2f3499e26968e17e9fa5f662ab66063965657815 100644 (file)
@@ -28,32 +28,30 @@ import org.slf4j.LoggerFactory;
 
 @Provider
 @Consumes({ Draft02.MediaTypes.DATA + RestconfService.JSON, Draft02.MediaTypes.OPERATION + RestconfService.JSON,
-    MediaType.APPLICATION_JSON })
+        MediaType.APPLICATION_JSON })
 public enum JsonToCompositeNodeProvider implements MessageBodyReader<CompositeNode> {
     INSTANCE;
 
     private final static Logger LOG = LoggerFactory.getLogger(JsonToCompositeNodeProvider.class);
 
     @Override
-    public boolean isReadable(final Class<?> type, final Type genericType,
-                              final Annotation[] annotations, final MediaType mediaType) {
+    public boolean isReadable(final Class<?> type, final Type genericType, final Annotation[] annotations,
+            final MediaType mediaType) {
         return true;
     }
 
     @Override
     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 {
+            final Annotation[] annotations, final MediaType mediaType,
+            final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException,
+            WebApplicationException {
         try {
             return JsonToCompositeNodeReader.read(entityStream);
         } catch (Exception e) {
-            LOG.debug( "Error parsing json input", e);
+            LOG.debug("Error parsing json input", e);
 
-            throw new RestconfDocumentedException(
-                    "Error parsing input: " + e.getMessage(),
-                    ErrorType.PROTOCOL, ErrorTag.MALFORMED_MESSAGE);
+            throw new RestconfDocumentedException("Error parsing input: " + e.getMessage(), ErrorType.PROTOCOL,
+                    ErrorTag.MALFORMED_MESSAGE);
         }
     }
 }
index 082675b6d135e4fa3be05017a34a2ff584da9008..5fbb60555814f11267bba0012a650adf4b040b0d 100644 (file)
@@ -13,14 +13,12 @@ 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.Map.Entry;
 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;
@@ -38,12 +36,10 @@ class JsonToCompositeNodeReader {
 
     }
 
-    public static CompositeNodeWrapper read(final InputStream entityStream)
-                                                      throws UnsupportedFormatException {
+    public static CompositeNodeWrapper read(final InputStream entityStream) throws UnsupportedFormatException {
         JsonParser parser = new JsonParser();
 
-        JsonElement rootElement = parser.parse(new JsonReader(
-                                                    new InputStreamReader(entityStream)));
+        JsonElement rootElement = parser.parse(new JsonReader(new InputStreamReader(entityStream)));
         if (rootElement.isJsonNull()) {
             // no content, so return null to indicate no input
             return null;
@@ -53,8 +49,7 @@ class JsonToCompositeNodeReader {
             throw new UnsupportedFormatException("Root element of Json has to be Object");
         }
 
-        Set<Entry<String, JsonElement>> entrySetsOfRootJsonObject =
-                                                  rootElement.getAsJsonObject().entrySet();
+        Set<Entry<String, JsonElement>> entrySetsOfRootJsonObject = rootElement.getAsJsonObject().entrySet();
         if (entrySetsOfRootJsonObject.size() != 1) {
             throw new UnsupportedFormatException("Json Object should contain one element");
         }
@@ -81,8 +76,7 @@ class JsonToCompositeNodeReader {
                 "First element in Json Object has to be \"Object\" or \"Array with one Object element\". Other scenarios are not supported yet.");
     }
 
-    private static CompositeNodeWrapper createStructureWithRoot(final String rootObjectName,
-                                                                final 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()) {
@@ -92,7 +86,7 @@ class JsonToCompositeNodeReader {
     }
 
     private static void addChildToParent(final String childName, final JsonElement childType,
-                                         final CompositeNodeWrapper parent) {
+            final CompositeNodeWrapper parent) {
         if (childType.isJsonObject()) {
             CompositeNodeWrapper child = new CompositeNodeWrapper(getNamespaceFor(childName),
                     getLocalNameFor(childName));
index cd263d3c55b0a56ce40feca32690749bd489ed6e..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;
@@ -106,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;
                     }
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 0854ca71673465e76e7659bfa9479afc3fb1962f..63a5b1b54055a81cd3f8f3f736365c4e99e1d8b8 100644 (file)
@@ -21,7 +21,6 @@ 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;
@@ -29,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;
@@ -46,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;
@@ -63,24 +60,23 @@ import org.w3c.dom.Document;
 import org.xml.sax.InputSource;
 
 /**
- * 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
 
@@ -88,169 +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(null);
 
         Object responseBody = null;
         try {
             ByteArrayOutputStream outStream = new ByteArrayOutputStream();
-            JsonWriter writer = new JsonWriter(new OutputStreamWriter( outStream, Charsets.UTF_8));
-            writer.setIndent( "    " );
+            JsonWriter writer = new JsonWriter(new OutputStreamWriter(outStream, Charsets.UTF_8));
+            writer.setIndent("    ");
 
-            jsonMapper.write( writer, errorsNode, errorsSchemaNode);
+            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, \"{}\", as XML", errorInfo, e);
+            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
@@ -258,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 063d2f51afffdd0c7094d7363d95795182b5cd8e..933ed0f849e7171b7c16c423c5462aa8de1bb25a 100644 (file)
@@ -30,24 +30,27 @@ import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 
 @Provider
 @Produces({ Draft02.MediaTypes.API + RestconfService.JSON, Draft02.MediaTypes.DATA + RestconfService.JSON,
-    Draft02.MediaTypes.OPERATION + RestconfService.JSON, MediaType.APPLICATION_JSON })
+        Draft02.MediaTypes.OPERATION + RestconfService.JSON, MediaType.APPLICATION_JSON })
 public enum StructuredDataToJsonProvider implements MessageBodyWriter<StructuredData> {
     INSTANCE;
 
     @Override
-    public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) {
+    public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations,
+            final MediaType mediaType) {
         return type.equals(StructuredData.class);
     }
 
     @Override
-    public long getSize(final StructuredData t, final Class<?> type, final Type genericType, final Annotation[] annotations, final 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(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 {
+    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);
index 3a235ced858a4be9af6dc24d9152602ff806bc09..703a2a463476bcfd4704c34419cc17c73a6af3fc 100644 (file)
@@ -39,7 +39,7 @@ import org.w3c.dom.Document;
 
 @Provider
 @Produces({ Draft02.MediaTypes.API + RestconfService.XML, Draft02.MediaTypes.DATA + RestconfService.XML,
-    Draft02.MediaTypes.OPERATION + RestconfService.XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
+        Draft02.MediaTypes.OPERATION + RestconfService.XML, MediaType.APPLICATION_XML, MediaType.TEXT_XML })
 public enum StructuredDataToXmlProvider implements MessageBodyWriter<StructuredData> {
     INSTANCE;
 
@@ -67,19 +67,22 @@ public enum StructuredDataToXmlProvider implements MessageBodyWriter<StructuredD
     };
 
     @Override
-    public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType) {
+    public boolean isWriteable(final Class<?> type, final Type genericType, final Annotation[] annotations,
+            final MediaType mediaType) {
         return type.equals(StructuredData.class);
     }
 
     @Override
-    public long getSize(final StructuredData t, final Class<?> type, final Type genericType, final Annotation[] annotations, final 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(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 {
+    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);
@@ -94,8 +97,7 @@ public enum StructuredDataToXmlProvider implements MessageBodyWriter<StructuredD
                 trans.setOutputProperty(OutputKeys.INDENT, "no");
             }
         } catch (RuntimeException e) {
-            throw new RestconfDocumentedException(e.getMessage(), ErrorType.TRANSPORT,
-                    ErrorTag.OPERATION_FAILED);
+            throw new RestconfDocumentedException(e.getMessage(), ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED);
         }
 
         // FIXME: BUG-1281: eliminate the intermediate Document
@@ -104,8 +106,7 @@ public enum StructuredDataToXmlProvider implements MessageBodyWriter<StructuredD
             trans.transform(new DOMSource(domTree), new StreamResult(entityStream));
         } catch (TransformerException e) {
             LOG.error("Error during translation of Document to OutputStream", e);
-            throw new RestconfDocumentedException(e.getMessage(), ErrorType.TRANSPORT,
-                    ErrorTag.OPERATION_FAILED);
+            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 7d0690cdc27e0a6754a354f187b88317e558720f..413823f52081ebb235cc33db3530e2bdbbf7c149 100644 (file)
@@ -36,8 +36,7 @@ public class XmlToCompositeNodeReader {
     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.
+        // see if there is any content being provided.
         entityStream = getMarkableStream(entityStream);
 
         if (isInputStreamEmpty(entityStream)) {
@@ -103,9 +102,8 @@ public class XmlToCompositeNodeReader {
     }
 
     /**
-     * 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
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 3d047dd07f53e47a4000a5de137fcc52e3affa75..ead1740ffd8befb557d85688b4a443f7edfd1134 100644 (file)
@@ -8,12 +8,13 @@
 package org.opendaylight.controller.sal.restconf.impl;
 
 import com.google.common.util.concurrent.Futures;
-import java.util.Collections;
+
 import java.util.concurrent.Future;
+
 import javax.ws.rs.core.Response.Status;
+
 import org.opendaylight.controller.md.sal.common.api.TransactionStatus;
 import org.opendaylight.controller.md.sal.common.api.data.DataReader;
-import org.opendaylight.controller.sal.common.util.Rpcs;
 import org.opendaylight.controller.sal.core.api.Broker.ConsumerSession;
 import org.opendaylight.controller.sal.core.api.data.DataBrokerService;
 import org.opendaylight.controller.sal.core.api.data.DataChangeListener;
@@ -24,15 +25,15 @@ import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
 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.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;
 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();
 
@@ -42,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;
     }
 
@@ -55,120 +56,120 @@ 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();
-        return deleteDataAtTarget(path,dataService.beginTransaction());
+        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());
+        return deleteDataAtTarget(path, mountPoint.beginTransaction());
     }
 
     private Future<RpcResult<TransactionStatus>> deleteDataAtTarget(final InstanceIdentifier path,
@@ -176,24 +177,24 @@ public class BrokerFacade implements DataReader<InstanceIdentifier, CompositeNod
         LOG.info("Delete Configuration via Restconf: {}", path);
         CompositeNode redDataAtPath = transaction.readConfigurationData(path);
         if (redDataAtPath == null) {
-            return Futures.immediateFuture(Rpcs.<TransactionStatus> getRpcResult(true, TransactionStatus.COMMITED,
-                    Collections.<RpcError> emptyList()));
+            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 69b975dab7e5ef15bb7e5ad4cf389ed55f0ef9c8..206dbdeab60a20dff4d13f9fbd3c96c68ac45b4d 100644 (file)
@@ -8,7 +8,6 @@
 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;
@@ -16,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;
index 85c8e595396e9463b8fb7bf93437510041306b09..29672f39d47c4222b297972be5b1dbeef3f1d6fe 100644 (file)
@@ -18,7 +18,6 @@ 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;
@@ -32,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;
@@ -68,7 +65,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 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();
 
@@ -95,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;
     }
 
@@ -111,162 +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();
 
-        final List<String> pathArgs = urlPathArgsDecode( SLASH_SPLITTER.split( restconfInstance ) );
-        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 static 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 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;
@@ -275,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 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();
@@ -348,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;
         }
 
@@ -405,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);
             }
         };
 
@@ -414,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;
         }
 
@@ -436,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);
             }
         };
 
@@ -445,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;
             }
         }
@@ -507,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;
                     }
                 }
@@ -543,463 +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 = 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 ||
-                node instanceof AnyXmlSchemaNode;
+    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.indexOf( ':' ) != -1 ) {
-            final Iterable<String> args = COLON_SPLITTER.split( str );
-            if( Iterables.size( args ) == 2 ) {
+    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 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 );
+    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 = 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 static List<String> urlPathArgsDecode( final Iterable<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;
             }
         }
@@ -1007,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 f93a0aea70fa311a7dd0b6f8ba520d8153f03b89..a3d44d3572106232e10edaad73e91d1b4d46039a 100644 (file)
@@ -8,10 +8,8 @@
 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;
@@ -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);
             }
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 14b8282312d7accd1ba0c912a55178c72d3f317c..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(final TypeDefinition<?> typeDefinition, final MountInstance mountPoint) {
+    public static final Codec<Object, Object> from(final TypeDefinition<?> typeDefinition,
+            final MountInstance mountPoint) {
         return new ObjectCodec(typeDefinition, mountPoint);
     }
 
@@ -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);
@@ -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);
@@ -168,7 +166,7 @@ public class RestCodec {
 
         @Override
         public IdentityValuesDTO serialize(final QName data) {
-            return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), data.getPrefix(),null);
+            return new IdentityValuesDTO(data.getNamespace().toString(), data.getLocalName(), data.getPrefix(), null);
         }
 
         @Override
@@ -234,8 +232,10 @@ public class RestCodec {
             IdentityValue valueWithNamespace = data.getValuesWithNamespaces().get(0);
             Module module = getModuleByNamespace(valueWithNamespace.getNamespace(), mountPoint);
             if (module == null) {
-                logger.info("Module by namespace '{}' of first node in instance-identiefier was not found.", 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;
             }
 
@@ -248,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();
@@ -260,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());
@@ -269,24 +271,28 @@ 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;
                     }
                 }
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 4e1adbc598be2807bccf1f0e8bd76926e141d55d..bb7547d3302f1d172c1271416c08e0895ac46398 100644 (file)
@@ -52,6 +52,8 @@ 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;
@@ -77,10 +79,11 @@ import org.opendaylight.yangtools.yang.parser.builder.impl.LeafSchemaNodeBuilder
 
 public class RestconfImpl implements RestconfService {
     private enum UriParameters {
-        PRETTY_PRINT( "prettyPrint"),
-        DEPTH( "depth");
+        PRETTY_PRINT("prettyPrint"),
+        DEPTH("depth");
 
         private String uriParameterName;
+
         UriParameters(String uriParameterName) {
             this.uriParameterName = uriParameterName;
         }
@@ -97,7 +100,7 @@ public class RestconfImpl implements RestconfService {
 
     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";
 
@@ -127,8 +130,8 @@ public class RestconfImpl implements RestconfService {
         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) {
@@ -136,11 +139,11 @@ 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,parsePrettyPrintParameter( uriInfo ));
+        return new StructuredData(modulesNode, modulesSchemaNode, null, parsePrettyPrintParameter(uriInfo));
     }
 
     @Override
@@ -149,122 +152,115 @@ public class RestconfImpl implements RestconfService {
 
         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,parsePrettyPrintParameter( uriInfo ));
+        return new StructuredData(streamsNode, streamsSchemaNode, null, parsePrettyPrintParameter(uriInfo));
     }
 
     @Override
-    public StructuredData getModules(final String identifier,final UriInfo uriInfo) {
+    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,parsePrettyPrintParameter( uriInfo ));
+        return new StructuredData(modulesNode, modulesSchemaNode, mountPoint, parsePrettyPrintParameter(uriInfo));
     }
 
     @Override
-    public StructuredData getModule(final String identifier,final UriInfo uriInfo) {
+    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,parsePrettyPrintParameter( uriInfo ));
+        return new StructuredData(moduleNode, moduleSchemaNode, mountPoint, parsePrettyPrintParameter(uriInfo));
     }
 
     @Override
     public StructuredData getOperations(final UriInfo uriInfo) {
         Set<Module> allModules = this.controllerContext.getAllModules();
-        return this.operationsFromModulesToStructuredData(allModules, null,parsePrettyPrintParameter(uriInfo));
+        return this.operationsFromModulesToStructuredData(allModules, null, parsePrettyPrintParameter(uriInfo));
     }
 
     @Override
-    public StructuredData getOperations(final String identifier,final UriInfo uriInfo) {
+    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,parsePrettyPrintParameter(uriInfo));
+        return this.operationsFromModulesToStructuredData(modules, mountPoint, parsePrettyPrintParameter(uriInfo));
     }
 
     private StructuredData operationsFromModulesToStructuredData(final Set<Module> modules,
-                                                                 final MountInstance mountPoint,boolean prettyPrint) {
+            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);
         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();
@@ -279,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,prettyPrint);
+        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;
@@ -301,95 +295,90 @@ 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");
         final DataSchemaNode descriptionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
-        streamNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(descriptionSchemaNode.getQName(), null,
+        streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(descriptionSchemaNode.getQName(), null,
                 "DESCRIPTION_PLACEHOLDER"));
 
         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
                 ((DataNodeContainer) streamSchemaNode), "replay-support");
         final DataSchemaNode replaySupportSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
-        streamNodeValues.add(NodeFactory.<Boolean>createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null,
+        streamNodeValues.add(NodeFactory.<Boolean> createImmutableSimpleNode(replaySupportSchemaNode.getQName(), null,
                 Boolean.valueOf(true)));
 
         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
                 ((DataNodeContainer) streamSchemaNode), "replay-log-creation-time");
         final DataSchemaNode replayLogCreationTimeSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
-        streamNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(),
+        streamNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(replayLogCreationTimeSchemaNode.getQName(),
                 null, ""));
 
         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
                 ((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");
         final DataSchemaNode revisionSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
         Date _revision = module.getRevision();
-        moduleNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(revisionSchemaNode.getQName(), null,
+        moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(revisionSchemaNode.getQName(), null,
                 REVISION_FORMAT.format(_revision)));
 
         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
                 ((DataNodeContainer) moduleSchemaNode), "namespace");
         final DataSchemaNode namespaceSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
-        moduleNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(namespaceSchemaNode.getQName(), null,
+        moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(namespaceSchemaNode.getQName(), null,
                 module.getNamespace().toString()));
 
         instanceDataChildrenByName = this.controllerContext.findInstanceDataChildrenByName(
                 ((DataNodeContainer) moduleSchemaNode), "feature");
         final DataSchemaNode featureSchemaNode = Iterables.getFirst(instanceDataChildrenByName, null);
         for (final FeatureDefinition feature : module.getFeatures()) {
-            moduleNodeValues.add(NodeFactory.<String>createImmutableSimpleNode(featureSchemaNode.getQName(), null,
+            moduleNodeValues.add(NodeFactory.<String> createImmutableSimpleNode(featureSchemaNode.getQName(), null,
                     feature.getQName().getLocalName()));
         }
 
@@ -402,53 +391,45 @@ public class RestconfImpl implements RestconfService {
     }
 
     @Override
-    public StructuredData invokeRpc(final String identifier, final CompositeNode payload,final UriInfo uriInfo) {
+    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(),parsePrettyPrintParameter(uriInfo));
+        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,parsePrettyPrintParameter(uriInfo));
+        return callRpc(rpc, payload, parsePrettyPrintParameter(uriInfo));
     }
 
     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
+        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,final boolean prettyPrint) {
+    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);
@@ -461,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(
+        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,prettyPrint);
+        return new StructuredData(responseData, rpc.getOutput(), null, prettyPrint);
     }
 
     @Override
     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,uriInfo);
+        return invokeRpc(identifier, (CompositeNode) null, uriInfo);
     }
 
     private RpcExecutor resolveIdentifierInInvokeRpc(final String identifier) {
@@ -493,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)
@@ -503,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;
         }
@@ -517,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) {
@@ -529,10 +504,9 @@ public class RestconfImpl implements RestconfService {
 
     }
 
-    private StructuredData callRpc(final RpcExecutor rpcExecutor, final CompositeNode payload,boolean prettyPrint) {
+    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;
@@ -555,30 +529,29 @@ 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,prettyPrint);
+        return new StructuredData(rpcResult.getResult(), rpc.getOutput(), null, prettyPrint);
     }
 
     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);
         }
     }
 
@@ -589,58 +562,54 @@ public class RestconfImpl implements RestconfService {
         MountInstance mountPoint = iiWithData.getMountPoint();
         if (mountPoint != null) {
             data = broker.readConfigurationDataBehindMountPoint(mountPoint, iiWithData.getInstanceIdentifier());
-        }
-        else {
+        } else {
             data = broker.readConfigurationData(iiWithData.getInstanceIdentifier());
         }
 
-        data = pruneDataAtDepth( data, parseDepthParameter( uriInfo ) );
-        boolean prettyPrintMode = parsePrettyPrintParameter( uriInfo );
-        return new StructuredData(data, iiWithData.getSchemaNode(), iiWithData.getMountPoint(),prettyPrintMode);
+        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( final T node, final 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( final UriInfo info ) {
-        String param = info.getQueryParameters( false ).getFirst( UriParameters.DEPTH.toString() );
-        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\""));
         }
     }
 
@@ -651,14 +620,13 @@ public class RestconfImpl implements RestconfService {
         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 ) );
-        boolean prettyPrintMode = parsePrettyPrintParameter( info );
-        return new StructuredData(data, iiWithData.getSchemaNode(), mountPoint,prettyPrintMode);
+        data = pruneDataAtDepth(data, parseDepthParameter(info));
+        boolean prettyPrintMode = parsePrettyPrintParameter(info);
+        return new StructuredData(data, iiWithData.getSchemaNode(), mountPoint, prettyPrintMode);
     }
 
     private boolean parsePrettyPrintParameter(UriInfo info) {
@@ -674,40 +642,83 @@ 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 );
+                    ErrorType.PROTOCOL, ErrorTag.UNKNOWN_NAMESPACE);
         }
 
         InstanceIdWithSchemaNode iiWithData = null;
@@ -716,27 +727,24 @@ public class RestconfImpl implements RestconfService {
             // 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);
@@ -751,26 +759,23 @@ 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();
         }
 
@@ -779,29 +784,27 @@ public class RestconfImpl implements RestconfService {
 
     @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 );
+                    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;
@@ -809,26 +812,23 @@ 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();
         }
 
@@ -843,18 +843,16 @@ 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();
         }
 
@@ -865,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();
@@ -886,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) {
@@ -913,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());
@@ -924,8 +916,7 @@ public class RestconfImpl implements RestconfService {
         return module;
     }
 
-    private InstanceIdWithSchemaNode addLastIdentifierFromData(
-            final InstanceIdWithSchemaNode identifierWithSchemaNode,
+    private InstanceIdWithSchemaNode addLastIdentifierFromData(final InstanceIdWithSchemaNode identifierWithSchemaNode,
             final CompositeNode data, final DataSchemaNode schemaOfData) {
         InstanceIdentifier instanceIdentifier = null;
         if (identifierWithSchemaNode != null) {
@@ -936,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;
@@ -976,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);
@@ -989,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) {
@@ -1015,15 +1003,13 @@ public class RestconfImpl implements RestconfService {
             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)) {
@@ -1031,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);
                 }
             }
 
@@ -1044,66 +1028,56 @@ 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 );
+        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 );
+        } else if (nodeBuilder instanceof SimpleNodeWrapper) {
+            normalizeSimpleNode((SimpleNodeWrapper) nodeBuilder, schema, mountPoint);
+        } else if ((nodeBuilder instanceof EmptyNodeWrapper)) {
+            normalizeEmptyNode((EmptyNodeWrapper) nodeBuilder, schema);
         }
     }
 
-    private void normalizeAnyXmlNode( final CompositeNodeWrapper compositeNode, final AnyXmlSchemaNode schema ) {
+    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 );
+        for (NodeWrapper<? extends Object> child : children) {
+            child.setNamespace(schema.getQName().getNamespace());
+            if (child instanceof CompositeNodeWrapper) {
+                normalizeAnyXmlNode((CompositeNodeWrapper) child, schema);
             }
         }
     }
 
-    private void normalizeEmptyNode( final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema ) {
+    private void normalizeEmptyNode(final EmptyNodeWrapper emptyNodeBuilder, final DataSchemaNode schema) {
         if ((schema instanceof LeafSchemaNode)) {
             emptyNodeBuilder.setComposite(false);
-        }
-        else {
+        } else {
             if ((schema instanceof ContainerSchemaNode)) {
                 // FIXME: Add presence check
                 emptyNodeBuilder.setComposite(true);
@@ -1111,59 +1085,55 @@ public class RestconfImpl implements RestconfService {
         }
     }
 
-    private void normalizeSimpleNode( final SimpleNodeWrapper simpleNode, final DataSchemaNode schema,
-            final MountInstance mountPoint ) {
+    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 );
+                inputValue = new IdentityValuesDTO(simpleNode.getNamespace().toString(), (String) value, null,
+                        (String) value);
             } // else value is already instance of IdentityValuesDTO
         }
 
         Object outputValue = inputValue;
 
-        if( typeDefinition != null ) {
-            Codec<Object,Object> codec = RestCodec.from(typeDefinition, mountPoint);
+        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 ) {
+    private void normalizeCompositeNode(final CompositeNodeWrapper compositeNodeBuilder,
+            final DataNodeContainer schema, final MountInstance mountPoint, final QName currentAugment) {
         final List<NodeWrapper<?>> children = compositeNodeBuilder.getValues();
-        checkNodeMultiplicityAccordingToSchema(schema,children);
+        checkNodeMultiplicityAccordingToSchema(schema, children);
         for (final NodeWrapper<? extends Object> child : children) {
-            final List<DataSchemaNode> potentialSchemaNodes =
-                    this.controllerContext.findInstanceDataChildrenByName(
-                            schema, child.getLocalName());
+            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) {
-                    builder.append("   ").append(potentialSchemaNode.getQName().getNamespace().toString())
-                    .append("\n");
+                    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 );
+                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) {
-                    final QName potentialCurrentAugment =
-                            this.normalizeNodeName(child, potentialSchemaNode, currentAugment, mountPoint);
-                    if (child.getQname() != null ) {
+                    final QName potentialCurrentAugment = this.normalizeNodeName(child, potentialSchemaNode,
+                            currentAugment, mountPoint);
+                    if (child.getQname() != null) {
                         this.normalizeNode(child, potentialSchemaNode, potentialCurrentAugment, mountPoint);
                         rightNodeSchemaFound = true;
                     }
@@ -1171,14 +1141,13 @@ public class RestconfImpl implements RestconfService {
             }
 
             if (!rightNodeSchemaFound) {
-                throw new RestconfDocumentedException(
-                        "Schema node \"" + child.getLocalName() + "\" was not found in module.",
-                        ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT );
+                throw new RestconfDocumentedException("Schema node \"" + child.getLocalName()
+                        + "\" was not found in module.", ErrorType.APPLICATION, ErrorTag.UNKNOWN_ELEMENT);
             }
         }
 
         if ((schema instanceof ListSchemaNode)) {
-            ListSchemaNode listSchemaNode = (ListSchemaNode)schema;
+            ListSchemaNode listSchemaNode = (ListSchemaNode) schema;
             final List<QName> listKeys = listSchemaNode.getKeyDefinition();
             for (final QName listKey : listKeys) {
                 boolean foundKey = false;
@@ -1189,10 +1158,9 @@ public class RestconfImpl implements RestconfService {
                 }
 
                 if (!foundKey) {
-                    throw new RestconfDocumentedException(
-                            "Missing key in URI \"" + listKey.getLocalName() +
-                            "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"",
-                            ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE );
+                    throw new RestconfDocumentedException("Missing key in URI \"" + listKey.getLocalName()
+                            + "\" of list \"" + listSchemaNode.getQName().getLocalName() + "\"", ErrorType.PROTOCOL,
+                            ErrorTag.DATA_MISSING);
                 }
             }
         }
@@ -1211,43 +1179,43 @@ public class RestconfImpl implements RestconfService {
                 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 '"
+                    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);
+                            + "'. 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);
         }
@@ -1257,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());
         }
     }
 
@@ -1314,17 +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 if (node instanceof AnyXmlSchemaNode) {
+            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());
+        } else {
+            throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
         }
     }
 }
index b0959c8398263dbd55a4ccb9fafac6d339f9fdaf..854e9635cf3cde883d97bbcc28f29c99bbda5c9c 100644 (file)
@@ -8,9 +8,7 @@
 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;
@@ -129,6 +127,4 @@ public final class SimpleNodeWrapper implements NodeWrapper<SimpleNode<?>>, Simp
         return unwrap().setValue(value);
     }
 
-
-
 }
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 925a09337ca3ee1e8fba707020e3c7a19b8e03f6..e526ec13be75fad83ff6c33b95dfe9ba0d809298 100644 (file)
@@ -12,11 +12,9 @@ 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;
@@ -30,7 +28,6 @@ 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;
@@ -41,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;
@@ -61,8 +57,7 @@ import org.w3c.dom.Element;
 import org.w3c.dom.Node;
 
 /**
- * {@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 {
 
@@ -72,8 +67,7 @@ public class ListenerAdapter implements DataChangeListener {
     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;
@@ -82,10 +76,8 @@ public class ListenerAdapter implements DataChangeListener {
     private final EventBus eventBus;
     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.
@@ -94,8 +86,7 @@ public class ListenerAdapter implements DataChangeListener {
      */
     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());
@@ -104,14 +95,10 @@ public class ListenerAdapter implements DataChangeListener {
     }
 
     @Override
-    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()) {
+    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);
@@ -132,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()) {
-                        LOG.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 {
-                        LOG.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);
                     }
                 }
@@ -153,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;
@@ -223,7 +204,9 @@ public class ListenerAdapter implements DataChangeListener {
      * Type of the event.
      */
     private enum EventType {
-        REGISTER, DEREGISTER, NOTIFY;
+        REGISTER,
+        DEREGISTER,
+        NOTIFY;
     }
 
     /**
@@ -233,11 +216,9 @@ public class ListenerAdapter implements DataChangeListener {
      *            DataChangeEvent
      * @return Data in printable form.
      */
-    private String prepareXmlFrom(
-            final 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);
 
@@ -246,10 +227,8 @@ 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 {
@@ -260,8 +239,7 @@ public class ListenerAdapter implements DataChangeListener {
             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, Charsets.UTF_8)));
+            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) {
@@ -310,29 +288,22 @@ public class ListenerAdapter implements DataChangeListener {
     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);
+        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);
     }
 
     /**
@@ -349,15 +320,13 @@ public class ListenerAdapter implements DataChangeListener {
      * @param operation
      *            {@link Operation}
      */
-    private void addValuesFromDataToElement(final Document doc,
-            final Set<InstanceIdentifier> data, final Element element, final Store store,
-            final 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);
         }
     }
@@ -376,15 +345,13 @@ public class ListenerAdapter implements DataChangeListener {
      * @param operation
      *            {@link Operation}
      */
-    private void addValuesFromDataToElement(final Document doc,
-            final Map<InstanceIdentifier, CompositeNode> data, final Element element,
-            final Store store, final 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);
         }
     }
@@ -404,9 +371,8 @@ public class ListenerAdapter implements DataChangeListener {
      *            {@link Operation}
      * @return {@link Node} node represented by changed event element.
      */
-    private Node createDataChangeEventElement(final Document doc,
-            final InstanceIdentifier path, final CompositeNode data, final Store store,
-            final 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");
@@ -442,8 +408,7 @@ public class ListenerAdapter implements DataChangeListener {
      * @return Data in XML format.
      */
     private Node translateToXml(final InstanceIdentifier path, final CompositeNode data) {
-        DataNodeContainer schemaNode = ControllerContext.getInstance()
-                .getDataNodeContainerFor(path);
+        DataNodeContainer schemaNode = ControllerContext.getInstance().getDataNodeContainerFor(path);
         if (schemaNode == null) {
             LOG.info(
                     "Path '{}' contains node with unsupported type (supported type is Container or List) or some node was not found.",
@@ -454,9 +419,7 @@ public class ListenerAdapter implements DataChangeListener {
             Document xml = xmlMapper.write(data, schemaNode);
             return xml.getFirstChild();
         } catch (UnsupportedDataTypeException e) {
-            LOG.error(
-                    "Error occured during translation of notification to XML.",
-                    e);
+            LOG.error("Error occured during translation of notification to XML.", e);
             return null;
         }
     }
@@ -469,8 +432,7 @@ public class ListenerAdapter implements DataChangeListener {
      * @param element
      *            {@link Element}
      */
-    private void addPathAsValueToElement(final InstanceIdentifier path,
-            final 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;
@@ -479,17 +441,13 @@ public class ListenerAdapter implements DataChangeListener {
         // 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("'");
@@ -517,14 +475,13 @@ public class ListenerAdapter implements DataChangeListener {
      * @param prefixes
      *            Map of namespaces and prefixes.
      */
-    private static void writeIdentifierWithNamespacePrefix(final Element element,
-            final StringBuilder textContent, final QName qName, final 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());
             }
         }
@@ -573,8 +530,7 @@ public class ListenerAdapter implements DataChangeListener {
      * @param registration
      *            ListenerRegistration<DataChangeListener>
      */
-    public void setRegistration(
-            final ListenerRegistration<DataChangeListener> registration) {
+    public void setRegistration(final ListenerRegistration<DataChangeListener> registration) {
         this.registration = registration;
     }
 
@@ -588,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<>();
@@ -608,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(final Channel subscriber) {
         if (!subscriber.isActive()) {
-            LOG.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);
@@ -625,8 +579,8 @@ 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
      */
@@ -640,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();
@@ -651,7 +604,8 @@ 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;
 
@@ -661,11 +615,12 @@ public class ListenerAdapter implements DataChangeListener {
     }
 
     /**
-     * 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;
 
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 26e4936d3f27d0d20e3875fe051335d79beae3be..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(final ChannelHandlerContext ctx, final 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(final ChannelHandlerContext ctx,
-            final 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,15 +78,13 @@ 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.sendUnsupportedVersionResponse(ctx.channel());
@@ -114,12 +104,11 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>
      * @param res
      *            FullHttpResponse
      */
-    private static void sendHttpResponse(final ChannelHandlerContext ctx,
-            final HttpRequest req, final 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());
@@ -140,14 +129,10 @@ public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object>
      * @param frame
      *            {@link WebSocketFrame}
      */
-    private void handleWebSocketFrame(final ChannelHandlerContext ctx,
-            final 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());
@@ -156,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(final ChannelHandlerContext ctx, final 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();
         }
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 93d32a14992e9df0209be9409cbea91074db514a..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();
@@ -119,68 +115,68 @@ public class CnSnToJsonBasicDataTypesTest extends YangAndXmlAndDataSchemaLoader
     static class ComplexAnyXmlVerifier extends LeafVerifier {
 
         ComplexAnyXmlVerifier() {
-            super( null, JsonToken.BEGIN_OBJECT );
+            super(null, JsonToken.BEGIN_OBJECT);
         }
 
         @Override
-        void verify( JsonReader reader, String keyName ) throws IOException {
+        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() );
+            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" );
+            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 );
+            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() );
+            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 );
+            assertEquals("Json reader child key for " + innerKey, "list", nextName);
             reader.beginArray();
-            verifyNestedLists( reader, 1 );
-            verifyNestedLists( reader, 3 );
+            verifyNestedLists(reader, 1);
+            verifyNestedLists(reader, 3);
             reader.endArray();
 
             reader.endObject();
             reader.endObject();
         }
 
-        void verifyNestedLists( JsonReader reader, int leafNum ) throws IOException {
+        void verifyNestedLists(JsonReader reader, int leafNum) throws IOException {
             reader.beginObject();
 
             String nextName = reader.nextName();
-            assertEquals( "Json reader next name", "nested-list", nextName );
+            assertEquals("Json reader next name", "nested-list", nextName);
 
             reader.beginArray();
 
             reader.beginObject();
-            verifyLeaf( reader, "nested-list", "nested-leaf", "nested-value" + leafNum++ );
+            verifyLeaf(reader, "nested-list", "nested-leaf", "nested-value" + leafNum++);
             reader.endObject();
 
             reader.beginObject();
-            verifyLeaf( reader, "nested-list", "nested-leaf", "nested-value" + leafNum );
+            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 {
+        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() );
+            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 {
+        Object getActualValue(JsonReader reader) throws IOException {
             return null;
         }
     }
@@ -199,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);
 
@@ -236,68 +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" ) );
-        expectedMap.put( "complex-any", new ComplexAnyXmlVerifier() );
-        expectedMap.put( "simple-any", new StringVerifier( "simple" ) );
-        expectedMap.put( "empty-any", new StringVerifier( "" ) );
+        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();
@@ -307,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 3f89c97367efd2f849802a61d5e4fec1f12149f1..3ca29c8d65cd485002ef8b46ad7b675d4a4bc581 100644 (file)
@@ -46,14 +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);
 
-//      pattern for e.g. >    "lf1"   : ""    < or >"lf1":""<
-        assertTrue(containsStringData(jsonOutput, "\"lf1\"",":","\"\""));
+        // pattern for e.g. > "lf1" : "" < or >"lf1":""<
+        assertTrue(containsStringData(jsonOutput, "\"lf1\"", ":", "\"\""));
     }
 
     private CompositeNode prepareCompositeNode() {
index 3d25955b3caae0bff5a51b5dec49f53b270160e5..eb6a5b9e00f7c7af65d2398bd2e21e87f650fe9f 100644 (file)
@@ -29,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() {
@@ -46,12 +45,12 @@ public class CnSnToJsonWithAugmentTest extends YangAndXmlAndDataSchemaLoader {
         }
         assertNotNull(jsonOutput);
 
-        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\"",":", "\\["));
+        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 30dc1161bf43841888f4d823e4c50450bf93a199..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( mockBit2.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 19ca812f8e9a90c1aad698be0df347b2b651b26f..656427352aea0da2242910ba5a274b1d500e63f2 100644 (file)
@@ -7,6 +7,7 @@
  */
 
 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;
@@ -66,268 +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 );
+        when(dataBroker.beginTransaction()).thenReturn(mockTransaction);
         when(mockTransaction.readConfigurationData(any(InstanceIdentifier.class))).thenReturn(
                 ImmutableCompositeNode.builder().toInstance());
-        mockTransaction.removeConfigurationData( instanceID );
-        when( mockTransaction.commit() ).thenReturn( expFuture );
+        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 );
+        when(mockMountInstance.beginTransaction()).thenReturn(mockTransaction);
         when(mockTransaction.readConfigurationData(any(InstanceIdentifier.class))).thenReturn(
                 ImmutableCompositeNode.builder().toInstance());
-        mockTransaction.removeConfigurationData( instanceID );
-        when( mockTransaction.commit() ).thenReturn( expFuture );
+        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 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 b90097bc94a0e7888b589f33960343cc94d36c12..313b766ed3312bad6cb5f74a542e84893226aa54 100644 (file)
@@ -36,8 +36,7 @@ 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;
@@ -50,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;
@@ -67,17 +66,15 @@ public class InvokeRpcMethodTest {
     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<>();
@@ -86,17 +83,15 @@ public class InvokeRpcMethodTest {
     }
 
     @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() {
@@ -115,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,uriInfo);
+        StructuredData structData = restconf.invokeRpc("invoke-rpc-module:rpc-test", payload, uriInfo);
         assertTrue(structData == null);
 
     }
@@ -137,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", "",uriInfo);
+            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", "",uriInfo);
+            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",
-                "",uriInfo);
+        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 ",uriInfo);
+            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", "",uriInfo);
+            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,uriInfo);
+        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", "",uriInfo);
+            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", "",uriInfo);
-        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",
-                "",uriInfo);
+                "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 42131026a5218cdb59079cc2324059930e816dd6..5fbfc453523339500c46e5d751b7967db455c19d 100644 (file)
@@ -25,9 +25,8 @@ 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
+ * 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
  */
@@ -35,31 +34,32 @@ 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);
+        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);
+                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);
+        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);
+                ErrorTag.BAD_ELEMENT, XmlToCompositeNodeProvider.INSTANCE);
     }
 
-    private void multipleEqualNameDataNodeTest(String path, ErrorType errorType, ErrorTag errorTag,MessageBodyReader<CompositeNode> messageBodyReader) {
+    private void multipleEqualNameDataNodeTest(String path, ErrorType errorType, ErrorTag errorTag,
+            MessageBodyReader<CompositeNode> messageBodyReader) {
         try {
-            CompositeNode compositeNode = TestUtils.readInputToCnSn(path, false,messageBodyReader);
+            CompositeNode compositeNode = TestUtils.readInputToCnSn(path, false, messageBodyReader);
             assertNotNull(compositeNode);
 
             Set<Module> modules = null;
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 9fd5128d19b51db4c71ad3678dae982aec1b3551..536d140cf1b78e05b7a3e77d38e43a32d8a1f8f4 100644 (file)
@@ -75,7 +75,7 @@ public class RestGetOperationTest extends JerseyTest {
         Object key;
         Object data; // List for a CompositeNode, value Object for a SimpleNode
 
-        NodeData( final Object key, final Object data ) {
+        NodeData(final Object key, final Object data) {
             this.key = key;
             this.data = data;
         }
@@ -117,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;
     }
 
@@ -172,19 +172,18 @@ 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
      */
     @Test
     public void getDataWithSlashesBehindMountPoint() throws UnsupportedEncodingException, URISyntaxException,
-    ParseException {
+            ParseException {
         InstanceIdentifier awaitedInstanceIdentifier = prepareInstanceIdentifierForList();
         when(
                 brokerFacade.readConfigurationDataBehindMountPoint(any(MountInstance.class),
@@ -446,11 +445,11 @@ public class RestGetOperationTest extends JerseyTest {
         assertTrue(
                 "module1-behind-mount-point in json wasn't found",
                 prepareXmlRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point", responseBody)
-                .find());
+                        .find());
         assertTrue(
                 "module2-behind-mount-point in json wasn't found",
                 prepareXmlRegex("module2-behind-mount-point", "2014-02-04", "module:2:behind:mount:point", responseBody)
-                .find());
+                        .find());
 
     }
 
@@ -486,7 +485,7 @@ public class RestGetOperationTest extends JerseyTest {
         assertTrue(
                 "module1-behind-mount-point in json wasn't found",
                 prepareXmlRegex("module1-behind-mount-point", "2014-02-03", "module:1:behind:mount:point", responseBody)
-                .find());
+                        .find());
         split = responseBody.split("<module");
         assertEquals("<module element is returned more then once", 2, split.length);
 
@@ -516,7 +515,8 @@ public class RestGetOperationTest extends JerseyTest {
                 .find());
     }
 
-    private Matcher prepareJsonRegex(final String module, final String revision, final String namespace, final String searchIn) {
+    private Matcher prepareJsonRegex(final String module, final String revision, final String namespace,
+            final String searchIn) {
         StringBuilder regex = new StringBuilder();
         regex.append("^");
 
@@ -542,7 +542,8 @@ public class RestGetOperationTest extends JerseyTest {
 
     }
 
-    private Matcher prepareXmlRegex(final String module, final String revision, final String namespace, final String searchIn) {
+    private Matcher prepareXmlRegex(final String module, final String revision, final String namespace,
+            final String searchIn) {
         StringBuilder regex = new StringBuilder();
         regex.append("^");
 
@@ -570,7 +571,8 @@ public class RestGetOperationTest extends JerseyTest {
         return ptrn.matcher(searchIn);
     }
 
-    private void prepareMockForModulesTest(final 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);
@@ -614,8 +616,8 @@ public class RestGetOperationTest extends JerseyTest {
     }
 
     /**
-     * If includeWhiteChars URI parameter is set to false then no white
-     * characters can be included in returned output
+     * If includeWhiteChars URI parameter is set to false then no white characters can be included in returned output
+     *
      * @throws UnsupportedEncodingException
      */
     @Test
@@ -624,10 +626,9 @@ public class RestGetOperationTest extends JerseyTest {
         getDataWithUriIncludeWhiteCharsParameter("operational");
     }
 
-
     private void getDataWithUriIncludeWhiteCharsParameter(String target) throws UnsupportedEncodingException {
         mockReadConfigurationDataMethod();
-        String uri = "/"+target+"/ietf-interfaces:interfaces/interface/eth0";
+        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);
 
@@ -649,311 +650,290 @@ public class RestGetOperationTest extends JerseyTest {
     @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( final 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( final 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( final Response response, final 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( final Element element, final 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( final String name, final 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( final String name ) {
-        return new NodeData( name, null );
+    private NodeData expectEmptyContainer(final String name) {
+        return new NodeData(name, null);
     }
 
-    private NodeData expectLeaf( final String name, final Object value ) {
-        return new NodeData( name, value );
+    private NodeData expectLeaf(final String name, final Object value) {
+        return new NodeData(name, value);
     }
 
-    private QName toNestedQName( final 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( final 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( final QName key, final 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( final QName key, final 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 c5c459618933af91bb272654d0b40b070fb7ffd3..b8c0270a61407a8358a741abe2515bc83395ef60 100644 (file)
@@ -78,63 +78,61 @@ import org.w3c.dom.NodeList;
 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,745 +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
+        // 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() );
+        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> 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);
@@ -921,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 449b79923edd40e0c21f922ba3ff6c271e45d3c5..ed1529540dc4fedde6fa803b909b5827e1241c79 100644 (file)
@@ -147,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();
@@ -161,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) {
@@ -279,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();
     }
@@ -298,7 +296,7 @@ public final class TestUtils {
         return result.toString();
     }
 
-    private static Pattern patternForStringsSeparatedByWhiteChars(String ... substrings ) {
+    private static Pattern patternForStringsSeparatedByWhiteChars(String... substrings) {
         StringBuilder pattern = new StringBuilder();
         pattern.append(".*");
         for (String substring : substrings) {
@@ -309,7 +307,7 @@ public final class TestUtils {
         return Pattern.compile(pattern.toString(), Pattern.DOTALL);
     }
 
-    public static boolean containsStringData(String jsonOutput,String ...substrings ) {
+    public static boolean containsStringData(String jsonOutput, String... substrings) {
         Pattern pattern = patternForStringsSeparatedByWhiteChars(substrings);
         Matcher matcher = pattern.matcher(jsonOutput);
         return matcher.matches();
index efdb7b240c94a9fb9b47aec81d71ff99e61ebff5..18703040ee89ef6c7fff33bb57d9ced739aa6d0f 100644 (file)
@@ -15,10 +15,8 @@ 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;
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 3617ed9fb0d897adaf654ed96f0f98967811d7d2..ae07571ad93efc192cb0c395420048e8a437631e 100644 (file)
@@ -8,6 +8,7 @@
 package org.opendaylight.controller.sal.restconf.impl.test.structures;
 
 import static org.junit.Assert.assertFalse;
+
 import java.util.HashMap;
 import java.util.Map;
 
@@ -57,14 +58,12 @@ public class LstItem {
     }
 
     public void addLfLst(LfLst lfLst) {
-        assertFalse( "Found multiple leaf list elements for " + lfLst.getName(),
-                    lfLsts.containsKey( lfLst.getName() ) );
+        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() ) );
+        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 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 8d29b981dc2d8dce784397c25ae99eafa13f27d6..11a0ef211ae2cb20eac661ff789acf9c2e1412eb 100644 (file)
             <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>
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-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;
+            }
+        }
+    }
+}
index 50ae8fd04fcce09c66a9eb7dd512af433df058d7..c6aa545935af5e2ae9771343706ac24a0518a363 100644 (file)
@@ -1,15 +1,12 @@
 package org.opendaylight.controller.sample.kitchen.impl;
 
-import java.util.Arrays;
-import java.util.Collections;
 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.sal.common.util.RpcErrors;
-import org.opendaylight.controller.sal.common.util.Rpcs;
 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;
@@ -20,10 +17,10 @@ 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.ErrorSeverity;
 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;
 
@@ -89,7 +86,8 @@ public class KitchenServiceImpl implements KitchenService, KitchenServiceRuntime
                     }
 
                     return Futures.immediateFuture(
-                              Rpcs.<Void> getRpcResult( atLeastOneSucceeded, errorList.build() ) );
+                              RpcResultBuilder.<Void> status( atLeastOneSucceeded )
+                                              .withRpcErrors( errorList.build() ).build() );
                 }
         } );
     }
@@ -102,7 +100,7 @@ public class KitchenServiceImpl implements KitchenService, KitchenServiceRuntime
             public RpcResult<Void> call() throws Exception {
 
                 // We don't actually do anything here - just return a successful result.
-                return Rpcs.<Void> getRpcResult( true, Collections.<RpcError>emptyList() );
+                return RpcResultBuilder.<Void> success().build();
             }
         } );
     }
@@ -113,11 +111,9 @@ public class KitchenServiceImpl implements KitchenService, KitchenServiceRuntime
         if( toasterOutOfBread )
         {
             log.info( "We're out of toast but we can make eggs" );
-            return Futures.immediateFuture( Rpcs.<Void> getRpcResult( true,
-                       Arrays.asList( RpcErrors.getRpcError( "", "partial-operation", null,
-                                          ErrorSeverity.WARNING,
-                                          "Toaster is out of bread but we can make you eggs",
-                                          ErrorType.APPLICATION, null ) ) ) );
+            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.
index d2b0f90194a9a066558f6d4dca5d1d8751ec01aa..de5ddd9a75298f61d5c4ce15c00b9df0e170cc92 100644 (file)
@@ -7,9 +7,6 @@
  */
 package org.opendaylight.controller.sample.toaster.provider;
 
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
 import java.util.concurrent.Callable;
 import java.util.concurrent.ExecutionException;
 import java.util.concurrent.ExecutorService;
@@ -28,8 +25,6 @@ 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.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;
@@ -43,7 +38,7 @@ import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120
 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.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.slf4j.Logger;
@@ -163,8 +158,7 @@ public class OpendaylightToaster implements ToasterService, ToasterProviderRunti
         }
 
         // Always return success from the cancel toast call.
-        return Futures.immediateFuture( Rpcs.<Void> getRpcResult( true,
-                                        Collections.<RpcError>emptyList() ) );
+        return Futures.immediateFuture( RpcResultBuilder.<Void> success().build() );
     }
 
     /**
@@ -181,17 +175,14 @@ public class OpendaylightToaster implements ToasterService, ToasterProviderRunti
         return futureResult;
     }
 
-    private List<RpcError> makeToasterOutOfBreadError() {
-        return Arrays.asList(
-                RpcErrors.getRpcError( "out-of-stock", "resource-denied", null, null,
-                                       "Toaster is out of bread",
-                                       ErrorType.APPLICATION, null ) );
+    private RpcError makeToasterOutOfBreadError() {
+        return RpcResultBuilder.newError( ErrorType.APPLICATION, "resource-denied",
+                "Toaster is out of bread", "out-of-stock", null, null );
     }
 
-    private List<RpcError> makeToasterInUseError() {
-        return Arrays.asList(
-            RpcErrors.getRpcError( "", "in-use", null, ErrorSeverity.WARNING,
-                                   "Toaster is busy", ErrorType.APPLICATION, null ) );
+    private RpcError makeToasterInUseError() {
+        return RpcResultBuilder.newWarning( ErrorType.APPLICATION, "in-use",
+                "Toaster is busy", null, null, null );
     }
 
     private void checkStatusAndMakeToast( final MakeToastInput input,
@@ -225,8 +216,8 @@ public class OpendaylightToaster implements ToasterService, ToasterProviderRunti
                         if( outOfBread() ) {
                             LOG.debug( "Toaster is out of bread" );
 
-                            return Futures.immediateFuture( Rpcs.<TransactionStatus>getRpcResult(
-                                       false, null, makeToasterOutOfBreadError() ) );
+                            return Futures.immediateFuture( RpcResultBuilder.<TransactionStatus>failed()
+                                    .withRpcError( makeToasterOutOfBreadError() ).build() );
                         }
 
                         LOG.debug( "Setting Toaster status to Down" );
@@ -244,8 +235,8 @@ public class OpendaylightToaster implements ToasterService, ToasterProviderRunti
                     // 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( Rpcs.<TransactionStatus>getRpcResult(
-                            false, null, makeToasterInUseError() ) );
+                    return Futures.immediateFuture( RpcResultBuilder.<TransactionStatus>failed()
+                            .withRpcError( makeToasterInUseError() ).build() );
                 }
         } );
 
@@ -265,7 +256,8 @@ public class OpendaylightToaster implements ToasterService, ToasterProviderRunti
                     // the read above returned ToasterStatus.Down. Either way, fail the
                     // futureResult and copy the errors.
 
-                    futureResult.set( Rpcs.<Void>getRpcResult( false, null, result.getErrors() ) );
+                    futureResult.set( RpcResultBuilder.<Void>failed().withRpcErrors(
+                                                                     result.getErrors() ).build() );
                 }
             }
 
@@ -286,10 +278,8 @@ public class OpendaylightToaster implements ToasterService, ToasterProviderRunti
                     LOG.error( "Failed to commit Toaster status", ex );
 
                     // Got some unexpected error so fail.
-                    futureResult.set( Rpcs.<Void> getRpcResult( false, null, Arrays.asList(
-                        RpcErrors.getRpcError( null, null, null, ErrorSeverity.ERROR,
-                                               ex.getMessage(),
-                                               ErrorType.APPLICATION, ex ) ) ) );
+                    futureResult.set( RpcResultBuilder.<Void> failed()
+                                        .withError( ErrorType.APPLICATION, ex.getMessage() ).build() );
                 }
             }
         } );
@@ -312,7 +302,7 @@ public class OpendaylightToaster implements ToasterService, ToasterProviderRunti
             notificationProvider.publish( reStockedNotification );
         }
 
-        return Futures.immediateFuture(Rpcs.<Void> getRpcResult(true, Collections.<RpcError>emptyList()));
+        return Futures.immediateFuture( RpcResultBuilder.<Void> success().build() );
     }
 
     /**
@@ -416,8 +406,7 @@ public class OpendaylightToaster implements ToasterService, ToasterProviderRunti
 
                     LOG.debug("Toast done");
 
-                    futureResult.set( Rpcs.<Void>getRpcResult( true, null,
-                                                          Collections.<RpcError>emptyList() ) );
+                    futureResult.set( RpcResultBuilder.<Void>success().build() );
 
                     return null;
                 }
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()]);
+    }
 }
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 f7091beba5fcb09f26cb1248dbdfdd52d600db77..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());
 
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 c770bde9206c03bba89027bc77b5fcb835e8dd03..1360a54d6fbaf2609067f1617337e8af76ec7852 100644 (file)
@@ -60,6 +60,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 +69,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;
@@ -106,28 +108,40 @@ extends AbstractSessionNegotiator<NetconfHelloMessage, S> {
 
         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);
+
+                        // 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) {
+                            // FIXME BUG-1365 calling "negotiation failed" closes the channel, but the channel does not get closed if data is still being transferred
+                            // Loopback connection initiation might
+                            negotiationFailed(new IllegalStateException("Session was not established after " + timeout));
+                        }
+
                         changeState(State.FAILED);
                     } 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() {
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 87f51364ba1c5b59f3b9326a518a07c99c72129c..cf48729113ce7b1304f2a0f7b3f2e4a7c0e05dfc 100644 (file)
@@ -20,6 +20,7 @@ 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;
@@ -60,6 +61,7 @@ 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();
+    }
+
+}
index 9825d0eefb791098bf1724d5996c44f881c0da6f..4c0c94ccb82a50d5027b1be6ea23718939cc3a28 100644 (file)
@@ -11,6 +11,7 @@ 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;
@@ -156,4 +157,14 @@ public class IEEE8021Q extends Packet {
         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;
+    }
+
 }
diff --git a/pom.xml b/pom.xml
index af8400242924501d0aca460e46da718327876bdb..242ab8eb89fce53b5ee7396b02790df9e96b781b 100644 (file)
--- a/pom.xml
+++ b/pom.xml
     <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>