Merge "Bug 2361: Added prototype implementation using new SPI."
authorRobert Varga <nite@hq.sk>
Sat, 21 Mar 2015 17:22:49 +0000 (17:22 +0000)
committerGerrit Code Review <gerrit@opendaylight.org>
Sat, 21 Mar 2015 17:22:50 +0000 (17:22 +0000)
382 files changed:
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingCodecTree.java [new file with mode: 0644]
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingCodecTreeFactory.java [new file with mode: 0644]
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingCodecTreeNode.java [new file with mode: 0644]
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingNormalizedNodeCachingCodec.java [new file with mode: 0644]
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingNormalizedNodeCodec.java [new file with mode: 0644]
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingNormalizedNodeSerializer.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingNormalizedNodeWriterFactory.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/gen/impl/AugmentableDataNodeContainerEmitterSource.java [moved from code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/gen/impl/AugmentableDataNodeContainerEmmiterSource.java with 91% similarity]
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/gen/impl/DataNodeContainerSerializerSource.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/gen/impl/DataObjectSerializerSource.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/gen/impl/StreamWriterGenerator.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/AugmentationNodeContext.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/BindingCodecContext.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/BindingNormalizedNodeCodecRegistry.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/BindingToNormalizedStreamWriter.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/BitsCodec.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/CachingNormalizedNodeCodecImpl.java [new file with mode: 0644]
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/CaseNodeCodecContext.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/ChoiceNodeCodecContext.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/ContainerNodeCodecContext.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/DataContainerCodecContext.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/DataContainerCodecPrototype.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/DataObjectCodecContext.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/EnumerationCodec.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/IdentifiableItemCodec.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/InstanceIdentifierCodec.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/KeyedListNodeCodecContext.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/LazyDataObject.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/LeafNodeCodecContext.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/ListNodeCodecContext.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/NodeCodecContext.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/NodeContextSupplier.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/NotificationCodecContext.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/SchemaRootCodecContext.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/UnionTypeCodec.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/ValueContext.java
code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/ValueTypeCodec.java
code-generator/binding-data-codec/src/test/java/org/opendaylight/yangtools/binding/data/codec/test/InstanceIdentifierSerializeDeserializeTest.java
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/AbstractTransformerGenerator.java [deleted file]
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/BindingClassListener.java [deleted file]
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/BindingGeneratorImpl.java
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/BindingSchemaContextUtils.java
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/CodecMapping.java [deleted file]
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/GeneratorListener.java [deleted file]
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/InstanceIdentifierCodecImpl.java [deleted file]
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/IntermediateMapping.java [deleted file]
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/LazyGeneratedCodecRegistry.java [deleted file]
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/ModuleContext.java
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/RuntimeGeneratedMappingServiceImpl.java [deleted file]
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/StaticFieldInitializer.java [deleted file]
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/TransformerGenerator.xtend [deleted file]
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/TypeResolver.java [deleted file]
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/YangTemplate.xtend
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/package-info.java [deleted file]
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/util/BindingRuntimeContext.java
code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/util/YangSchemaUtils.java
code-generator/binding-generator-util/src/main/java/org/opendaylight/yangtools/binding/generator/util/Types.java
code-generator/binding-java-api-generator/src/main/java/org/opendaylight/yangtools/sal/java/api/generator/BaseTemplate.xtend
code-generator/binding-java-api-generator/src/main/java/org/opendaylight/yangtools/sal/java/api/generator/BuilderTemplate.xtend
code-generator/binding-java-api-generator/src/main/java/org/opendaylight/yangtools/sal/java/api/generator/ClassTemplate.xtend
code-generator/binding-java-api-generator/src/main/java/org/opendaylight/yangtools/sal/java/api/generator/EnumTemplate.xtend
code-generator/binding-java-api-generator/src/main/java/org/opendaylight/yangtools/sal/java/api/generator/InterfaceTemplate.xtend
code-generator/binding-java-api-generator/src/main/java/org/opendaylight/yangtools/sal/java/api/generator/UnionTemplate.xtend
code-generator/binding-java-api-generator/src/main/java/org/opendaylight/yangtools/sal/java/api/generator/YangModuleInfoTemplate.xtend
code-generator/binding-java-api-generator/src/test/java/org/opendaylight/yangtools/sal/java/api/generator/test/CompilationTest.java
code-generator/binding-java-api-generator/src/test/java/org/opendaylight/yangtools/sal/java/api/generator/test/UnionTypedefUnusedImportTest.java [new file with mode: 0644]
code-generator/binding-java-api-generator/src/test/resources/compilation/union-typedef/union-typedef-test.yang [new file with mode: 0644]
code-generator/binding-type-provider/src/main/java/org/opendaylight/yangtools/sal/binding/yang/types/GroupingDefinitionDependencySort.java
code-generator/binding-type-provider/src/main/java/org/opendaylight/yangtools/sal/binding/yang/types/TypeProviderImpl.java
code-generator/maven-sal-api-gen-plugin/pom.xml
code-generator/maven-sal-api-gen-plugin/src/main/java/org/opendaylight/yangtools/yang/unified/doc/generator/GeneratorImpl.xtend
code-generator/maven-sal-api-gen-plugin/src/main/java/org/opendaylight/yangtools/yang/wadl/generator/WadlRestconfGenerator.xtend
common/artifacts/pom.xml
common/features/pom.xml
common/features/src/main/features/features.xml
common/parent/pom.xml
common/util/src/main/java/org/opendaylight/yangtools/util/Immutables.java
common/util/src/main/java/org/opendaylight/yangtools/util/LazyCollections.java
common/util/src/main/java/org/opendaylight/yangtools/util/UnmodifiableCollection.java [new file with mode: 0644]
integration-test/bundle-test/src/test/java/org/opendaylight/yangtools/bundle/test/BundleStartTest.java
integration-test/yang-runtime-tests/src/test/java/org/opendaylight/yangtools/it/yang/runtime/tests/Bug466EmptyAugmentationCodecs.java [deleted file]
integration-test/yang-runtime-tests/src/test/java/org/opendaylight/yangtools/it/yang/runtime/tests/MultipleRevisionsSupportTest.java
integration-test/yang-runtime-tests/src/test/java/org/opendaylight/yangtools/it/yang/runtime/tests/RuntimeCodecAugmentationWithGroupingsAndCasesTest.java [deleted file]
model/iana/iana-if-type-2014-05-08/pom.xml [new file with mode: 0644]
model/iana/iana-if-type-2014-05-08/src/main/yang/iana-if-type@2014-05-08.yang [new file with mode: 0644]
model/iana/pom.xml
model/ietf/ietf-interfaces/pom.xml [new file with mode: 0644]
model/ietf/ietf-interfaces/src/main/yang/ietf-interfaces.yang [new file with mode: 0644]
model/ietf/ietf-topology/src/main/yang/network-topology@2013-10-21.yang
model/ietf/pom.xml
restconf/restconf-client-api/src/main/java/org/opendaylight/yangtools/restconf/client/api/RestconfClientContextFactory.java
restconf/restconf-client-impl/pom.xml
restconf/restconf-client-impl/src/main/java/org/opendaylight/yangtools/restconf/client/AbstractDataStore.java
restconf/restconf-client-impl/src/main/java/org/opendaylight/yangtools/restconf/client/BindingToRestRpc.java
restconf/restconf-client-impl/src/main/java/org/opendaylight/yangtools/restconf/client/ConfigurationDataStoreImpl.java
restconf/restconf-client-impl/src/main/java/org/opendaylight/yangtools/restconf/client/RestconfClientFactory.java
restconf/restconf-client-impl/src/main/java/org/opendaylight/yangtools/restconf/client/RestconfClientImpl.java
restconf/restconf-client-impl/src/main/java/org/opendaylight/yangtools/restconf/client/to/RestRpcServiceContext.java
restconf/restconf-client-impl/src/test/java/org/opendaylight/yangtools/restconf/client/RestconfClientImplTest.java
restconf/restconf-jaxrs-api/src/main/java/org/opendaylight/yangtools/RestRestconfService.java [deleted file]
restconf/restconf-util/pom.xml
restconf/restconf-util/src/main/java/org/opendaylight/yangtools/restconf/utils/RestMessageTools.java [deleted file]
restconf/restconf-util/src/main/java/org/opendaylight/yangtools/restconf/utils/RestconfUtils.java
restconf/restconf-util/src/test/java/org/opendaylight/yangtools/restconf/utils/BindingStreamWriterTest.java
restconf/restconf-util/src/test/java/org/opendaylight/yangtools/restconf/utils/Bug1196Test.java [deleted file]
restconf/restconf-util/src/test/java/org/opendaylight/yangtools/restconf/utils/Bug527Test.java [deleted file]
restconf/restconf-util/src/test/java/org/opendaylight/yangtools/restconf/utils/LazyGeneratedCodecRestartTest.java [deleted file]
restconf/restconf-util/src/test/java/org/opendaylight/yangtools/restconf/utils/RestconfUtilsTest.java [deleted file]
yang/pom.xml
yang/yang-binding/src/main/java/org/opendaylight/yangtools/yang/binding/util/BindingReflections.java
yang/yang-binding/src/main/java/org/opendaylight/yangtools/yang/binding/util/NotificationListenerInvoker.java [new file with mode: 0644]
yang/yang-binding/src/main/java/org/opendaylight/yangtools/yang/binding/util/RpcMethodInvoker.java [new file with mode: 0644]
yang/yang-binding/src/main/java/org/opendaylight/yangtools/yang/binding/util/RpcMethodInvokerWithInput.java [new file with mode: 0644]
yang/yang-binding/src/main/java/org/opendaylight/yangtools/yang/binding/util/RpcMethodInvokerWithoutInput.java [new file with mode: 0644]
yang/yang-binding/src/main/java/org/opendaylight/yangtools/yang/binding/util/RpcServiceInvoker.java [new file with mode: 0644]
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/AttributesContainer.java
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/CompositeNode.java [deleted file]
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/MutableCompositeNode.java [deleted file]
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/MutableNode.java [deleted file]
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/MutableSimpleNode.java [deleted file]
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/Node.java [deleted file]
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/NodeModificationBuilder.java [deleted file]
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/SimpleNode.java [deleted file]
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/codec/DataNodeCodec.java [deleted file]
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/schema/AnyXmlNode.java
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/schema/AugmentationNode.java
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/schema/ChoiceNode.java
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/schema/ContainerNode.java
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/schema/DataContainerNode.java
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/schema/LeafSetNode.java
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/schema/MapNode.java
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/schema/NormalizedNodeContainer.java
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/schema/NormalizedNodes.java
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/schema/OrderedNodeContainer.java
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/schema/UnkeyedListNode.java
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/schema/stream/NormalizedNodeStreamAttributeWriter.java [new file with mode: 0644]
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/schema/stream/NormalizedNodeWriter.java
yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/schema/tree/ModificationType.java
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/AbstractJSONCodec.java
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/BooleanJSONCodec.java [new file with mode: 0644]
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/ChoiceNodeDataWithSchema.java
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/CompositeNodeDataWithSchema.java
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONCodec.java
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONCodecFactory.java
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONLeafrefCodec.java [deleted file]
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONNormalizedNodeStreamWriter.java
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONStreamWriterContext.java
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONStreamWriterExclusiveRootContext.java [new file with mode: 0644]
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONStreamWriterInvisibleContext.java
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONStreamWriterListContext.java
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONStreamWriterNamedObjectContext.java
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONStreamWriterObjectContext.java
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONStreamWriterRootContext.java
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONStreamWriterSharedRootContext.java [new file with mode: 0644]
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONStreamWriterURIContext.java
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONStringIdentityrefCodec.java
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONStringInstanceIdentifierCodec.java
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JsonParserStream.java
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JsonWriterFactory.java [new file with mode: 0644]
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/ListNodeDataWithSchema.java
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/NumberJSONCodec.java [moved from yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/UnquotedJSONCodec.java with 58% similarity]
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/QuotedJSONCodec.java
yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/RpcAsContainer.java [new file with mode: 0644]
yang/yang-data-codec-gson/src/test/java/org/opendaylight/yangtools/yang/data/codec/gson/JsonStreamToNormalizedNodeTest.java
yang/yang-data-codec-gson/src/test/java/org/opendaylight/yangtools/yang/data/codec/gson/NormalizedNodeToJsonStreamTest.java
yang/yang-data-codec-gson/src/test/java/org/opendaylight/yangtools/yang/data/codec/gson/TestingNormalizedNodeStructuresCreator.java
yang/yang-data-codec-gson/src/test/resources/complexjson/complex-json.json
yang/yang-data-codec-gson/src/test/resources/complexjson/keyed-list-node-in-container.json
yang/yang-data-codec-gson/src/test/resources/complexjson/keyed-list-restconf-behaviour.json [new file with mode: 0644]
yang/yang-data-codec-gson/src/test/resources/complexjson/keyed-list-yang-json-behaviour.json [new file with mode: 0644]
yang/yang-data-codec-gson/src/test/resources/complexjson/missing-module-in-top-level.json [new file with mode: 0644]
yang/yang-data-codec-gson/src/test/resources/complexjson/namesakes.json [new file with mode: 0644]
yang/yang-data-codec-gson/src/test/resources/complexjson/not-existing-element.json [new file with mode: 0644]
yang/yang-data-codec-gson/src/test/resources/complexjson/unkeyed-node-in-container.json
yang/yang-data-codec-gson/src/test/resources/complexjson/yang/complexjson-augmentation-namesake.yang [new file with mode: 0644]
yang/yang-data-codec-gson/src/test/resources/complexjson/yang/complexjson-augmentation.yang
yang/yang-data-composite-node/pom.xml [deleted file]
yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/AnyXmlNodeCnSnParser.java [deleted file]
yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/AugmentationNodeCnSnParser.java [deleted file]
yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/ChoiceNodeCnSnParser.java [deleted file]
yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/CnSnToNormalizedNodeParserFactory.java [deleted file]
yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/ContainerNodeCnSnParser.java [deleted file]
yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/LeafNodeCnSnParser.java [deleted file]
yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/LeafSetEntryNodeCnSnParser.java [deleted file]
yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/LeafSetNodeCnSnParser.java [deleted file]
yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/MapEntryNodeCnSnParser.java [deleted file]
yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/AnyXmlNodeCnSnSerializer.java [deleted file]
yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/AugmentationNodeCnSnSerializer.java [deleted file]
yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/ChoiceNodeCnSnSerializer.java [deleted file]
yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/CnSnFromNormalizedNodeSerializerFactory.java [deleted file]
yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/ContainerNodeCnSnSerializer.java [deleted file]
yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/LeafNodeCnSnSerializer.java [deleted file]
yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/LeafSetEntryNodeCnSnSerializer.java [deleted file]
yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/LeafSetNodeCnSnSerializer.java [deleted file]
yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/MapEntryNodeCnSnSerializer.java [deleted file]
yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/MapNodeCnSnSerializer.java [deleted file]
yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/json/CnSnToNormalizedNodesUtils.java [deleted file]
yang/yang-data-composite-node/src/test/java/org/opendaylight/yangtools/yang/data/composite/node/schema/TestUtils.java [deleted file]
yang/yang-data-composite-node/src/test/java/org/opendaylight/yangtools/yang/data/composite/node/schema/parser/Bug2180Test.java [deleted file]
yang/yang-data-composite-node/src/test/java/org/opendaylight/yangtools/yang/data/composite/node/schema/parser/ParseCnSnStructToNormalizedStructTest.java [deleted file]
yang/yang-data-composite-node/src/test/java/org/opendaylight/yangtools/yang/data/composite/node/schema/serializer/SerializeNormalizedStructToCnSnStructTest.java [deleted file]
yang/yang-data-composite-node/src/test/resources/cnsn-to-normalized-node/json/simple-container.json [deleted file]
yang/yang-data-composite-node/src/test/resources/cnsn-to-normalized-node/yang/augment-simple-container.yang [deleted file]
yang/yang-data-composite-node/src/test/resources/cnsn-to-normalized-node/yang/bug2180-test-model.yang [deleted file]
yang/yang-data-composite-node/src/test/resources/cnsn-to-normalized-node/yang/simple-container.yang [deleted file]
yang/yang-data-impl/pom.xml
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/AbstractNodeTO.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/CompositeNodeModificationTOImpl.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/CompositeNodeTOImpl.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/ImmutableCompositeNode.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/LazyNodeToNodeMap.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/MutableCompositeNodeTOImpl.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/MutableSimpleNodeTOImpl.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/NodeFactory.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/NodeModificationBuilderImpl.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/NodeUtils.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/SimpleNodeModificationTOImpl.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/SimpleNodeTOImpl.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/XmlTreeBuilder.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/AugmentationCodec.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/BindingIndependentMappingService.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/ChoiceCaseCodec.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/ChoiceCodec.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/CodecRegistry.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/DataContainerCodec.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/DomCodec.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/IdentifierCodec.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/InstanceIdentifierCodec.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/SchemaTracker.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/xml/ElementInstanceIdentifierParser.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/xml/InstanceIdentifierForXmlCodec.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/xml/RandomPrefixInstanceIdentifierSerializer.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/xml/XMLStreamNormalizedNodeStreamWriter.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/xml/XmlDocumentUtils.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/xml/XmlStreamUtils.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/xml/XmlUtils.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/Builders.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/ImmutableNodes.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/ImmutableNormalizedNodeStreamWriter.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/SchemaUtils.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/api/CollectionNodeBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/api/DataContainerNodeAttrBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/api/DataContainerNodeBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/api/ListNodeBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/api/NormalizedNodeContainerBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/impl/AbstractImmutableDataContainerNodeAttrBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/impl/AbstractImmutableDataContainerNodeBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/impl/ImmutableAnyXmlNodeBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/impl/ImmutableAnyXmlNodeSchemaAwareBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/impl/ImmutableChoiceNodeSchemaAwareBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/impl/ImmutableLeafSetNodeBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/impl/ImmutableMapEntryNodeBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/impl/ImmutableMapNodeBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/impl/ImmutableOrderedLeafSetNodeBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/impl/ImmutableOrderedMapNodeBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/impl/ImmutableUnkeyedListNodeBuilder.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/builder/impl/valid/DataValidationException.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/nodes/AbstractImmutableDataContainerNode.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/FromNormalizedNodeSerializerFactory.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/ToNormalizedNodeParserFactory.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/AugmentationSchemaProxy.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/parser/AnyXmlNodeBaseParser.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/parser/AugmentationNodeBaseParser.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/parser/BaseDispatcherParser.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/parser/ChoiceNodeBaseParser.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/parser/ContainerNodeBaseParser.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/parser/ListEntryNodeBaseParser.java [moved from yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/parser/MapEntryNodeBaseParser.java with 56% similarity]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/parser/ListNodeBaseParser.java [new file with mode: 0644]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/parser/MapNodeBaseParser.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/parser/NodeParserDispatcher.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/parser/OrderedListNodeBaseParser.java [new file with mode: 0644]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/parser/UnkeyedListNodeBaseParser.java [new file with mode: 0644]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/serializer/BaseDispatcherSerializer.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/serializer/ChoiceNodeBaseSerializer.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/serializer/ListEntryNodeBaseSerializer.java [moved from yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/serializer/MapEntryNodeBaseSerializer.java with 73% similarity]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/serializer/ListNodeBaseSerializer.java [new file with mode: 0644]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/serializer/MapNodeBaseSerializer.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/serializer/NodeSerializerDispatcher.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/DomUtils.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/parser/AnyXmlDomParser.java [new file with mode: 0644]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/parser/DomToNormalizedNodeParserFactory.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/parser/LeafNodeDomParser.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/parser/LeafSetEntryNodeDomParser.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/parser/ListEntryNodeDomParser.java [new file with mode: 0644]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/parser/MapEntryNodeDomParser.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/parser/MapNodeDomParser.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/parser/OrderedListNodeDomParser.java [moved from yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/MapNodeCnSnParser.java with 51% similarity]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/parser/UnkeyedListEntryNodeDomParser.java [new file with mode: 0644]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/parser/UnkeyedListNodeDomParser.java [new file with mode: 0644]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/serializer/DomFromNormalizedNodeSerializerFactory.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/serializer/ListEntryNodeDomSerializer.java [new file with mode: 0644]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/serializer/MapEntryNodeDomSerializer.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/serializer/MapNodeDomSerializer.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/serializer/UnkeyedListEntryNodeDomSerializer.java [new file with mode: 0644]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/serializer/UnkeyedListNodeDomSerializer.java [new file with mode: 0644]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/tree/DataNodeContainerModificationStrategy.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/tree/InMemoryDataTree.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/tree/InMemoryDataTreeCandidate.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/tree/InMemoryDataTreeModification.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/tree/LogicalOperation.java [new file with mode: 0644]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/tree/ModifiedNode.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/tree/NodeModification.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/tree/NoopDataTreeCandidate.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/tree/NormalizedNodeContainerModificationStrategy.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/tree/SchemaAwareApplyOperation.java
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/util/AbstractCompositeNodeBuilder.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/util/AbstractNodeBuilder.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/util/CompositeNodeBuilder.java [deleted file]
yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/util/NodeBuilder.java [deleted file]
yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/codec/xml/test/RpcReplyToDomTest.java [deleted file]
yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/CompositeNodeTOImplTest.java [deleted file]
yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/LazyNodeToNodeMapTest.java [deleted file]
yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/MyNodeBuilder.java [deleted file]
yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/NodeFactoryTest.java [deleted file]
yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/NodeHelper.java [deleted file]
yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/NodeModificationBuilderImplTest.java [deleted file]
yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/NodeUtilsTest.java [deleted file]
yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/XmlTreeBuilderTest.java [deleted file]
yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/codec/xml/XmlDocumentUtilsTest.java
yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/codec/xml/XmlStreamUtilsTest.java
yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/schema/NormalizedDataBuilderTest.java
yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/serializer/NormalizedNodeXmlTranslationTest.java
yang/yang-data-impl/src/test/resources/org/opendaylight/yangtools/yang/data/impl/schema/simple.xml
yang/yang-data-impl/src/test/resources/org/opendaylight/yangtools/yang/data/impl/schema/test.yang
yang/yang-data-operations/src/main/java/org/opendaylight/yangtools/yang/data/operations/AbstractContainerNodeModification.java
yang/yang-data-operations/src/main/java/org/opendaylight/yangtools/yang/data/operations/ChoiceNodeModification.java
yang/yang-data-operations/src/main/java/org/opendaylight/yangtools/yang/data/operations/DataModificationException.java
yang/yang-data-operations/src/main/java/org/opendaylight/yangtools/yang/data/operations/UnkeyedListNodeModification.java [new file with mode: 0644]
yang/yang-data-operations/src/test/java/org/opendaylight/yangtools/yang/data/operations/YangDataOperationsTest.java
yang/yang-data-util/pom.xml
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AbstractContainerNode.java [deleted file]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AbstractInteriorContextNode.java [new file with mode: 0644]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AbstractLeafNodeContext.java [new file with mode: 0644]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AbstractMixinContextNode.java [new file with mode: 0644]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AbstractNode.java [deleted file]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AbstractStringInstanceIdentifierCodec.java
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AnyXmlContextNode.java [new file with mode: 0644]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AugmentationContextNode.java [new file with mode: 0644]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/ChoiceNodeContextNode.java [new file with mode: 0644]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/ContainerContextNode.java [new file with mode: 0644]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/DataContainerContextNode.java [new file with mode: 0644]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/DataSchemaContextNode.java [new file with mode: 0644]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/DataSchemaContextTree.java [new file with mode: 0644]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/LeafContextNode.java [new file with mode: 0644]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/LeafListEntryContextNode.java [new file with mode: 0644]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/ListItemContextNode.java [new file with mode: 0644]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/Nodes.java [deleted file]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/OrderedLeafListMixinContextNode.java [new file with mode: 0644]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/OrderedMapMixinContextNode.java [new file with mode: 0644]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/UnkeyedListItemContextNode.java [new file with mode: 0644]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/UnkeyedListMixinContextNode.java [new file with mode: 0644]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/UnorderedLeafListMixinContextNode.java [new file with mode: 0644]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/UnorderedMapMixinContextNode.java [new file with mode: 0644]
yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/XpathStringParsingPathArgumentBuilder.java [new file with mode: 0644]
yang/yang-maven-plugin-spi/pom.xml
yang/yang-maven-plugin/pom.xml
yang/yang-maven-plugin/src/main/java/org/opendaylight/yangtools/yang2sources/plugin/YangToSourcesMojo.java
yang/yang-model-api/src/main/java/org/opendaylight/yangtools/yang/model/api/ChoiceNode.java
yang/yang-model-api/src/main/java/org/opendaylight/yangtools/yang/model/api/ChoiceSchemaNode.java [new file with mode: 0644]
yang/yang-model-api/src/main/java/org/opendaylight/yangtools/yang/model/api/package-info.java
yang/yang-model-export/src/main/java/org/opendaylight/yangtools/yang/model/export/SchemaContextEmitter.java
yang/yang-model-export/src/main/java/org/opendaylight/yangtools/yang/model/export/SingleModuleYinStatementWriter.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/DataNodeIterator.java
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/EffectiveAugmentationSchema.java [new file with mode: 0644]
yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/SchemaContextUtil.java
yang/yang-model-util/src/test/java/org/opendaylight/yangtools/yang/model/util/SchemaContextProxyTest.java
yang/yang-parser-impl/pom.xml
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/builder/impl/BuilderUtils.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/builder/impl/ChoiceBuilder.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/builder/impl/ChoiceNodeImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/builder/impl/ModuleBuilder.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/builder/impl/UsesNodeImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/impl/YangParserImpl.java
yang/yang-parser-impl/src/main/java/org/opendaylight/yangtools/yang/parser/util/NamedByteArrayInputStream.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/parser/impl/AugmentTest.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/parser/impl/GroupingTest.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/parser/impl/TestUtils.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/parser/impl/UsesAugmentTest.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/parser/impl/YangParserTest.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/parser/impl/YangParserWithContextTest.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/parser/repo/SharedSchemaRepositoryTest.java
yang/yang-parser-impl/src/test/java/org/opendaylight/yangtools/yang/parser/util/SchemaContextUtilTest.java

diff --git a/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingCodecTree.java b/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingCodecTree.java
new file mode 100644 (file)
index 0000000..ea28281
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.binding.data.codec.api;
+
+import javax.annotation.Nullable;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+
+/**
+ *
+ * Navigable tree representing hierarchy of Binding to Normalized Node codecs
+ *
+ * This navigable tree is associated to conrete set of YANG models, represented
+ * by SchemaContext and provides access to subtree specific serialization
+ * context.
+ *
+ * TODO: Add more detailed documentation
+ **/
+public interface BindingCodecTree {
+
+      @Nullable <T extends DataObject> BindingCodecTreeNode<T> getSubtreeCodec(InstanceIdentifier<T> path);
+
+      @Nullable BindingCodecTreeNode<?> getSubtreeCodec(YangInstanceIdentifier path);
+
+      @Nullable BindingCodecTreeNode<?> getSubtreeCodec(SchemaPath path);
+
+}
\ No newline at end of file
diff --git a/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingCodecTreeFactory.java b/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingCodecTreeFactory.java
new file mode 100644 (file)
index 0000000..25f45be
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.binding.data.codec.api;
+
+import com.google.common.annotations.Beta;
+import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+public interface BindingCodecTreeFactory {
+
+    /**
+     *
+     * Creates Binding Codec Tree for specified Binding runtime context.
+     *
+     * @param context
+     *            Binding Runtime Context for which Binding codecs should be
+     *            instantiated.
+     * @return Binding Codec Tree for specified Binding runtime context.
+     */
+    BindingCodecTree create(BindingRuntimeContext context);
+
+    /**
+     *
+     * Creates Binding Codec Tree for specified Binding runtime context.
+     *
+     * @param context
+     *            Binding Runtime Context for which Binding codecs should be
+     *            instantiated.
+     * @param bindingClasses
+     *            Binding Runtime Context will be constructed using bindings
+     *            which contains specified classes, in order to support
+     *            deserialization in multi-classloader environment.
+     * @return Binding Codec Tree for specified Binding runtime context.
+     */
+    @Beta
+   BindingCodecTree create(SchemaContext context, Class<?>... bindingClasses);
+
+}
diff --git a/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingCodecTreeNode.java b/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingCodecTreeNode.java
new file mode 100644 (file)
index 0000000..4317ef3
--- /dev/null
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.binding.data.codec.api;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableCollection;
+import java.util.List;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
+
+/**
+ * Subtree codec specific to model subtree between Java Binding and
+ * NormalizedNode.
+ *
+ */
+@Beta
+public interface BindingCodecTreeNode<T extends DataObject> extends BindingNormalizedNodeCodec<T> {
+
+    /**
+     *
+     * Returns binding class of interface which represents API of current
+     * schema node.
+     *
+     * The result is same as invoking {@link DataObject#getImplementedInterface()}
+     * on instance of data.
+     *
+     * @return interface which defines API of binding representation of data.
+     */
+    @Nonnull
+    Class<T> getBindingClass();
+
+    /**
+     *
+     * Returns child context as if it was walked by
+     * {@link BindingStreamEventWriter}. This means that to enter case, one must
+     * issue getChild(ChoiceClass).getChild(CaseClass).
+     *
+     * @param childClass Child class by Biding Stream navigation
+     * @return Context of child
+     * @throws IllegalArgumentException
+     *             If supplied child class is not valid in specified context.
+     */
+    @Nonnull
+    <E extends DataObject> BindingCodecTreeNode<E> streamChild(@Nonnull Class<E> childClass);
+
+    /**
+     *
+     * Returns child context as if it was walked by
+     * {@link BindingStreamEventWriter}. This means that to enter case, one must
+     * issue getChild(ChoiceClass).getChild(CaseClass).
+     *
+     * This method differs from {@link #streamChild(Class)}, that is less
+     * stricter for interfaces representing augmentation and cases, that
+     * may return {@link BindingCodecTreeNode} even if augmentation interface
+     * containing same data was supplied and does not represent augmentation
+     * of this node.
+     *
+     * @param childClass
+     * @return Context of child or Optional absent is supplied class is not
+     *         applicable in context.
+     */
+    <E extends DataObject> Optional<? extends BindingCodecTreeNode<E>> possibleStreamChild(@Nonnull Class<E> childClass);
+
+    /**
+     * Returns nested node context using supplied YANG Instance Identifier
+     *
+     * @param child
+     *            Yang Instance Identifier Argument
+     * @return Context of child
+     * @throws IllegalArgumentException
+     *             If supplied argument does not represent valid child.
+     */
+    @Nonnull
+    BindingCodecTreeNode<?> yangPathArgumentChild(@Nonnull YangInstanceIdentifier.PathArgument child);
+
+    /**
+     * Returns nested node context using supplied Binding Instance Identifier
+     * and adds YANG instance identifiers to supplied list.
+     *
+     * @param arg
+     *            Binding Instance Identifier Argument
+     * @param builder
+     *            Mutable instance of list, which is appended by YangInstanceIdentifiers
+     *            as tree is walked. Use null if such side-product is not needed.
+     * @return Context of child
+     * @throws IllegalArgumentException
+     *             If supplied argument does not represent valid child.
+     */
+    @Nonnull
+    BindingCodecTreeNode<?> bindingPathArgumentChild(@Nonnull InstanceIdentifier.PathArgument arg,
+            @Nullable List<YangInstanceIdentifier.PathArgument> builder);
+
+    /**
+     *
+     * Returns codec which uses caches serialization / deserialization results
+     *
+     * Caching may introduce performance penalty to serialization / deserialization
+     * but may decrease use of heap for repetitive objects.
+     *
+     *
+     * @param cacheSpecifier Set of objects, for which cache may be in place
+     * @return Codec whihc uses cache for serialization / deserialization.
+     */
+    @Nonnull
+    BindingNormalizedNodeCachingCodec<T> createCachingCodec(@Nonnull
+            ImmutableCollection<Class<? extends DataObject>> cacheSpecifier);
+
+    @Beta
+    void writeAsNormalizedNode(T data, NormalizedNodeStreamWriter writer);
+}
diff --git a/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingNormalizedNodeCachingCodec.java b/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingNormalizedNodeCachingCodec.java
new file mode 100644 (file)
index 0000000..2e990d9
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.binding.data.codec.api;
+
+import com.google.common.annotations.Beta;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+
+/**
+ *
+ * Caching variant of Binding to Normalized Node codec.
+ *
+ * Caching may introduce performance penalty to serialization / deserialization
+ * but may decrease use of heap for repetitive objects.
+ *
+ * @param <T> Binding representtion of data
+ *
+ */
+@Beta
+public interface BindingNormalizedNodeCachingCodec<T extends DataObject> extends BindingNormalizedNodeCodec<T>, AutoCloseable {
+
+    /**
+     *
+     * Invoking close will invalidate this codec and any of its child
+     * codecs and will invalidate cache.
+     *
+     * Any subsequent calls to this codec will fail with {@link IllegalStateException}
+     * thrown.
+     *
+     */
+    @Override
+    public void close();
+}
diff --git a/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingNormalizedNodeCodec.java b/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/api/BindingNormalizedNodeCodec.java
new file mode 100644 (file)
index 0000000..ca48ea8
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.binding.data.codec.api;
+
+import com.google.common.annotations.Beta;
+import javax.annotation.Nonnull;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+/**
+ *
+ * Codec providing serialization and deserializiation between Binding
+ * and NormalizedNode representation of data.
+ *
+ *
+ * @param <T> Binding representation of data
+ */
+@Beta
+public interface BindingNormalizedNodeCodec<T extends DataObject> {
+
+    /**
+     * Converts from Normalized Node to Binding representation of data.
+     *
+     * @param data Normalized Node representation of data
+     * @return Binding representation of data
+     */
+    @Nonnull T deserialize(@Nonnull NormalizedNode<?,?> data);
+
+    /**
+     * Converts from  Binding to Normalized Node representation of data.
+     *
+     * @param data Binding representation of data
+     * @return Normalized Node representation of data
+     */
+    @Nonnull NormalizedNode<?,?> serialize(@Nonnull T data);
+
+}
index 5e3fd0be5f34a257904b0694b6b28114b7571885..d16fa50058b41bc5c01d371e439b836971871904 100644 (file)
@@ -32,6 +32,8 @@ public interface BindingNormalizedNodeSerializer {
      * @param binding
      *            Binding Instance Identifier
      * @return DOM Instance Identifier
+     * @throws IllegalArgumentException
+     *             If supplied Instance Identifier is not valid.
      */
     YangInstanceIdentifier toYangInstanceIdentifier(@Nonnull InstanceIdentifier<?> binding);
 
@@ -56,6 +58,8 @@ public interface BindingNormalizedNodeSerializer {
      * @param data
      *            Data object representing data
      * @return NormalizedNode representation
+     * @throws IllegalArgumentException
+     *             If supplied Instance Identifier is not valid.
      */
     <T extends DataObject> Entry<YangInstanceIdentifier, NormalizedNode<?, ?>> toNormalizedNode(
             InstanceIdentifier<T> path, T data);
index cd87da1f795e7a102c582efdcea3fa29b83d73e3..fe8bb26761dbf4f1c7d370dbb226cd0321f48a9c 100644 (file)
@@ -46,6 +46,7 @@ public interface BindingNormalizedNodeWriterFactory {
      *            Stream writer on which events will be invoked.
      * @return Instance Identifier and {@link BindingStreamEventWriter}
      *         which will write to supplied {@link NormalizedNodeStreamWriter}.
+     * @throws IllegalArgumentException If supplied Instance Identifier is not valid.
      */
     @Nonnull Entry<YangInstanceIdentifier, BindingStreamEventWriter> newWriterAndIdentifier(@Nonnull InstanceIdentifier<?> path,
             @Nonnull NormalizedNodeStreamWriter domWriter);
@@ -66,6 +67,7 @@ public interface BindingNormalizedNodeWriterFactory {
      * @param domWriter Stream writer on which events will be invoked.
      * @return {@link BindingStreamEventWriter}
      *         which will write to supplied {@link NormalizedNodeStreamWriter}.
+     * @throws IllegalArgumentException If supplied Instance Identifier is not valid.
      */
     @Nonnull
     BindingStreamEventWriter newWriter(@Nonnull InstanceIdentifier<?> path,
@@ -11,10 +11,10 @@ import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
 import org.opendaylight.yangtools.yang.binding.DataObjectSerializerImplementation;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 
-abstract class AugmentableDataNodeContainerEmmiterSource extends DataNodeContainerSerializerSource {
+abstract class AugmentableDataNodeContainerEmitterSource extends DataNodeContainerSerializerSource {
     private static final String AUGMENTABLE_SERIALIZER = "AUGMENTABLE_SERIALIZER";
 
-    public AugmentableDataNodeContainerEmmiterSource(final AbstractStreamWriterGenerator generator, final GeneratedType type, final DataNodeContainer node) {
+    public AugmentableDataNodeContainerEmitterSource(final AbstractStreamWriterGenerator generator, final GeneratedType type, final DataNodeContainer node) {
         super(generator, type, node);
         /*
          * Eventhough intuition says the serializer could reference the generator directly,
index 9b8faba4cb67a2a3bf36215dbc9796937ed9b48d..76d1cd01c6c79188eba4f470b992d453ec04cac0 100644 (file)
@@ -20,7 +20,7 @@ import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.DataObjectSerializerImplementation;
 import org.opendaylight.yangtools.yang.binding.DataObjectSerializerRegistry;
 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
@@ -150,7 +150,7 @@ abstract class DataNodeContainerSerializerSource extends DataObjectSerializerSou
             emitList(b, getterName, valueType, casted);
         } else if (child instanceof ContainerSchemaNode) {
             b.append(statement(staticInvokeEmitter(childType, getterName)));
-        } else if (child instanceof ChoiceNode) {
+        } else if (child instanceof ChoiceSchemaNode) {
             String propertyName = CHOICE_PREFIX + childType.getName();
             staticConstant(propertyName, DataObjectSerializerImplementation.class, ChoiceDispatchSerializer.from(loadClass(childType)));
             b.append(statement(invoke(propertyName, StreamWriterGenerator.SERIALIZE_METHOD_NAME, REGISTRY, cast(DataObject.class.getName(),getterName), STREAM)));
index 4a3d1b38ba8b486acedff00e5b015edf9e49d3b4..ec276e79daa9fa03afd7dd64fc55e797bc59932b 100644 (file)
@@ -8,7 +8,6 @@
 package org.opendaylight.yangtools.binding.data.codec.gen.impl;
 
 import com.google.common.base.Preconditions;
-
 import org.opendaylight.yangtools.binding.data.codec.gen.spi.AbstractSource;
 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
 import org.opendaylight.yangtools.sal.binding.generator.impl.GeneratedClassLoadingStrategy;
@@ -68,7 +67,6 @@ abstract class DataObjectSerializerSource extends AbstractSource {
 
     protected final CharSequence leafSetEntryNode(final CharSequence value) {
         return invoke(STREAM, "leafSetEntryNode", value);
-
     }
 
     protected final CharSequence startContainerNode(final CharSequence type, final CharSequence expected) {
@@ -76,7 +74,7 @@ abstract class DataObjectSerializerSource extends AbstractSource {
     }
 
     protected final  CharSequence escape(final String localName) {
-        return '"'+localName+'"';
+        return '"' + localName + '"';
     }
 
     protected final CharSequence startUnkeyedList(final CharSequence type, final CharSequence expected) {
@@ -113,7 +111,6 @@ abstract class DataObjectSerializerSource extends AbstractSource {
         return invoke(STREAM, "startCase", (localName),expected);
     }
 
-
     protected final CharSequence anyxmlNode(final String name, final String value) throws IllegalArgumentException {
         return invoke(STREAM, "anyxmlNode", escape(name),name);
     }
@@ -123,11 +120,11 @@ abstract class DataObjectSerializerSource extends AbstractSource {
     }
 
     protected final CharSequence forEach(final String iterable,final Type valueType,final CharSequence body) {
-        return forEach(iterable,ITERATOR,valueType.getFullyQualifiedName(),CURRENT,body);
+        return forEach(iterable, ITERATOR, valueType.getFullyQualifiedName(), CURRENT, body);
     }
 
     protected final CharSequence classReference(final Type type) {
-        return new StringBuilder().append(type.getFullyQualifiedName()).append(".class");
+        return type.getFullyQualifiedName() + ".class";
     }
 
     protected final CharSequence staticInvokeEmitter(final Type childType, final String name) {
index b9bbbace0e354683e586803c5c39a67b0c4683cb..a6073c667e452418d65db565f640bec9aaabb06c 100644 (file)
@@ -64,7 +64,7 @@ public class StreamWriterGenerator extends AbstractStreamWriterGenerator {
     @Override
     protected DataObjectSerializerSource generateContainerSerializer(final GeneratedType type, final ContainerSchemaNode node) {
 
-        return new AugmentableDataNodeContainerEmmiterSource(this, type, node) {
+        return new AugmentableDataNodeContainerEmitterSource(this, type, node) {
             @Override
             public CharSequence emitStartEvent() {
                 return startContainerNode(classReference(type), getChildSizeFromSchema(node));
@@ -75,7 +75,7 @@ public class StreamWriterGenerator extends AbstractStreamWriterGenerator {
     @Override
     protected DataObjectSerializerSource generateNotificationSerializer(final GeneratedType type, final NotificationDefinition node) {
 
-        return new AugmentableDataNodeContainerEmmiterSource(this, type, node) {
+        return new AugmentableDataNodeContainerEmitterSource(this, type, node) {
             @Override
             public CharSequence emitStartEvent() {
                 return startContainerNode(classReference(type), getChildSizeFromSchema(node));
@@ -85,7 +85,7 @@ public class StreamWriterGenerator extends AbstractStreamWriterGenerator {
 
     @Override
     protected DataObjectSerializerSource generateCaseSerializer(final GeneratedType type, final ChoiceCaseNode node) {
-        return new AugmentableDataNodeContainerEmmiterSource(this, type, node) {
+        return new AugmentableDataNodeContainerEmitterSource(this, type, node) {
             @Override
             public CharSequence emitStartEvent() {
                 return startCaseNode(classReference(type),getChildSizeFromSchema(node));
@@ -95,7 +95,7 @@ public class StreamWriterGenerator extends AbstractStreamWriterGenerator {
 
     @Override
     protected DataObjectSerializerSource generateUnkeyedListEntrySerializer(final GeneratedType type, final ListSchemaNode node) {
-        return new AugmentableDataNodeContainerEmmiterSource(this, type, node) {
+        return new AugmentableDataNodeContainerEmitterSource(this, type, node) {
 
             @Override
             public CharSequence emitStartEvent() {
@@ -117,7 +117,7 @@ public class StreamWriterGenerator extends AbstractStreamWriterGenerator {
 
     @Override
     protected DataObjectSerializerSource generateMapEntrySerializer(final GeneratedType type, final ListSchemaNode node) {
-        return new AugmentableDataNodeContainerEmmiterSource(this, type, node) {
+        return new AugmentableDataNodeContainerEmitterSource(this, type, node) {
             @Override
             public CharSequence emitStartEvent() {
                 return startMapEntryNode(invoke(INPUT, "getKey"), getChildSizeFromSchema(node));
index feb731f0b97f6ae7a5483d92513f363bb520109a..dd9e41d0da337920bdd9dff2e7f728990f86dc45 100644 (file)
@@ -8,19 +8,27 @@
 package org.opendaylight.yangtools.binding.data.codec.impl;
 
 import com.google.common.base.Preconditions;
+import org.opendaylight.yangtools.yang.binding.Augmentation;
+import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 
-final class AugmentationNodeContext extends DataObjectCodecContext<AugmentationSchema> {
+final class AugmentationNodeContext<D extends DataObject & Augmentation<?>> extends DataObjectCodecContext<D,AugmentationSchema> {
 
     public AugmentationNodeContext(final DataContainerCodecPrototype<AugmentationSchema> prototype) {
         super(prototype);
     }
 
     @Override
-    protected Object dataFromNormalizedNode(final NormalizedNode<?, ?> normalizedNode) {
+    public D deserialize(final NormalizedNode<?, ?> normalizedNode) {
         Preconditions.checkArgument(normalizedNode instanceof AugmentationNode);
         return createBindingProxy((AugmentationNode)normalizedNode);
     }
+
+    @Override
+    protected Object deserializeObject(NormalizedNode<?, ?> normalizedNode) {
+        return deserialize(normalizedNode);
+    }
+
 }
\ No newline at end of file
index 956b27bc31e586a53d9a7b2faf57af281b98e973..e0e0c97777e2dfab31450eefb1480c7f954fabee 100644 (file)
@@ -22,6 +22,8 @@ import java.util.Map.Entry;
 import java.util.concurrent.Callable;
 import javax.annotation.Nonnull;
 import javax.annotation.Nullable;
+import org.opendaylight.yangtools.binding.data.codec.api.BindingCodecTree;
+import org.opendaylight.yangtools.binding.data.codec.api.BindingCodecTreeNode;
 import org.opendaylight.yangtools.binding.data.codec.impl.NodeCodecContext.CodecContextFactory;
 import org.opendaylight.yangtools.concepts.Codec;
 import org.opendaylight.yangtools.concepts.Immutable;
@@ -31,6 +33,8 @@ import org.opendaylight.yangtools.util.ClassLoaderUtils;
 import org.opendaylight.yangtools.yang.binding.BindingMapping;
 import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
 import org.opendaylight.yangtools.yang.binding.DataContainer;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.DataObjectSerializer;
 import org.opendaylight.yangtools.yang.binding.Identifiable;
 import org.opendaylight.yangtools.yang.binding.Identifier;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
@@ -57,20 +61,22 @@ import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-final class BindingCodecContext implements CodecContextFactory, Immutable {
+final class BindingCodecContext implements CodecContextFactory, BindingCodecTree, Immutable {
     private static final Logger LOG = LoggerFactory.getLogger(BindingCodecContext.class);
     static final String GETTER_PREFIX = "get";
 
     private final Codec<YangInstanceIdentifier, InstanceIdentifier<?>> instanceIdentifierCodec;
     private final Codec<QName, Class<?>> identityCodec;
+    private final BindingNormalizedNodeCodecRegistry registry;
     private final BindingRuntimeContext context;
-    private final SchemaRootCodecContext root;
+    private final SchemaRootCodecContext<?> root;
 
-    public BindingCodecContext(final BindingRuntimeContext context) {
+    BindingCodecContext(final BindingRuntimeContext context, BindingNormalizedNodeCodecRegistry registry) {
         this.context = Preconditions.checkNotNull(context, "Binding Runtime Context is required.");
         this.root = SchemaRootCodecContext.create(this);
         this.identityCodec = new IdentityCodec(context);
         this.instanceIdentifierCodec = new InstanceIdentifierCodec(this);
+        this.registry = Preconditions.checkNotNull(registry);
     }
 
     @Override
@@ -86,36 +92,40 @@ final class BindingCodecContext implements CodecContextFactory, Immutable {
         return identityCodec;
     }
 
+    @SuppressWarnings({"rawtypes", "unchecked"})
+    @Override
+    public DataObjectSerializer getEventStreamSerializer(Class<?> type) {
+        return registry.getSerializer((Class) type);
+    }
+
     public Entry<YangInstanceIdentifier, BindingStreamEventWriter> newWriter(final InstanceIdentifier<?> path,
             final NormalizedNodeStreamWriter domWriter) {
         final LinkedList<YangInstanceIdentifier.PathArgument> yangArgs = new LinkedList<>();
-        final DataContainerCodecContext<?> codecContext = getCodecContextNode(path, yangArgs);
-        final BindingStreamEventWriter writer = new BindingToNormalizedStreamWriter(codecContext, domWriter);
-        return new SimpleEntry<>(YangInstanceIdentifier.create(yangArgs), writer);
+        final DataContainerCodecContext<?,?> codecContext = getCodecContextNode(path, yangArgs);
+        return new SimpleEntry<>(YangInstanceIdentifier.create(yangArgs), codecContext.createWriter(domWriter));
     }
 
     public BindingStreamEventWriter newWriterWithoutIdentifier(final InstanceIdentifier<?> path,
             final NormalizedNodeStreamWriter domWriter) {
-        return new BindingToNormalizedStreamWriter(getCodecContextNode(path, null), domWriter);
+        return getCodecContextNode(path, null).createWriter(domWriter);
     }
 
     BindingStreamEventWriter newRpcWriter(final Class<? extends DataContainer> rpcInputOrOutput,
             final NormalizedNodeStreamWriter domWriter) {
-        final NodeCodecContext schema = root.getRpc(rpcInputOrOutput);
-        return new BindingToNormalizedStreamWriter(schema, domWriter);
+        return root.getRpc(rpcInputOrOutput).createWriter(domWriter);
     }
 
     BindingStreamEventWriter newNotificationWriter(final Class<? extends Notification> notification,
             final NormalizedNodeStreamWriter domWriter) {
-        final NodeCodecContext schema = root.getNotification(notification);
-        return new BindingToNormalizedStreamWriter(schema, domWriter);
+        return root.getNotification(notification).createWriter(domWriter);
     }
 
-    public DataContainerCodecContext<?> getCodecContextNode(final InstanceIdentifier<?> binding,
+    public DataContainerCodecContext<?,?> getCodecContextNode(final InstanceIdentifier<?> binding,
             final List<YangInstanceIdentifier.PathArgument> builder) {
-        DataContainerCodecContext<?> currentNode = root;
+        DataContainerCodecContext<?,?> currentNode = root;
         for (final InstanceIdentifier.PathArgument bindingArg : binding.getPathArguments()) {
-            currentNode = currentNode.getIdentifierChild(bindingArg, builder);
+            currentNode = currentNode.bindingPathArgumentChild(bindingArg, builder);
+            Preconditions.checkArgument(currentNode != null, "Supplied Instance Identifier %s is not valid.",binding);
         }
         return currentNode;
     }
@@ -130,16 +140,17 @@ final class BindingCodecContext implements CodecContextFactory, Immutable {
      * @param bindingArguments Collection for traversed path arguments
      * @return Codec for target node, or @null if the node does not have a
      *         binding representation (choice, case, leaf).
+     *
      */
-    @Nullable NodeCodecContext getCodecContextNode(final @Nonnull YangInstanceIdentifier dom,
+    @Nullable NodeCodecContext<?> getCodecContextNode(final @Nonnull YangInstanceIdentifier dom,
             final @Nonnull Collection<InstanceIdentifier.PathArgument> bindingArguments) {
-        NodeCodecContext currentNode = root;
-        ListNodeCodecContext currentList = null;
+        NodeCodecContext<?> currentNode = root;
+        ListNodeCodecContext<?> currentList = null;
 
         for (final YangInstanceIdentifier.PathArgument domArg : dom.getPathArguments()) {
-            Preconditions.checkArgument(currentNode instanceof DataContainerCodecContext<?>, "Unexpected child of non-container node %s", currentNode);
-            final DataContainerCodecContext<?> previous = (DataContainerCodecContext<?>) currentNode;
-            final NodeCodecContext nextNode = previous.getYangIdentifierChild(domArg);
+            Preconditions.checkArgument(currentNode instanceof DataContainerCodecContext<?,?>, "Unexpected child of non-container node %s", currentNode);
+            final DataContainerCodecContext<?,?> previous = (DataContainerCodecContext<?,?>) currentNode;
+            final NodeCodecContext<?> nextNode = previous.yangPathArgumentChild(domArg);
 
             /*
              * List representation in YANG Instance Identifier consists of two
@@ -160,13 +171,13 @@ final class BindingCodecContext implements CodecContextFactory, Immutable {
             } else if (nextNode instanceof ListNodeCodecContext) {
                 // We enter list, we do not update current Node yet,
                 // since we need to verify
-                currentList = (ListNodeCodecContext) nextNode;
+                currentList = (ListNodeCodecContext<?>) nextNode;
             } else if (nextNode instanceof ChoiceNodeCodecContext) {
                 // We do not add path argument for choice, since
                 // it is not supported by binding instance identifier.
                 currentNode = nextNode;
-            } else if (nextNode instanceof DataContainerCodecContext<?>) {
-                bindingArguments.add(((DataContainerCodecContext<?>) nextNode).getBindingPathArgument(domArg));
+            } else if (nextNode instanceof DataContainerCodecContext<?,?>) {
+                bindingArguments.add(((DataContainerCodecContext<?,?>) nextNode).getBindingPathArgument(domArg));
                 currentNode = nextNode;
             } else if (nextNode instanceof LeafNodeCodecContext) {
                 LOG.debug("Instance identifier referencing a leaf is not representable (%s)", dom);
@@ -192,16 +203,16 @@ final class BindingCodecContext implements CodecContextFactory, Immutable {
         return currentNode;
     }
 
-    NotificationCodecContext getNotificationContext(final SchemaPath notification) {
+    NotificationCodecContext<?> getNotificationContext(final SchemaPath notification) {
         return root.getNotification(notification);
     }
 
-    ContainerNodeCodecContext getRpcDataContext(final SchemaPath path) {
+    ContainerNodeCodecContext<?> getRpcDataContext(final SchemaPath path) {
         return root.getRpc(path);
     }
 
     @Override
-    public ImmutableMap<String, LeafNodeCodecContext> getLeafNodes(final Class<?> parentClass,
+    public ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodes(final Class<?> parentClass,
             final DataNodeContainer childSchema) {
         final HashMap<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
         for (final DataSchemaNode leaf : childSchema.getChildNodes()) {
@@ -232,9 +243,9 @@ final class BindingCodecContext implements CodecContextFactory, Immutable {
         return GETTER_PREFIX + suffix;
     }
 
-    private ImmutableMap<String, LeafNodeCodecContext> getLeafNodesUsingReflection(final Class<?> parentClass,
+    private ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodesUsingReflection(final Class<?> parentClass,
             final Map<String, DataSchemaNode> getterToLeafSchema) {
-        final Map<String, LeafNodeCodecContext> leaves = new HashMap<>();
+        final Map<String, LeafNodeCodecContext<?>> leaves = new HashMap<>();
         for (final Method method : parentClass.getMethods()) {
             if (method.getParameterTypes().length == 0) {
                 final DataSchemaNode schema = getterToLeafSchema.get(method.getName());
@@ -255,7 +266,7 @@ final class BindingCodecContext implements CodecContextFactory, Immutable {
                     continue; // We do not have schema for leaf, so we will ignore it (eg. getClass, getImplementedInterface).
                 }
                 final Codec<Object, Object> codec = getCodec(valueType, schema);
-                final LeafNodeCodecContext leafNode = new LeafNodeCodecContext(schema, codec, method);
+                final LeafNodeCodecContext<?> leafNode = new LeafNodeCodecContext<>(schema, codec, method);
                 leaves.put(schema.getQName().getLocalName(), leafNode);
             }
         }
@@ -321,10 +332,27 @@ final class BindingCodecContext implements CodecContextFactory, Immutable {
         final Class<? extends Identifier<?>> identifier = ClassLoaderUtils.findFirstGenericArgument(listClz,
                 Identifiable.class);
         final Map<QName, ValueContext> valueCtx = new HashMap<>();
-        for (final LeafNodeCodecContext leaf : getLeafNodes(identifier, schema).values()) {
+        for (final LeafNodeCodecContext<?> leaf : getLeafNodes(identifier, schema).values()) {
             final QName name = leaf.getDomPathArgument().getNodeType();
             valueCtx.put(name, new ValueContext(identifier, leaf));
         }
         return new IdentifiableItemCodec(schema, identifier, listClz, valueCtx);
     }
+
+    @SuppressWarnings("unchecked")
+    @Override
+    public <T extends DataObject> BindingCodecTreeNode<T> getSubtreeCodec(InstanceIdentifier<T> path) {
+        // TODO Do we need defensive check here?
+        return (BindingCodecTreeNode<T>) getCodecContextNode(path, null);
+    }
+
+    @Override
+    public BindingCodecTreeNode<?> getSubtreeCodec(YangInstanceIdentifier path) {
+        return getCodecContextNode(path, null);
+    }
+
+    @Override
+    public BindingCodecTreeNode<?> getSubtreeCodec(SchemaPath path) {
+        throw new UnsupportedOperationException("Not implemented yet.");
+    }
 }
index 37145b3bed206a9e6dbc1a367360c2790285d44f..0c59f342bc74e10371494e315432964da30740a3 100644 (file)
@@ -18,10 +18,12 @@ import java.util.AbstractMap.SimpleEntry;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map.Entry;
+import org.opendaylight.yangtools.binding.data.codec.api.BindingCodecTreeFactory;
 import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeSerializer;
 import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeWriterFactory;
 import org.opendaylight.yangtools.binding.data.codec.gen.impl.DataObjectSerializerGenerator;
 import org.opendaylight.yangtools.concepts.Delegator;
+import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
 import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
 import org.opendaylight.yangtools.yang.binding.DataContainer;
@@ -32,6 +34,7 @@ import org.opendaylight.yangtools.yang.binding.DataObjectSerializerRegistry;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.binding.Notification;
+import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
@@ -44,16 +47,19 @@ import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-public class BindingNormalizedNodeCodecRegistry implements DataObjectSerializerRegistry, BindingNormalizedNodeWriterFactory, BindingNormalizedNodeSerializer {
+public class BindingNormalizedNodeCodecRegistry implements DataObjectSerializerRegistry,
+        BindingCodecTreeFactory, BindingNormalizedNodeWriterFactory,
+        BindingNormalizedNodeSerializer {
     private static final Logger LOG = LoggerFactory.getLogger(BindingNormalizedNodeCodecRegistry.class);
 
     private final DataObjectSerializerGenerator generator;
     private final LoadingCache<Class<? extends DataObject>, DataObjectSerializer> serializers;
-    private BindingCodecContext codecContext;
+    private volatile BindingCodecContext codecContext;
 
     public BindingNormalizedNodeCodecRegistry(final DataObjectSerializerGenerator generator) {
         this.generator = Preconditions.checkNotNull(generator);
@@ -70,7 +76,7 @@ public class BindingNormalizedNodeCodecRegistry implements DataObjectSerializerR
     }
 
     public void onBindingRuntimeContextUpdated(final BindingRuntimeContext context) {
-        codecContext = new BindingCodecContext(context);
+        codecContext = create(context);
         generator.onBindingRuntimeContextUpdated(context);
     }
 
@@ -172,7 +178,7 @@ public class BindingNormalizedNodeCodecRegistry implements DataObjectSerializerR
         }
 
         final List<PathArgument> builder = new ArrayList<>();
-        final NodeCodecContext codec = codecContext.getCodecContextNode(path, builder);
+        final NodeCodecContext<?> codec = codecContext.getCodecContextNode(path, builder);
         if (codec == null) {
             if (data != null) {
                 LOG.warn("Path {} does not have a binding equivalent, should have been caught earlier ({})", path, data.getClass());
@@ -180,21 +186,21 @@ public class BindingNormalizedNodeCodecRegistry implements DataObjectSerializerR
             return null;
         }
 
-        final DataObject lazyObj = (DataObject) codec.dataFromNormalizedNode(data);
+        final DataObject lazyObj = codec.deserialize(data);
         final InstanceIdentifier<?> bindingPath = InstanceIdentifier.create(builder);
         return new SimpleEntry<InstanceIdentifier<?>, DataObject>(bindingPath, lazyObj);
     }
 
     @Override
     public Notification fromNormalizedNodeNotification(final SchemaPath path, final ContainerNode data) {
-        final NotificationCodecContext codec = codecContext.getNotificationContext(path);
-        return (Notification) codec.dataFromNormalizedNode(data);
+        final NotificationCodecContext<?> codec = codecContext.getNotificationContext(path);
+        return codec.deserialize(data);
     }
 
     @Override
     public DataObject fromNormalizedNodeRpcData(final SchemaPath path, final ContainerNode data) {
-        final ContainerNodeCodecContext codec = codecContext.getRpcDataContext(path);
-        return (DataObject) codec.dataFromNormalizedNode(data);
+        final ContainerNodeCodecContext<?> codec = codecContext.getRpcDataContext(path);
+        return codec.deserialize(data);
     }
 
    @Override
@@ -213,40 +219,57 @@ public class BindingNormalizedNodeCodecRegistry implements DataObjectSerializerR
         return codecContext.newNotificationWriter(notification, streamWriter);
     }
 
-
     @Override
     public BindingStreamEventWriter newRpcWriter(final Class<? extends DataContainer> rpcInputOrOutput,
             final NormalizedNodeStreamWriter streamWriter) {
         return codecContext.newRpcWriter(rpcInputOrOutput,streamWriter);
     }
 
-
     public <T extends DataObject> Function<Optional<NormalizedNode<?, ?>>, Optional<T>>  deserializeFunction(final InstanceIdentifier<T> path) {
-        final DataObjectCodecContext<?> ctx = (DataObjectCodecContext<?>) codecContext.getCodecContextNode(path, null);
+        final DataObjectCodecContext<?,?> ctx = (DataObjectCodecContext<?,?>) codecContext.getCodecContextNode(path, null);
         return new DeserializeFunction<T>(ctx);
     }
 
+    @Override
+    public BindingCodecContext create(BindingRuntimeContext context) {
+        return new BindingCodecContext(context, this);
+    }
+
+    @Override
+    public BindingCodecContext create(SchemaContext context, Class<?>... bindingClasses) {
+        ModuleInfoBackedContext strategy = ModuleInfoBackedContext.create();
+        for (Class<?> bindingCls : bindingClasses) {
+            try {
+                strategy.registerModuleInfo(BindingReflections.getModuleInfo(bindingCls));
+            } catch (Exception e) {
+                throw new IllegalStateException(
+                        "Could not create BindingRuntimeContext from class " + bindingCls.getName(),
+                        e);
+            }
+        }
+        BindingRuntimeContext runtimeCtx = BindingRuntimeContext.create(strategy, context);
+        return create(runtimeCtx);
+    }
+
 
-    private static class DeserializeFunction<T> implements Function<Optional<NormalizedNode<?, ?>>, Optional<T>> {
-        private final DataObjectCodecContext<?> ctx;
+    private static final class DeserializeFunction<T> implements Function<Optional<NormalizedNode<?, ?>>, Optional<T>> {
+        private final DataObjectCodecContext<?,?> ctx;
 
-        public DeserializeFunction(final DataObjectCodecContext<?> ctx) {
-            super();
+        DeserializeFunction(final DataObjectCodecContext<?,?> ctx) {
             this.ctx = ctx;
         }
 
         @SuppressWarnings("unchecked")
         @Override
         public Optional<T> apply(final Optional<NormalizedNode<?, ?>> input) {
-            if(input.isPresent()) {
-                return Optional.of((T) ctx.dataFromNormalizedNode(input.get()));
+            if (input.isPresent()) {
+                return Optional.of((T) ctx.deserialize(input.get()));
             }
             return Optional.absent();
         }
     }
 
-    private class GeneratorLoader extends CacheLoader<Class<? extends DataContainer>, DataObjectSerializer> {
-
+    private final class GeneratorLoader extends CacheLoader<Class<? extends DataContainer>, DataObjectSerializer> {
         @Override
         public DataObjectSerializer load(final Class<? extends DataContainer> key) throws Exception {
             final DataObjectSerializerImplementation prototype = generator.getSerializer(key);
@@ -254,9 +277,7 @@ public class BindingNormalizedNodeCodecRegistry implements DataObjectSerializerR
         }
     }
 
-    private class DataObjectSerializerProxy implements DataObjectSerializer,
-            Delegator<DataObjectSerializerImplementation> {
-
+    private final class DataObjectSerializerProxy implements DataObjectSerializer, Delegator<DataObjectSerializerImplementation> {
         private final DataObjectSerializerImplementation delegate;
 
         DataObjectSerializerProxy(final DataObjectSerializerImplementation delegate) {
index a110ff8347bb2e5d7ba82fbb2c75b8e14a7c40fe..a608520a6315668cc71b613ef47ddf869301b66f 100644 (file)
@@ -30,21 +30,21 @@ import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStre
 class BindingToNormalizedStreamWriter implements BindingStreamEventWriter, Delegator<NormalizedNodeStreamWriter> {
 
     private final NormalizedNodeStreamWriter delegate;
-    private final Deque<NodeCodecContext> schema = new ArrayDeque<>();
-    private final NodeCodecContext rootNodeSchema;
+    private final Deque<NodeCodecContext<?>> schema = new ArrayDeque<>();
+    private final NodeCodecContext<?> rootNodeSchema;
 
-    public BindingToNormalizedStreamWriter(final NodeCodecContext schema, final NormalizedNodeStreamWriter delegate) {
+    public BindingToNormalizedStreamWriter(final NodeCodecContext<?> schema, final NormalizedNodeStreamWriter delegate) {
         this.delegate = Preconditions.checkNotNull(delegate, "Delegate must not be null");
         this.rootNodeSchema = Preconditions.checkNotNull(schema);
 
     }
 
-    private NodeCodecContext current() {
+    private NodeCodecContext<?> current() {
         return schema.peek();
     }
 
     private NodeIdentifier duplicateSchemaEnter() {
-        final NodeCodecContext next;
+        final NodeCodecContext<?> next;
         if (current() == null) {
             // Entry of first node
             next = rootNodeSchema;
@@ -55,25 +55,25 @@ class BindingToNormalizedStreamWriter implements BindingStreamEventWriter, Deleg
         return (NodeIdentifier) current().getDomPathArgument();
     }
 
+    @SuppressWarnings({"unchecked", "rawtypes"})
     private <T extends YangInstanceIdentifier.PathArgument> T enter(final Class<?> name, final Class<T> identifier) {
-        final NodeCodecContext next;
+        final NodeCodecContext<?> next;
         if (current() == null) {
             // Entry of first node
             next = rootNodeSchema;
         } else {
             Preconditions.checkArgument((current() instanceof DataContainerCodecContext), "Could not start node %s",
                     name);
-            next = ((DataContainerCodecContext<?>) current()).getStreamChild(name);
+            next = ((DataContainerCodecContext<?,?>) current()).streamChild((Class) name);
         }
         this.schema.push(next);
-        @SuppressWarnings("unchecked")
         T arg = (T) next.getDomPathArgument();
         return arg;
     }
 
     private <T extends YangInstanceIdentifier.PathArgument> T enter(final String localName, final Class<T> identifier) {
-        NodeCodecContext current = current();
-        NodeCodecContext next = ((DataObjectCodecContext<?>) current).getLeafChild(localName);
+        NodeCodecContext<?> current = current();
+        NodeCodecContext<?> next = ((DataObjectCodecContext<?,?>) current).getLeafChild(localName);
         this.schema.push(next);
         @SuppressWarnings("unchecked")
         T arg = (T) next.getDomPathArgument();
@@ -82,7 +82,7 @@ class BindingToNormalizedStreamWriter implements BindingStreamEventWriter, Deleg
 
     @Override
     public void endNode() throws IOException {
-        NodeCodecContext left = schema.pop();
+        NodeCodecContext<?> left = schema.pop();
         // NormalizedNode writer does not have entry into case, but into choice
         // so for leaving case, we do not emit endNode.
         if (!(left instanceof CaseNodeCodecContext)) {
@@ -96,10 +96,10 @@ class BindingToNormalizedStreamWriter implements BindingStreamEventWriter, Deleg
     }
 
     private Map.Entry<NodeIdentifier, Object> serializeLeaf(final String localName, final Object value) {
-        Preconditions.checkArgument(current() instanceof DataObjectCodecContext<?>);
+        Preconditions.checkArgument(current() instanceof DataObjectCodecContext);
 
-        DataObjectCodecContext<?> currentCasted = (DataObjectCodecContext<?>) current();
-        LeafNodeCodecContext leafContext = currentCasted.getLeafChild(localName);
+        DataObjectCodecContext<?,?> currentCasted = (DataObjectCodecContext<?,?>) current();
+        LeafNodeCodecContext<?> leafContext = currentCasted.getLeafChild(localName);
 
         NodeIdentifier domArg = (NodeIdentifier) leafContext.getDomPathArgument();
         Object domValue = leafContext.getValueCodec().serialize(value);
@@ -120,7 +120,7 @@ class BindingToNormalizedStreamWriter implements BindingStreamEventWriter, Deleg
 
     @Override
     public void leafSetEntryNode(final Object value) throws IOException, IllegalArgumentException {
-        LeafNodeCodecContext ctx = (LeafNodeCodecContext) current();
+        LeafNodeCodecContext<?> ctx = (LeafNodeCodecContext<?>) current();
         getDelegate().leafSetEntryNode(ctx.getValueCodec().serialize(value));
     }
 
@@ -156,7 +156,7 @@ class BindingToNormalizedStreamWriter implements BindingStreamEventWriter, Deleg
     @Override
     public void startMapEntryNode(final Identifier<?> key, final int childSizeHint) throws IOException, IllegalArgumentException {
         duplicateSchemaEnter();
-        NodeIdentifierWithPredicates identifier = ((KeyedListNodeCodecContext) current()).serialize(key);
+        NodeIdentifierWithPredicates identifier = ((KeyedListNodeCodecContext<?>) current()).serialize(key);
         getDelegate().startMapEntryNode(identifier, childSizeHint);
     };
 
index c8eb336d8a9dbec76b14dc84d24a6b3f7f527592..d8b1455fd6ded2bdd54a830ae8c1499965398a04 100644 (file)
@@ -9,7 +9,6 @@ package org.opendaylight.yangtools.binding.data.codec.impl;
 
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableSortedMap;
-
 import java.lang.reflect.Constructor;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
@@ -19,7 +18,6 @@ import java.util.Set;
 import java.util.SortedMap;
 import java.util.TreeMap;
 import java.util.concurrent.Callable;
-
 import org.opendaylight.yangtools.binding.data.codec.impl.ValueTypeCodec.SchemaUnawareCodec;
 import org.opendaylight.yangtools.yang.binding.BindingMapping;
 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
@@ -84,12 +82,7 @@ class BitsCodec extends ReflectionBasedCodec implements SchemaUnawareCodec {
          * for construction of bits object.
          */
         for (String value : valueGetters.keySet()) {
-            if (casted.contains(value)) {
-                args[currentArg] = Boolean.TRUE;
-            } else {
-                args[currentArg] = Boolean.FALSE;
-            }
-            currentArg++;
+            args[currentArg++] = casted.contains(value);
         }
 
         try {
diff --git a/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/CachingNormalizedNodeCodecImpl.java b/code-generator/binding-data-codec/src/main/java/org/opendaylight/yangtools/binding/data/codec/impl/CachingNormalizedNodeCodecImpl.java
new file mode 100644 (file)
index 0000000..0beb463
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.binding.data.codec.impl;
+
+import com.google.common.base.Preconditions;
+import java.util.Set;
+import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeCachingCodec;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+
+class CachingNormalizedNodeCodecImpl<D extends DataObject> implements BindingNormalizedNodeCachingCodec<D>{
+
+    private final Set<Class<? extends DataObject>> cachedValues;
+    private final DataContainerCodecContext<D, ?> context;
+
+    CachingNormalizedNodeCodecImpl(DataContainerCodecContext<D, ?> subtreeRoot, Set<Class<? extends DataObject>> cacheSpec) {
+        this.context = Preconditions.checkNotNull(subtreeRoot);
+        this.cachedValues = Preconditions.checkNotNull(cacheSpec);
+    }
+
+    @Override
+    public D deserialize(NormalizedNode<?, ?> data) {
+        return context.deserialize(data);
+    }
+
+    @Override
+    public NormalizedNode<?, ?> serialize(D data) {
+        // FIXME: Add real-class based serialization.
+        return context.serialize(data);
+    }
+
+    @Override
+    public void close() {
+        // NOOP as of now.
+    }
+
+}
index 86d8098fc2b769cc7e3ecd583cf9625733b09c71..1b84553f1151df8ceb1d9ec108896ef56fd55cd2 100644 (file)
@@ -9,12 +9,13 @@ package org.opendaylight.yangtools.binding.data.codec.impl;
 
 import com.google.common.base.Preconditions;
 import java.util.List;
+import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
 
-final class CaseNodeCodecContext extends DataObjectCodecContext<ChoiceCaseNode> {
+final class CaseNodeCodecContext<D extends DataObject> extends DataObjectCodecContext<D,ChoiceCaseNode> {
     public CaseNodeCodecContext(final DataContainerCodecPrototype<ChoiceCaseNode> prototype) {
         super(prototype);
     }
@@ -26,8 +27,13 @@ final class CaseNodeCodecContext extends DataObjectCodecContext<ChoiceCaseNode>
     }
 
     @Override
-    protected Object dataFromNormalizedNode(final NormalizedNode<?, ?> normalizedNode) {
+    public D deserialize(final NormalizedNode<?, ?> normalizedNode) {
         Preconditions.checkState(normalizedNode instanceof ChoiceNode);
         return createBindingProxy((ChoiceNode) normalizedNode);
     }
+
+    @Override
+    protected Object deserializeObject(NormalizedNode<?, ?> normalizedNode) {
+        return deserialize(normalizedNode);
+    }
 }
\ No newline at end of file
index 8bc5b0872117edd80e099d9977b92603546f6cb7..60da344ba109f300920fa1ee27c4e89ddaa2eb67 100644 (file)
@@ -11,13 +11,13 @@ import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Iterables;
-
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Set;
-
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
@@ -25,25 +25,25 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdent
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-final class ChoiceNodeCodecContext extends DataContainerCodecContext<ChoiceNode> {
+final class ChoiceNodeCodecContext<D extends DataObject> extends DataContainerCodecContext<D,ChoiceSchemaNode> {
     private static final Logger LOG = LoggerFactory.getLogger(ChoiceNodeCodecContext.class);
     private final ImmutableMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangCaseChild;
     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byClass;
     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byCaseChildClass;
 
-    public ChoiceNodeCodecContext(final DataContainerCodecPrototype<ChoiceNode> prototype) {
+    public ChoiceNodeCodecContext(final DataContainerCodecPrototype<ChoiceSchemaNode> prototype) {
         super(prototype);
         Map<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangCaseChildBuilder = new HashMap<>();
         Map<Class<?>, DataContainerCodecPrototype<?>> byClassBuilder = new HashMap<>();
         Map<Class<?>, DataContainerCodecPrototype<?>> byCaseChildClassBuilder = new HashMap<>();
         Set<Class<?>> potentialSubstitutions = new HashSet<>();
         // Walks all cases for supplied choice in current runtime context
-        for (Class<?> caze : factory().getRuntimeContext().getCases(bindingClass())) {
+        for (Class<?> caze : factory().getRuntimeContext().getCases(getBindingClass())) {
             // We try to load case using exact match thus name
             // and original schema must equals
             DataContainerCodecPrototype<ChoiceCaseNode> cazeDef = loadCase(caze);
@@ -52,7 +52,9 @@ final class ChoiceNodeCodecContext extends DataContainerCodecContext<ChoiceNode>
             if (cazeDef != null) {
                 byClassBuilder.put(cazeDef.getBindingClass(), cazeDef);
                 // Updates collection of case children
-                for (Class<? extends DataObject> cazeChild : BindingReflections.getChildrenClasses((Class<? extends DataObject>) caze)) {
+                @SuppressWarnings("unchecked")
+                Class<? extends DataObject> cazeCls = (Class<? extends DataObject>) caze;
+                for (Class<? extends DataObject> cazeChild : BindingReflections.getChildrenClasses(cazeCls)) {
                     byCaseChildClassBuilder.put(cazeChild, cazeDef);
                 }
                 // Updates collection of YANG instance identifier to case
@@ -90,18 +92,23 @@ final class ChoiceNodeCodecContext extends DataContainerCodecContext<ChoiceNode>
         byCaseChildClass = ImmutableMap.copyOf(byCaseChildClassBuilder);
     }
 
+
+    @SuppressWarnings("unchecked")
     @Override
-    protected DataContainerCodecContext<?> getStreamChild(final Class<?> childClass) {
+    public <DV extends DataObject> DataContainerCodecContext<DV, ?> streamChild(Class<DV> childClass) {
         DataContainerCodecPrototype<?> child = byClass.get(childClass);
         Preconditions.checkArgument(child != null,"Supplied class is not valid case",childClass);
-        return child.get();
+        return (DataContainerCodecContext<DV, ?>) child.get();
     }
 
+
+    @SuppressWarnings("unchecked")
     @Override
-    protected Optional<DataContainerCodecContext<?>> getPossibleStreamChild(final Class<?> childClass) {
+    public <DV extends DataObject> Optional<DataContainerCodecContext<DV, ?>> possibleStreamChild(
+            Class<DV> childClass) {
         DataContainerCodecPrototype<?> child = byClass.get(childClass);
         if(child != null) {
-            return Optional.<DataContainerCodecContext<?>>of(child.get());
+            return Optional.<DataContainerCodecContext<DV,?>>of((DataContainerCodecContext<DV, ?>) child.get());
         }
         return Optional.absent();
     }
@@ -121,14 +128,15 @@ final class ChoiceNodeCodecContext extends DataContainerCodecContext<ChoiceNode>
     }
 
     @Override
-    protected NodeCodecContext getYangIdentifierChild(final YangInstanceIdentifier.PathArgument arg) {
+    public NodeCodecContext<?> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
         DataContainerCodecPrototype<?> cazeProto = byYangCaseChild.get(arg);
         Preconditions.checkArgument(cazeProto != null, "Argument %s is not valid child of %s", arg, schema());
-        return cazeProto.get().getYangIdentifierChild(arg);
+        return cazeProto.get().yangPathArgumentChild(arg);
     }
 
+    @SuppressWarnings("unchecked")
     @Override
-    protected Object dataFromNormalizedNode(final NormalizedNode<?, ?> data) {
+    public D deserialize(final NormalizedNode<?, ?> data) {
         Preconditions
                 .checkArgument(data instanceof org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode);
         NormalizedNodeContainer<?, ?, NormalizedNode<?,?>> casted = (NormalizedNodeContainer<?, ?, NormalizedNode<?,?>>) data;
@@ -138,11 +146,20 @@ final class ChoiceNodeCodecContext extends DataContainerCodecContext<ChoiceNode>
             return null;
         }
         DataContainerCodecPrototype<?> caze = byYangCaseChild.get(first.getIdentifier());
-        return caze.get().dataFromNormalizedNode(data);
+        return (D) caze.get().deserialize(data);
     }
 
-    public DataContainerCodecContext<?> getCazeByChildClass(final Class<? extends DataObject> type) {
-        return byCaseChildClass.get(type).get();
+    @Nullable DataContainerCodecContext<?,?> getCazeByChildClass(final @Nonnull Class<? extends DataObject> type) {
+        final DataContainerCodecPrototype<?> protoCtx = byCaseChildClass.get(type);
+        if(protoCtx != null) {
+            return protoCtx.get();
+        }
+        return null;
+    }
+
+    @Override
+    protected Object deserializeObject(NormalizedNode<?, ?> normalizedNode) {
+        return deserialize(normalizedNode);
     }
 
 }
index f70e7ce996818985b57ed74cfad405de87d7d95a..a179d9af59aed819d224fc13699160f9e13cfd0a 100644 (file)
@@ -8,20 +8,26 @@
 package org.opendaylight.yangtools.binding.data.codec.impl;
 
 import com.google.common.base.Preconditions;
+import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 
-final class ContainerNodeCodecContext extends DataObjectCodecContext<ContainerSchemaNode> {
+final class ContainerNodeCodecContext<D extends DataObject> extends DataObjectCodecContext<D,ContainerSchemaNode> {
 
     ContainerNodeCodecContext(final DataContainerCodecPrototype<ContainerSchemaNode> prototype) {
         super(prototype);
     }
 
     @Override
-    protected Object dataFromNormalizedNode(final NormalizedNode<?, ?> data) {
+    public D deserialize(final NormalizedNode<?, ?> data) {
         Preconditions.checkState(data instanceof ContainerNode);
         return createBindingProxy((ContainerNode) data);
     }
 
+    @Override
+    protected Object deserializeObject(NormalizedNode<?, ?> normalizedNode) {
+        return deserialize(normalizedNode);
+    }
+
 }
\ No newline at end of file
index e873126598ba7f8cac91c29a1cbf7983c39e56ed..455cf674bbf7494ab335bc1123ad2d99bafddb31 100644 (file)
@@ -8,16 +8,28 @@
 package org.opendaylight.yangtools.binding.data.codec.impl;
 
 import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableCollection;
+import com.google.common.collect.ImmutableSet;
+import java.io.IOException;
 import java.util.List;
+import javax.annotation.Nullable;
+import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeCachingCodec;
 import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.DataObjectSerializer;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.common.QNameModule;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
+import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
+import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
 
-abstract class DataContainerCodecContext<T> extends NodeCodecContext {
+abstract class DataContainerCodecContext<D extends DataObject,T> extends NodeCodecContext<D>  {
 
     private final DataContainerCodecPrototype<T> prototype;
+    private volatile DataObjectSerializer eventStreamSerializer;
 
     protected DataContainerCodecContext(final DataContainerCodecPrototype<T> prototype) {
         this.prototype = prototype;
@@ -47,23 +59,28 @@ abstract class DataContainerCodecContext<T> extends NodeCodecContext {
      * @return Context of child
      * @throws IllegalArgumentException If supplied argument does not represent valid child.
      */
-    protected abstract NodeCodecContext getYangIdentifierChild(final YangInstanceIdentifier.PathArgument arg);
+    @Override
+    public abstract NodeCodecContext<?> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg);
 
     /**
      * Returns nested node context using supplied Binding Instance Identifier
      * and adds YANG instance identifiers to supplied list.
      *
      * @param arg Binding Instance Identifier Argument
-     * @return Context of child
+     * @return Context of child or null if supplied {@code arg} does not represent valid child.
      * @throws IllegalArgumentException If supplied argument does not represent valid child.
      */
-    protected  DataContainerCodecContext<?> getIdentifierChild(final InstanceIdentifier.PathArgument arg,
+    @Override
+    public @Nullable DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
             final List<YangInstanceIdentifier.PathArgument> builder) {
-        final DataContainerCodecContext<?> child = getStreamChild(arg.getType());
-        if (builder != null) {
-            child.addYangPathArgument(arg,builder);
+        final DataContainerCodecContext<?,?> child = streamChild(arg.getType());
+        if(child != null) {
+            if (builder != null) {
+                child.addYangPathArgument(arg,builder);
+            }
+            return child;
         }
-        return child;
+        throw new IllegalArgumentException("SUpplied argument is not valid child");
     }
 
     /**
@@ -80,8 +97,10 @@ abstract class DataContainerCodecContext<T> extends NodeCodecContext {
         return prototype.getBindingArg();
     }
 
-    protected final Class<?> bindingClass() {
-        return prototype.getBindingClass();
+    @SuppressWarnings("unchecked")
+    @Override
+    public final Class<D> getBindingClass() {
+        return Class.class.cast(prototype.getBindingClass());
     }
 
     /**
@@ -91,25 +110,62 @@ abstract class DataContainerCodecContext<T> extends NodeCodecContext {
      * must issue getChild(ChoiceClass).getChild(CaseClass).
      *
      * @param childClass
-     * @return Context of child
+     * @return Context of child node or null, if supplied class is not subtree child
      * @throws IllegalArgumentException If supplied child class is not valid in specified context.
      */
-    protected abstract DataContainerCodecContext<?> getStreamChild(final Class<?> childClass) throws IllegalArgumentException;
+    @Override
+    public abstract @Nullable <DV extends DataObject> DataContainerCodecContext<DV,?> streamChild(final Class<DV> childClass) throws IllegalArgumentException;
 
     /**
-    *
-    * Returns child context as if it was walked by
-    * {@link BindingStreamEventWriter}. This means that to enter case, one
-    * must issue getChild(ChoiceClass).getChild(CaseClass).
-    *
-    * @param childClass
-    * @return Context of child or Optional absent is supplied class is not applicable in context.
-    */
-   protected abstract Optional<DataContainerCodecContext<?>> getPossibleStreamChild(final Class<?> childClass);
+     *
+     * Returns child context as if it was walked by
+     * {@link BindingStreamEventWriter}. This means that to enter case, one
+     * must issue getChild(ChoiceClass).getChild(CaseClass).
+     *
+     * @param childClass
+     * @return Context of child or Optional absent is supplied class is not applicable in context.
+     */
+    @Override
+    public abstract <DV extends DataObject> Optional<DataContainerCodecContext<DV,?>> possibleStreamChild(final Class<DV> childClass);
 
     @Override
     public String toString() {
         return getClass().getSimpleName() + " [" + prototype.getBindingClass() + "]";
     }
 
+    @Override
+    public BindingNormalizedNodeCachingCodec<D> createCachingCodec(
+            ImmutableCollection<Class<? extends DataObject>> cacheSpecifier) {
+        return new CachingNormalizedNodeCodecImpl<D>(this,ImmutableSet.copyOf(cacheSpecifier));
+    }
+
+    BindingStreamEventWriter createWriter(NormalizedNodeStreamWriter domWriter) {
+        return  new BindingToNormalizedStreamWriter(this, domWriter);
+    }
+
+    DataObjectSerializer eventStreamSerializer() {
+        if(eventStreamSerializer == null) {
+            eventStreamSerializer = factory().getEventStreamSerializer(getBindingClass());
+        }
+        return eventStreamSerializer;
+    }
+
+    @Override
+    public NormalizedNode<?, ?> serialize(D data) {
+        final NormalizedNodeResult result = new NormalizedNodeResult();
+        // We create DOM stream writer which produces normalized nodes
+        final NormalizedNodeStreamWriter domWriter = ImmutableNormalizedNodeStreamWriter.from(result);
+        writeAsNormalizedNode(data, domWriter);
+        return result.getResult();
+    }
+
+    @Override
+    public void writeAsNormalizedNode(D data, NormalizedNodeStreamWriter writer) {
+        try {
+            eventStreamSerializer().serialize(data, createWriter(writer));
+        } catch (IOException e) {
+            throw new IllegalStateException("Failed to serialize Binding DTO",e);
+        }
+    }
+
 }
\ No newline at end of file
index 7abe3d382a0273ace9aa1c37afaa926b7d447d61..2b2c54985857b7b80a3f4c7aeae0ecefec343c6a 100644 (file)
@@ -20,14 +20,14 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdent
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
-class DataContainerCodecPrototype<T> implements NodeContextSupplier {
+final class DataContainerCodecPrototype<T> implements NodeContextSupplier {
 
     private final T schema;
     private final QNameModule namespace;
@@ -35,8 +35,9 @@ class DataContainerCodecPrototype<T> implements NodeContextSupplier {
     private final Class<?> bindingClass;
     private final InstanceIdentifier.Item<?> bindingArg;
     private final YangInstanceIdentifier.PathArgument yangArg;
-    private volatile DataContainerCodecContext<T> instance = null;
+    private volatile DataContainerCodecContext<?,T> instance = null;
 
+    @SuppressWarnings({"rawtypes", "unchecked"})
     private DataContainerCodecPrototype(final Class<?> cls, final YangInstanceIdentifier.PathArgument arg, final T nodeSchema,
             final CodecContextFactory factory) {
         super();
@@ -53,8 +54,9 @@ class DataContainerCodecPrototype<T> implements NodeContextSupplier {
         }
     }
 
+    @SuppressWarnings({"rawtypes", "unchecked"})
     private DataContainerCodecPrototype(final Class<?> cls, final YangInstanceIdentifier.PathArgument arg, final T nodeSchema,
-            final CodecContextFactory factory,final DataContainerCodecContext<T> instance) {
+            final CodecContextFactory factory,final DataContainerCodecContext<?,T> instance) {
         super();
         this.yangArg = arg;
         this.schema = nodeSchema;
@@ -115,8 +117,8 @@ class DataContainerCodecPrototype<T> implements NodeContextSupplier {
     }
 
     @Override
-    public DataContainerCodecContext<T> get() {
-        DataContainerCodecContext<T> tmp = instance;
+    public DataContainerCodecContext<?,T> get() {
+        DataContainerCodecContext<?,T> tmp = instance;
         if (tmp == null) {
             synchronized (this) {
                 tmp = instance;
@@ -132,27 +134,27 @@ class DataContainerCodecPrototype<T> implements NodeContextSupplier {
 
     @GuardedBy("this")
     @SuppressWarnings({ "rawtypes", "unchecked" })
-    private DataContainerCodecContext createInstance() {
+    private DataContainerCodecContext<?,T> createInstance() {
         // FIXME: make protected abstract
         if (schema instanceof ContainerSchemaNode) {
-            return new ContainerNodeCodecContext((DataContainerCodecPrototype) this);
+            return new ContainerNodeCodecContext(this);
         } else if (schema instanceof ListSchemaNode) {
             if (Identifiable.class.isAssignableFrom(getBindingClass())) {
-                return new KeyedListNodeCodecContext((DataContainerCodecPrototype) this);
+                return new KeyedListNodeCodecContext(this);
             } else {
-                return new ListNodeCodecContext((DataContainerCodecPrototype) this);
+                return new ListNodeCodecContext(this);
             }
-        } else if (schema instanceof ChoiceNode) {
-            return new ChoiceNodeCodecContext((DataContainerCodecPrototype) this);
+        } else if (schema instanceof ChoiceSchemaNode) {
+            return new ChoiceNodeCodecContext(this);
         } else if (schema instanceof AugmentationSchema) {
-            return new AugmentationNodeContext((DataContainerCodecPrototype) this);
+            return new AugmentationNodeContext(this);
         } else if (schema instanceof ChoiceCaseNode) {
-            return new CaseNodeCodecContext((DataContainerCodecPrototype) this);
+            return new CaseNodeCodecContext(this);
         }
         throw new IllegalArgumentException("Unsupported type " + bindingClass + " " + schema);
     }
 
     boolean isChoice() {
-        return schema instanceof ChoiceNode;
+        return schema instanceof ChoiceSchemaNode;
     }
 }
index e5d58cc82f3cd15e60fcae946e588d9e20bcd47b..6066064c8076daf4b482c8633f10b8abecb52cd2 100644 (file)
@@ -49,7 +49,7 @@ import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-abstract class DataObjectCodecContext<T extends DataNodeContainer> extends DataContainerCodecContext<T> {
+abstract class DataObjectCodecContext<D extends DataObject,T extends DataNodeContainer> extends DataContainerCodecContext<D,T> {
     private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
     private static final Lookup LOOKUP = MethodHandles.publicLookup();
     private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class);
@@ -61,64 +61,54 @@ abstract class DataObjectCodecContext<T extends DataNodeContainer> extends DataC
         }
     };
 
-    private final ImmutableMap<String, LeafNodeCodecContext> leafChild;
+    private final ImmutableMap<String, LeafNodeCodecContext<?>> leafChild;
     private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
     private final ImmutableSortedMap<Method, NodeContextSupplier> byMethod;
     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
     private final MethodHandle proxyConstructor;
 
-    // FIXME: this field seems to be unused
-    private final Method augmentationGetter;
-
     protected DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
         super(prototype);
 
-        this.leafChild = factory().getLeafNodes(bindingClass(), schema());
+        this.leafChild = factory().getLeafNodes(getBindingClass(), schema());
 
-        Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(bindingClass());
+        final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(getBindingClass());
 
-        Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
-        SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
-        Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
-        Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
+        final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
+        final SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
+        final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
+        final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
 
         // Adds leaves to mapping
-        for (LeafNodeCodecContext leaf : leafChild.values()) {
+        for (final LeafNodeCodecContext<?> leaf : leafChild.values()) {
             byMethodBuilder.put(leaf.getGetter(), leaf);
             byYangBuilder.put(leaf.getDomPathArgument(), leaf);
         }
 
-        for (Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
-            DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
+        for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
+            final DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
             byMethodBuilder.put(childDataObj.getValue(), childProto);
             byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
             byYangBuilder.put(childProto.getYangArg(), childProto);
             if (childProto.isChoice()) {
-                ChoiceNodeCodecContext choice = (ChoiceNodeCodecContext) childProto.get();
-                for(Class<?> cazeChild : choice.getCaseChildrenClasses()) {
+                final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
+                for(final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
                     byBindingArgClassBuilder.put(cazeChild, childProto);
                 }
             }
         }
         this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder);
-        if (Augmentable.class.isAssignableFrom(bindingClass())) {
-            try {
-                augmentationGetter = bindingClass().getMethod("getAugmentation", Class.class);
-            } catch (NoSuchMethodException | SecurityException e) {
-               throw new IllegalStateException("Could not get required method.",e);
-            }
-            ImmutableMap<AugmentationIdentifier, Type> augmentations = factory().getRuntimeContext()
+        if (Augmentable.class.isAssignableFrom(getBindingClass())) {
+            final ImmutableMap<AugmentationIdentifier, Type> augmentations = factory().getRuntimeContext()
                     .getAvailableAugmentationTypes(schema());
-            for (Entry<AugmentationIdentifier, Type> augment : augmentations.entrySet()) {
-                DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
+            for (final Entry<AugmentationIdentifier, Type> augment : augmentations.entrySet()) {
+                final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
                 if (augProto != null) {
                     byYangBuilder.put(augProto.getYangArg(), augProto);
                     byStreamClassBuilder.put(augProto.getBindingClass(), augProto);
                 }
             }
-        } else {
-            augmentationGetter = null;
         }
 
         this.byYang = ImmutableMap.copyOf(byYangBuilder);
@@ -126,7 +116,7 @@ abstract class DataObjectCodecContext<T extends DataNodeContainer> extends DataC
         byBindingArgClassBuilder.putAll(byStreamClass);
         this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
 
-        final Class<?> proxyClass = Proxy.getProxyClass(bindingClass().getClassLoader(),  new Class[] { bindingClass() });
+        final Class<?> proxyClass = Proxy.getProxyClass(getBindingClass().getClassLoader(),  new Class[] { getBindingClass() });
         try {
             proxyConstructor = LOOKUP.findConstructor(proxyClass, CONSTRUCTOR_TYPE).asType(DATAOBJECT_TYPE);
         } catch (NoSuchMethodException | IllegalAccessException e) {
@@ -134,11 +124,13 @@ abstract class DataObjectCodecContext<T extends DataNodeContainer> extends DataC
         }
     }
 
+
+    @SuppressWarnings("unchecked")
     @Override
-    protected DataContainerCodecContext<?> getStreamChild(final Class<?> childClass) {
+    public <DV extends DataObject> DataContainerCodecContext<DV, ?> streamChild(final Class<DV> childClass) {
         DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
         if (childProto != null) {
-            return childProto.get();
+            return (DataContainerCodecContext<DV,?>) childProto.get();
         }
 
         if (Augmentation.class.isAssignableFrom(childClass))  {
@@ -149,9 +141,10 @@ abstract class DataObjectCodecContext<T extends DataNodeContainer> extends DataC
              *
              * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
              */
-            Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
-            if ((bindingClass().equals(augTarget))) {
-                for (DataContainerCodecPrototype<?> realChild : byStreamClass.values()) {
+            @SuppressWarnings("rawtypes")
+            final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
+            if ((getBindingClass().equals(augTarget))) {
+                for (final DataContainerCodecPrototype<?> realChild : byStreamClass.values()) {
                     if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
                             && BindingReflections.isSubstitutionFor(childClass,realChild.getBindingClass())) {
                         childProto = realChild;
@@ -161,62 +154,71 @@ abstract class DataObjectCodecContext<T extends DataNodeContainer> extends DataC
             }
         }
         Preconditions.checkArgument(childProto != null, " Child %s is not valid child.",childClass);
-        return childProto.get();
+        return (DataContainerCodecContext<DV, ?>) childProto.get();
     }
 
+
+    @SuppressWarnings("unchecked")
     @Override
-    protected Optional<DataContainerCodecContext<?>> getPossibleStreamChild(final Class<?> childClass) {
-        DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
+    public <DV extends DataObject> Optional<DataContainerCodecContext<DV, ?>> possibleStreamChild(
+            Class<DV> childClass) {
+        final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
         if(childProto != null) {
-            return Optional.<DataContainerCodecContext<?>>of(childProto.get());
+            return Optional.<DataContainerCodecContext<DV,?>>of((DataContainerCodecContext<DV,?>) childProto.get());
         }
         return Optional.absent();
     }
 
     @Override
-    protected DataContainerCodecContext<?> getIdentifierChild(final InstanceIdentifier.PathArgument arg,
+    public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
             final List<YangInstanceIdentifier.PathArgument> builder) {
 
-        Class<? extends DataObject> argType = arg.getType();
-        DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
-        Preconditions.checkArgument(ctxProto != null,"Invalid child");
-
-        DataContainerCodecContext<?> context = ctxProto.get();
-        if(context instanceof ChoiceNodeCodecContext) {
-            ChoiceNodeCodecContext casted = (ChoiceNodeCodecContext) context;
-            casted.addYangPathArgument(arg, builder);
-            DataContainerCodecContext<?> caze = casted.getCazeByChildClass(arg.getType());
-            caze.addYangPathArgument(arg, builder);
-            return caze.getIdentifierChild(arg, builder);
+        final Class<? extends DataObject> argType = arg.getType();
+        final DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
+        if(ctxProto != null) {
+            final DataContainerCodecContext<?,?> context = ctxProto.get();
+            if(context instanceof ChoiceNodeCodecContext) {
+                final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
+                final DataContainerCodecContext<?,?> caze = choice.getCazeByChildClass(arg.getType());
+                if(caze != null) {
+                    choice.addYangPathArgument(arg, builder);
+                    caze.addYangPathArgument(arg, builder);
+                    return caze.bindingPathArgumentChild(arg, builder);
+                }
+                return null;
+            }
+            context.addYangPathArgument(arg, builder);
+            return context;
         }
-        context.addYangPathArgument(arg, builder);
-        return context;
+        // Argument is not valid child.
+        return null;
     }
 
+    @SuppressWarnings("unchecked")
     @Override
-    protected NodeCodecContext getYangIdentifierChild(YangInstanceIdentifier.PathArgument arg) {
+    public NodeCodecContext<D> yangPathArgumentChild(YangInstanceIdentifier.PathArgument arg) {
         if(arg instanceof NodeIdentifierWithPredicates) {
             arg = new NodeIdentifier(arg.getNodeType());
         }
-        NodeContextSupplier childSupplier = byYang.get(arg);
+        final NodeContextSupplier childSupplier = byYang.get(arg);
         Preconditions.checkArgument(childSupplier != null, "Argument %s is not valid child of %s", arg, schema());
-        return childSupplier.get();
+        return (NodeCodecContext<D>) childSupplier.get();
     }
 
-    protected final LeafNodeCodecContext getLeafChild(final String name) {
-        final LeafNodeCodecContext value = leafChild.get(name);
-        Preconditions.checkArgument(value != null, "Leaf %s is not valid for %s", name, bindingClass());
+    protected final LeafNodeCodecContext<?> getLeafChild(final String name) {
+        final LeafNodeCodecContext<?> value = leafChild.get(name);
+        Preconditions.checkArgument(value != null, "Leaf %s is not valid for %s", name, getBindingClass());
         return value;
     }
 
     private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
-        DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
+        final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
         // Direct instantiation or use in same module in which grouping
         // was defined.
         DataSchemaNode sameName;
         try {
             sameName = schema().getDataChildByName(origDef.getQName());
-        } catch (IllegalArgumentException e) {
+        } catch (final IllegalArgumentException e) {
             sameName = null;
         }
         final DataSchemaNode childSchema;
@@ -234,8 +236,8 @@ abstract class DataObjectCodecContext<T extends DataNodeContainer> extends DataC
             }
         } else {
             // We are looking for instantiation via uses in other module
-            QName instantiedName = QName.create(namespace(), origDef.getQName().getLocalName());
-            DataSchemaNode potential = schema().getDataChildByName(instantiedName);
+            final QName instantiedName = QName.create(namespace(), origDef.getQName().getLocalName());
+            final DataSchemaNode potential = schema().getDataChildByName(instantiedName);
             // We check if it is really instantiated from same
             // definition as class was derived
             if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
@@ -249,50 +251,53 @@ abstract class DataObjectCodecContext<T extends DataNodeContainer> extends DataC
     }
 
     private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
-        ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
+        final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
         @SuppressWarnings("rawtypes")
         final Class augClass;
         try {
             augClass = loader.loadClass(value);
-        } catch (ClassNotFoundException e) {
+        } catch (final ClassNotFoundException e) {
             LOG.warn("Failed to load augmentation prototype for {}", value, e);
             return null;
         }
 
-        Entry<AugmentationIdentifier, AugmentationSchema> augSchema = factory().getRuntimeContext()
+        @SuppressWarnings("unchecked")
+        final Entry<AugmentationIdentifier, AugmentationSchema> augSchema = factory().getRuntimeContext()
                 .getResolvedAugmentationSchema(schema(), augClass);
         return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
     }
 
     @SuppressWarnings("rawtypes")
     Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
-        NodeCodecContext childContext = byMethod.get(method).get();
-        Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
+        final NodeCodecContext<?> childContext = byMethod.get(method).get();
+        @SuppressWarnings("unchecked")
+        final Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
         if (domChild.isPresent()) {
-            return childContext.dataFromNormalizedNode(domChild.get());
+            return childContext.deserializeObject(domChild.get());
         }
         return null;
     }
 
-    protected final DataObject createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
+    protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
         try {
-            return (DataObject) proxyConstructor.invokeExact((InvocationHandler)new LazyDataObject(this, node));
-        } catch (Throwable e) {
+            return (D) proxyConstructor.invokeExact((InvocationHandler)new LazyDataObject<>(this, node));
+        } catch (final Throwable e) {
             throw Throwables.propagate(e);
         }
     }
 
+    @SuppressWarnings("unchecked")
     public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
             final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
 
         @SuppressWarnings("rawtypes")
-        Map map = new HashMap<>();
+        final Map map = new HashMap<>();
 
-        for(DataContainerCodecPrototype<?> value : byStreamClass.values()) {
+        for(final DataContainerCodecPrototype<?> value : byStreamClass.values()) {
             if(Augmentation.class.isAssignableFrom(value.getBindingClass())) {
-                Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
+                final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
                 if(augData.isPresent()) {
-                    map.put(value.getBindingClass(), value.get().dataFromNormalizedNode(augData.get()));
+                    map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
                 }
             }
         }
index e5788fe11c8eb504616d5253c91952cad641eaf3..a35a5621a2d904b49fa2e861c9b4a5bfba164769 100644 (file)
@@ -17,16 +17,15 @@ import org.opendaylight.yangtools.yang.binding.BindingMapping;
 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition.EnumPair;
 
-class EnumerationCodec extends ReflectionBasedCodec implements SchemaUnawareCodec {
+final class EnumerationCodec extends ReflectionBasedCodec implements SchemaUnawareCodec {
 
-    ImmutableBiMap<String, Enum<?>> yangValueToBinding;
+    private final ImmutableBiMap<String, Enum<?>> yangValueToBinding;
 
     public EnumerationCodec(final Class<? extends Enum<?>> enumeration, final Map<String, Enum<?>> schema) {
         super(enumeration);
         yangValueToBinding = ImmutableBiMap.copyOf(schema);
     }
 
-
     static Callable<EnumerationCodec> loader(final Class<?> returnType,
             final EnumTypeDefinition enumSchema) {
         Preconditions.checkArgument(Enum.class.isAssignableFrom(returnType));
@@ -51,7 +50,6 @@ class EnumerationCodec extends ReflectionBasedCodec implements SchemaUnawareCode
         };
     }
 
-
     @Override
     public Object deserialize(final Object input) {
         Enum<?> value = yangValueToBinding.get(input);
index e22f1f88fa7d2c0864d9d7ca73710be839f4077e..09231179d2a4731fe48f1cf8311ff7d18da13f63 100644 (file)
@@ -8,14 +8,17 @@
 package org.opendaylight.yangtools.binding.data.codec.impl;
 
 import com.google.common.base.Throwables;
+import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableMap;
 import java.lang.invoke.MethodHandle;
 import java.lang.invoke.MethodHandles;
 import java.lang.invoke.MethodHandles.Lookup;
 import java.lang.reflect.Constructor;
 import java.util.ArrayList;
-import java.util.Collection;
+import java.util.Collections;
+import java.util.Comparator;
 import java.util.LinkedHashMap;
+import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
 import org.opendaylight.yangtools.concepts.Codec;
@@ -26,12 +29,19 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdent
 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 
 final class IdentifiableItemCodec implements Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> {
+    private static final Comparator<QName> KEYARG_COMPARATOR = new Comparator<QName>() {
+        @Override
+        public int compare(final QName q1, final QName q2) {
+            return q1.getLocalName().compareToIgnoreCase(q2.getLocalName());
+        }
+    };
     private static final Lookup LOOKUP = MethodHandles.publicLookup();
-    private final MethodHandle ctor;
-    private final MethodHandle ctorInvoker;
     private final Map<QName, ValueContext> keyValueContexts;
+    private final List<QName> keysInBindingOrder;
     private final ListSchemaNode schema;
     private final Class<?> identifiable;
+    private final MethodHandle ctorInvoker;
+    private final MethodHandle ctor;
 
     public IdentifiableItemCodec(final ListSchemaNode schema, final Class<? extends Identifier<?>> keyClass,
             final Class<?> identifiable, final Map<QName, ValueContext> keyValueContexts) {
@@ -55,20 +65,47 @@ final class IdentifiableItemCodec implements Codec<NodeIdentifierWithPredicates,
             keys.put(qname, keyValueContexts.get(qname));
         }
         this.keyValueContexts = ImmutableMap.copyOf(keys);
+
+        /*
+         * When instantiating binding objects we need to specify constructor arguments
+         * in alphabetic order. We play a couple of tricks here to optimize CPU/memory
+         * trade-offs.
+         *
+         * We do not have to perform a sort if the source collection has less than two
+         * elements.
+
+         * We always perform an ImmutableList.copyOf(), as that will turn into a no-op
+         * if the source is already immutable. It will also produce optimized implementations
+         * for empty and singleton collections.
+         *
+         * BUG-2755: remove this if order is made declaration-order-dependent
+         */
+        final List<QName> unsortedKeys = schema.getKeyDefinition();
+        final List<QName> sortedKeys;
+        if (unsortedKeys.size() > 1) {
+            final List<QName> tmp = new ArrayList<>(unsortedKeys);
+            Collections.sort(tmp, KEYARG_COMPARATOR);
+            sortedKeys = tmp;
+        } else {
+            sortedKeys = unsortedKeys;
+        }
+
+        this.keysInBindingOrder = ImmutableList.copyOf(sortedKeys);
     }
 
     @Override
     public IdentifiableItem<?, ?> deserialize(final NodeIdentifierWithPredicates input) {
-        final Collection<QName> keys = schema.getKeyDefinition();
-        final ArrayList<Object> bindingValues = new ArrayList<>(keys.size());
-        for (final QName key : keys) {
+        final Object[] bindingValues = new Object[keysInBindingOrder.size()];
+        int offset = 0;
+
+        for (final QName key : keysInBindingOrder) {
             final Object yangValue = input.getKeyValues().get(key);
-            bindingValues.add(keyValueContexts.get(key).deserialize(yangValue));
+            bindingValues[offset++] = keyValueContexts.get(key).deserialize(yangValue);
         }
 
         final Identifier<?> identifier;
         try {
-            identifier = (Identifier<?>) ctorInvoker.invokeExact(ctor, bindingValues.toArray());
+            identifier = (Identifier<?>) ctorInvoker.invokeExact(ctor, bindingValues);
         } catch (Throwable e) {
             throw Throwables.propagate(e);
         }
index d15331f1adcb8af54ac71efe63275d3ba744b8e5..377f3744e0c9f10a54d5d5cfbe6c3787cfaa639a 100644 (file)
@@ -33,7 +33,7 @@ final class InstanceIdentifierCodec implements Codec<YangInstanceIdentifier, Ins
     @Override
     public InstanceIdentifier<?> deserialize(final YangInstanceIdentifier input) {
         final List<InstanceIdentifier.PathArgument> builder = new ArrayList<>();
-        final NodeCodecContext codec = context.getCodecContextNode(input, builder);
+        final NodeCodecContext<?> codec = context.getCodecContextNode(input, builder);
         if (codec == null) {
             return null;
         }
index e577c93fa6142bba8f2607201953b80c058dc9d0..a5b2a97f980ee7617284da394d5c87beacd85ee0 100644 (file)
@@ -10,6 +10,8 @@ package org.opendaylight.yangtools.binding.data.codec.impl;
 import java.lang.reflect.Method;
 import java.util.List;
 import org.opendaylight.yangtools.concepts.Codec;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.Identifiable;
 import org.opendaylight.yangtools.yang.binding.Identifier;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
@@ -19,16 +21,16 @@ import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 
-final class KeyedListNodeCodecContext extends ListNodeCodecContext {
+final class KeyedListNodeCodecContext<D extends DataObject & Identifiable<?>> extends ListNodeCodecContext<D> {
     private final Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> codec;
     private final Method keyGetter;
 
     KeyedListNodeCodecContext(final DataContainerCodecPrototype<ListSchemaNode> prototype) {
         super(prototype);
 
-        this.codec = factory().getPathArgumentCodec(bindingClass(), schema());
+        this.codec = factory().getPathArgumentCodec(getBindingClass(), schema());
         try {
-            this.keyGetter = bindingClass().getMethod("getKey");
+            this.keyGetter = getBindingClass().getMethod("getKey");
         } catch (NoSuchMethodException e) {
             throw new IllegalStateException("Required method not available", e);
         }
@@ -75,6 +77,6 @@ final class KeyedListNodeCodecContext extends ListNodeCodecContext {
 
     @SuppressWarnings({ "rawtypes", "unchecked" })
     NodeIdentifierWithPredicates serialize(final Identifier<?> key) {
-        return codec.serialize(new IdentifiableItem(bindingClass(), key));
+        return codec.serialize(new IdentifiableItem(getBindingClass(), key));
     }
 }
index 5cfc6f056c63a08d4a9f05c5c4f3fba196c4d6e4..b92acca00784e382c8db2aba813c8701e800b54d 100644 (file)
@@ -22,13 +22,14 @@ import java.util.concurrent.ConcurrentHashMap;
 import org.opendaylight.yangtools.binding.data.codec.util.AugmentationReader;
 import org.opendaylight.yangtools.yang.binding.Augmentable;
 import org.opendaylight.yangtools.yang.binding.Augmentation;
+import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-class LazyDataObject implements InvocationHandler, AugmentationReader {
+class LazyDataObject<D extends DataObject> implements InvocationHandler, AugmentationReader {
 
     private static final Logger LOG = LoggerFactory.getLogger(LazyDataObject.class);
     private static final String GET_IMPLEMENTED_INTERFACE = "getImplementedInterface";
@@ -40,13 +41,13 @@ class LazyDataObject implements InvocationHandler, AugmentationReader {
 
     private final ConcurrentHashMap<Method, Object> cachedData = new ConcurrentHashMap<>();
     private final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data;
-    private final DataObjectCodecContext<?> context;
+    private final DataObjectCodecContext<D,?> context;
 
     private volatile ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> cachedAugmentations = null;
     private volatile Integer cachedHashcode = null;
 
     @SuppressWarnings({ "rawtypes", "unchecked" })
-    LazyDataObject(final DataObjectCodecContext<?> ctx, final NormalizedNodeContainer data) {
+    LazyDataObject(final DataObjectCodecContext<D,?> ctx, final NormalizedNodeContainer data) {
         this.context = Preconditions.checkNotNull(ctx, "Context must not be null");
         this.data = Preconditions.checkNotNull(data, "Data must not be null");
     }
@@ -56,7 +57,7 @@ class LazyDataObject implements InvocationHandler, AugmentationReader {
         if (method.getParameterTypes().length == 0) {
             final String name = method.getName();
             if (GET_IMPLEMENTED_INTERFACE.equals(name)) {
-                return context.bindingClass();
+                return context.getBindingClass();
             } else if (TO_STRING.equals(name)) {
                 return bindingToString();
             } else if (HASHCODE.equals(name)) {
@@ -75,7 +76,7 @@ class LazyDataObject implements InvocationHandler, AugmentationReader {
         if (other == null) {
             return false;
         }
-        if (!context.bindingClass().isAssignableFrom(other.getClass())) {
+        if (!context.getBindingClass().isAssignableFrom(other.getClass())) {
             return false;
         }
         try {
@@ -105,7 +106,7 @@ class LazyDataObject implements InvocationHandler, AugmentationReader {
             final Object value = getBindingData(m);
             result += prime * result + ((value == null) ? 0 : value.hashCode());
         }
-        if (Augmentation.class.isAssignableFrom(context.bindingClass())) {
+        if (Augmentation.class.isAssignableFrom(context.getBindingClass())) {
             result += prime * result + (getAugmentations(this).hashCode());
         }
         cachedHashcode = result;
@@ -156,23 +157,25 @@ class LazyDataObject implements InvocationHandler, AugmentationReader {
             return aug.get(cls);
         }
         Preconditions.checkNotNull(cls,"Supplied augmentation must not be null.");
-        final Optional<DataContainerCodecContext<?>> augCtx= context.getPossibleStreamChild(cls);
+
+        @SuppressWarnings({"unchecked","rawtypes"})
+        final Optional<DataContainerCodecContext<?,?>> augCtx= context.possibleStreamChild((Class) cls);
         if(augCtx.isPresent()) {
             final Optional<NormalizedNode<?, ?>> augData = data.getChild(augCtx.get().getDomPathArgument());
             if (augData.isPresent()) {
-                return augCtx.get().dataFromNormalizedNode(augData.get());
+                return augCtx.get().deserialize(augData.get());
             }
         }
         return null;
     }
 
     public String bindingToString() {
-        final ToStringHelper helper = MoreObjects.toStringHelper(context.bindingClass()).omitNullValues();
+        final ToStringHelper helper = MoreObjects.toStringHelper(context.getBindingClass()).omitNullValues();
 
         for (final Method m :context.getHashCodeAndEqualsMethods()) {
             helper.add(m.getName(), getBindingData(m));
         }
-        if (Augmentable.class.isAssignableFrom(context.bindingClass())) {
+        if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
             helper.add("augmentations", getAugmentationsImpl());
         }
         return helper.toString();
@@ -198,7 +201,7 @@ class LazyDataObject implements InvocationHandler, AugmentationReader {
         if (getClass() != obj.getClass()) {
             return false;
         }
-        final LazyDataObject other = (LazyDataObject) obj;
+        final LazyDataObject<?> other = (LazyDataObject<?>) obj;
         if (context == null) {
             if (other.context != null) {
                 return false;
index f2cdb9009a95b368579291ed5c12940abee1948c..f74b109cd8731de731e991bfbf0ea5c05e3a09b1 100644 (file)
@@ -7,21 +7,26 @@
  */
 package org.opendaylight.yangtools.binding.data.codec.impl;
 
-import com.google.common.collect.Iterables;
-
+import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableCollection;
 import java.lang.reflect.Method;
 import java.util.ArrayList;
+import java.util.Collection;
 import java.util.List;
-
+import org.opendaylight.yangtools.binding.data.codec.api.BindingCodecTreeNode;
+import org.opendaylight.yangtools.binding.data.codec.api.BindingNormalizedNodeCachingCodec;
 import org.opendaylight.yangtools.concepts.Codec;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 
-final class LeafNodeCodecContext extends NodeCodecContext implements NodeContextSupplier {
+final class LeafNodeCodecContext<D extends DataObject> extends NodeCodecContext<D> implements NodeContextSupplier {
 
     private final YangInstanceIdentifier.PathArgument yangIdentifier;
     private final Codec<Object, Object> valueCodec;
@@ -43,12 +48,71 @@ final class LeafNodeCodecContext extends NodeCodecContext implements NodeContext
     }
 
     @Override
-    protected Object dataFromNormalizedNode(final NormalizedNode<?, ?> normalizedNode) {
+    public D deserialize(final NormalizedNode<?, ?> normalizedNode) {
+        throw new UnsupportedOperationException("Leaf can not be deserialized to DataObject");
+    }
+
+    @Override
+    public NodeCodecContext<?> get() {
+        return this;
+    }
+
+    final Method getGetter() {
+        return getter;
+    }
+
+    @Override
+    public BindingCodecTreeNode<?> bindingPathArgumentChild(PathArgument arg,
+            List<YangInstanceIdentifier.PathArgument> builder) {
+        return null;
+    }
+
+    @Override
+    public BindingNormalizedNodeCachingCodec<D> createCachingCodec(
+            ImmutableCollection<Class<? extends DataObject>> cacheSpecifier) {
+        return null;
+    }
+
+    @Override
+    public Class<D> getBindingClass() {
+        return null;
+    }
+
+    @Override
+    public NormalizedNode<?, ?> serialize(D data) {
+        throw new UnsupportedOperationException("Separete serialization of leaf node is not supported.");
+    }
+
+    @Override
+    public void writeAsNormalizedNode(D data, NormalizedNodeStreamWriter writer) {
+        throw new UnsupportedOperationException("Separete serialization of leaf node is not supported.");
+    }
+
+    @Override
+    public <E extends DataObject> BindingCodecTreeNode<E> streamChild(Class<E> childClass) {
+        return null;
+    }
+
+    @Override
+    public <E extends DataObject> Optional<? extends BindingCodecTreeNode<E>> possibleStreamChild(
+            Class<E> childClass) {
+        return null;
+    }
+
+    @Override
+    public BindingCodecTreeNode<?> yangPathArgumentChild(
+            org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument child) {
+        return null;
+    }
+
+    @Override
+    protected Object deserializeObject(NormalizedNode<?, ?> normalizedNode) {
         if (normalizedNode instanceof LeafNode<?>) {
             return valueCodec.deserialize(normalizedNode.getValue());
         } else if(normalizedNode instanceof LeafSetNode<?>) {
-            Iterable<LeafSetEntryNode<Object>> domValues = ((LeafSetNode<Object>) normalizedNode).getValue();
-            List<Object> result = new ArrayList<>(Iterables.size(domValues));
+            @SuppressWarnings("unchecked")
+            Collection<LeafSetEntryNode<Object>> domValues = ((LeafSetNode<Object>) normalizedNode).getValue();
+            List<Object> result = new ArrayList<>(domValues.size());
             for (LeafSetEntryNode<Object> valueNode : domValues) {
                 result.add(valueCodec.deserialize(valueNode.getValue()));
             }
@@ -57,13 +121,4 @@ final class LeafNodeCodecContext extends NodeCodecContext implements NodeContext
         return null;
     }
 
-    @Override
-    public NodeCodecContext get() {
-        return this;
-    }
-
-    final Method getGetter() {
-        return getter;
-    }
-
 }
\ No newline at end of file
index d9acc2c3423a3913e6358e034d17f51e8c5f45a9..919df103cf583f199fe553f0d85ce69cbcb8a068 100644 (file)
@@ -7,7 +7,6 @@
  */
 package org.opendaylight.yangtools.binding.data.codec.impl;
 
-import com.google.common.collect.Iterables;
 import java.util.ArrayList;
 import java.util.List;
 import org.opendaylight.yangtools.yang.binding.DataObject;
@@ -18,13 +17,24 @@ import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 
-class ListNodeCodecContext extends DataObjectCodecContext<ListSchemaNode> {
+class ListNodeCodecContext<D extends DataObject> extends DataObjectCodecContext<D,ListSchemaNode> {
     protected ListNodeCodecContext(final DataContainerCodecPrototype<ListSchemaNode> prototype) {
         super(prototype);
     }
 
     @Override
-    protected Object dataFromNormalizedNode(final NormalizedNode<?, ?> node) {
+    public D deserialize(final NormalizedNode<?, ?> node) {
+        if (node instanceof MapEntryNode) {
+            return fromMapEntry((MapEntryNode) node);
+        } else if (node instanceof UnkeyedListEntryNode) {
+            return fromUnkeyedListEntry((UnkeyedListEntryNode) node);
+        } else {
+            throw new IllegalStateException("Unsupported data type " + node.getClass());
+        }
+    }
+
+    @Override
+    protected Object deserializeObject(NormalizedNode<?, ?> node) {
         if (node instanceof MapNode) {
             return fromMap((MapNode) node);
         } else if (node instanceof MapEntryNode) {
@@ -38,28 +48,29 @@ class ListNodeCodecContext extends DataObjectCodecContext<ListSchemaNode> {
         }
     }
 
-    private List<DataObject> fromMap(final MapNode nodes) {
-        List<DataObject> ret = new ArrayList<>(Iterables.size(nodes.getValue()));
-        for(MapEntryNode node : nodes.getValue()) {
+    private List<D> fromMap(final MapNode nodes) {
+        List<D> ret = new ArrayList<>(nodes.getValue().size());
+        for (MapEntryNode node : nodes.getValue()) {
             ret.add(fromMapEntry(node));
         }
         return ret;
     }
 
-    private DataObject fromMapEntry(final MapEntryNode node) {
+    private D fromMapEntry(final MapEntryNode node) {
         return createBindingProxy(node);
     }
 
-    private DataObject fromUnkeyedListEntry(final UnkeyedListEntryNode node) {
+    private D fromUnkeyedListEntry(final UnkeyedListEntryNode node) {
         return createBindingProxy(node);
     }
 
-    private List<DataObject> fromUnkeyedList(final UnkeyedListNode nodes) {
+    private List<D> fromUnkeyedList(final UnkeyedListNode nodes) {
         // FIXME: Could be this lazy transformed list?
-        List<DataObject> ret = new ArrayList<>(Iterables.size(nodes.getValue()));
+        List<D> ret = new ArrayList<>(nodes.getValue().size());
         for (UnkeyedListEntryNode node : nodes.getValue()) {
             ret.add(fromUnkeyedListEntry(node));
         }
         return ret;
     }
+
 }
\ No newline at end of file
index 66e0dae1e35b8242d00a38402af27d04d70a47e1..028801bede157d4e7dad37324912d6e8015cc988 100644 (file)
@@ -8,11 +8,12 @@
 package org.opendaylight.yangtools.binding.data.codec.impl;
 
 import com.google.common.collect.ImmutableMap;
-
 import java.util.List;
-
+import org.opendaylight.yangtools.binding.data.codec.api.BindingCodecTreeNode;
 import org.opendaylight.yangtools.concepts.Codec;
 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.DataObjectSerializer;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
@@ -37,7 +38,7 @@ import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
  * </ul>
  *
  */
-abstract class NodeCodecContext {
+abstract class NodeCodecContext<D extends DataObject> implements BindingCodecTreeNode<D> {
 
     /**
      * Returns Yang Instance Identifier Path Argument of current node
@@ -69,7 +70,7 @@ abstract class NodeCodecContext {
          * @param schema  Instantiated schema of binding type.
          * @return Map of local name to leaf node context.
          */
-        ImmutableMap<String, LeafNodeCodecContext> getLeafNodes(Class<?> type, DataNodeContainer schema);
+        ImmutableMap<String, LeafNodeCodecContext<?>> getLeafNodes(Class<?> type, DataNodeContainer schema);
 
         /**
          * Returns Path argument codec for list item
@@ -80,6 +81,8 @@ abstract class NodeCodecContext {
          */
         Codec<NodeIdentifierWithPredicates, IdentifiableItem<?, ?>> getPathArgumentCodec(Class<?> type,
                 ListSchemaNode schema);
+
+        DataObjectSerializer getEventStreamSerializer(Class<?> type);
     }
 
     /**
@@ -97,11 +100,5 @@ abstract class NodeCodecContext {
         }
     }
 
-    /**
-     * Return the data object for a normalized node
-     *
-     * @param normalizedNode Backing normalized node
-     * @return Data object
-     */
-    protected abstract Object dataFromNormalizedNode(NormalizedNode<?, ?> normalizedNode);
+    protected abstract Object deserializeObject(NormalizedNode<?, ?> normalizedNode);
 }
index a0529e504aa8ce3e04e58dc35fcc98ca51955649..c659990ddd4a0e8f9e81099a6065fb0bf708ea38 100644 (file)
@@ -13,7 +13,7 @@ import javax.annotation.Nonnull;
 /**
  * Type capture of an entity producing NodeCodecContexts.
  */
-interface NodeContextSupplier extends Supplier<NodeCodecContext> {
+interface NodeContextSupplier extends Supplier<NodeCodecContext<?>> {
     @Override
-    @Nonnull NodeCodecContext get();
+    @Nonnull NodeCodecContext<?> get();
 }
index 6d292bdeeba313dc376d98a26498090dcc7c05e0..25433b8dfea0f48d1c8aa23c4f4998f8d1b22a32 100644 (file)
@@ -8,21 +8,28 @@
 package org.opendaylight.yangtools.binding.data.codec.impl;
 
 import com.google.common.base.Preconditions;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.Notification;
 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
 
-final class NotificationCodecContext extends DataObjectCodecContext<NotificationDefinition> {
+final class NotificationCodecContext<D extends DataObject & Notification> extends DataObjectCodecContext<D,NotificationDefinition> {
 
     public NotificationCodecContext(final Class<?> key, final NotificationDefinition schema, final CodecContextFactory factory) {
         super(DataContainerCodecPrototype.from(key, schema, factory));
     }
 
     @Override
-    protected Object dataFromNormalizedNode(final NormalizedNode<?, ?> data) {
+    public D deserialize(final NormalizedNode<?, ?> data) {
         Preconditions.checkState(data instanceof ContainerNode);
         return createBindingProxy((NormalizedNodeContainer<?, ?, ?>) data);
     }
 
+    @Override
+    protected Object deserializeObject(NormalizedNode<?, ?> normalizedNode) {
+        return deserialize(normalizedNode);
+    }
+
 }
\ No newline at end of file
index 874a778817d944a5cfbb4b78dfc839031d85f9f3..681b7906ed06a359b5d232013e833e1ed95ac5c3 100644 (file)
@@ -16,6 +16,7 @@ import org.opendaylight.yangtools.util.ClassLoaderUtils;
 import org.opendaylight.yangtools.yang.binding.BindingMapping;
 import org.opendaylight.yangtools.yang.binding.ChildOf;
 import org.opendaylight.yangtools.yang.binding.DataContainer;
+import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.DataRoot;
 import org.opendaylight.yangtools.yang.binding.Notification;
 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
@@ -23,7 +24,7 @@ import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.QNameModule;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
@@ -34,52 +35,54 @@ import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
 
-final class SchemaRootCodecContext extends DataContainerCodecContext<SchemaContext> {
+final class SchemaRootCodecContext<D extends DataObject> extends DataContainerCodecContext<D,SchemaContext> {
 
-    private final LoadingCache<Class<?>, DataContainerCodecContext<?>> childrenByClass = CacheBuilder.newBuilder()
-            .build(new CacheLoader<Class<?>, DataContainerCodecContext<?>>() {
+    private final LoadingCache<Class<?>, DataContainerCodecContext<?,?>> childrenByClass = CacheBuilder.newBuilder()
+            .build(new CacheLoader<Class<?>, DataContainerCodecContext<?,?>>() {
                 @Override
-                public DataContainerCodecContext<?> load(final Class<?> key) {
+                public DataContainerCodecContext<?,?> load(final Class<?> key) {
                     return createDataTreeChildContext(key);
                 }
 
             });
 
-    private final LoadingCache<Class<?>, ContainerNodeCodecContext> rpcDataByClass = CacheBuilder.newBuilder().build(
-            new CacheLoader<Class<?>, ContainerNodeCodecContext>() {
+    private final LoadingCache<Class<?>, ContainerNodeCodecContext<?>> rpcDataByClass = CacheBuilder.newBuilder().build(
+            new CacheLoader<Class<?>, ContainerNodeCodecContext<?>>() {
                 @Override
-                public ContainerNodeCodecContext load(final Class<?> key) {
+                public ContainerNodeCodecContext<?> load(final Class<?> key) {
                     return createRpcDataContext(key);
                 }
             });
 
-    private final LoadingCache<Class<?>, NotificationCodecContext> notificationsByClass = CacheBuilder.newBuilder()
-            .build(new CacheLoader<Class<?>, NotificationCodecContext>() {
+    private final LoadingCache<Class<?>, NotificationCodecContext<?>> notificationsByClass = CacheBuilder.newBuilder()
+            .build(new CacheLoader<Class<?>, NotificationCodecContext<?>>() {
                 @Override
-                public NotificationCodecContext load(final Class<?> key) {
+                public NotificationCodecContext<?> load(final Class<?> key) {
                     return createNotificationDataContext(key);
                 }
             });
 
-    private final LoadingCache<QName, DataContainerCodecContext<?>> childrenByQName = CacheBuilder.newBuilder().build(
-            new CacheLoader<QName, DataContainerCodecContext<?>>() {
+    private final LoadingCache<QName, DataContainerCodecContext<?,?>> childrenByQName = CacheBuilder.newBuilder().build(
+            new CacheLoader<QName, DataContainerCodecContext<?,?>>() {
+                @SuppressWarnings("unchecked")
                 @Override
-                public DataContainerCodecContext<?> load(final QName qname) {
+                public DataContainerCodecContext<?,?> load(final QName qname) {
                     final DataSchemaNode childSchema = schema().getDataChildByName(qname);
                     Preconditions.checkArgument(childSchema != null, "Argument %s is not valid child of %s", qname,
                             schema());
 
-                    if (childSchema instanceof DataNodeContainer || childSchema instanceof ChoiceNode) {
-                        final Class<?> childCls = factory().getRuntimeContext().getClassForSchema(childSchema);
-                        return getStreamChild(childCls);
+                    if (childSchema instanceof DataNodeContainer || childSchema instanceof ChoiceSchemaNode) {
+                        @SuppressWarnings("rawtypes")
+                        final Class childCls = factory().getRuntimeContext().getClassForSchema(childSchema);
+                        return streamChild(childCls);
                     } else {
                         throw new UnsupportedOperationException("Unsupported child type " + childSchema.getClass());
                     }
                 }
             });
 
-    private final LoadingCache<SchemaPath, ContainerNodeCodecContext> rpcDataByPath = CacheBuilder.newBuilder().build(
-            new CacheLoader<SchemaPath, ContainerNodeCodecContext>() {
+    private final LoadingCache<SchemaPath, ContainerNodeCodecContext<?>> rpcDataByPath = CacheBuilder.newBuilder().build(
+            new CacheLoader<SchemaPath, ContainerNodeCodecContext<?>>() {
 
                 @SuppressWarnings({ "rawtypes", "unchecked" })
                 @Override
@@ -90,8 +93,8 @@ final class SchemaRootCodecContext extends DataContainerCodecContext<SchemaConte
                 }
             });
 
-    private final LoadingCache<SchemaPath, NotificationCodecContext> notificationsByPath = CacheBuilder.newBuilder()
-            .build(new CacheLoader<SchemaPath, NotificationCodecContext>() {
+    private final LoadingCache<SchemaPath, NotificationCodecContext<?>> notificationsByPath = CacheBuilder.newBuilder()
+            .build(new CacheLoader<SchemaPath, NotificationCodecContext<?>>() {
 
                 @SuppressWarnings({ "rawtypes", "unchecked" })
                 @Override
@@ -113,48 +116,53 @@ final class SchemaRootCodecContext extends DataContainerCodecContext<SchemaConte
      *            CodecContextFactory
      * @return
      */
-    static SchemaRootCodecContext create(final CodecContextFactory factory) {
+    static SchemaRootCodecContext<?> create(final CodecContextFactory factory) {
         final DataContainerCodecPrototype<SchemaContext> prototype = DataContainerCodecPrototype.rootPrototype(factory);
-        return new SchemaRootCodecContext(prototype);
+        return new SchemaRootCodecContext<>(prototype);
     }
 
+
+    @SuppressWarnings("unchecked")
     @Override
-    protected DataContainerCodecContext<?> getStreamChild(final Class<?> childClass) {
-        return childrenByClass.getUnchecked(childClass);
+    public <DV extends DataObject> DataContainerCodecContext<DV, ?> streamChild(Class<DV> childClass)
+            throws IllegalArgumentException {
+        return (DataContainerCodecContext<DV, ?>) childrenByClass.getUnchecked(childClass);
     }
 
     @Override
-    protected Optional<DataContainerCodecContext<?>> getPossibleStreamChild(final Class<?> childClass) {
+    public <E extends DataObject> Optional<DataContainerCodecContext<E,?>> possibleStreamChild(final Class<E> childClass) {
         throw new UnsupportedOperationException("Not supported");
     }
 
     @Override
-    protected NodeCodecContext getYangIdentifierChild(final PathArgument arg) {
+    public DataContainerCodecContext<?,?> yangPathArgumentChild(final PathArgument arg) {
         return childrenByQName.getUnchecked(arg.getNodeType());
     }
 
     @Override
-    protected Object dataFromNormalizedNode(final NormalizedNode<?, ?> normalizedNode) {
-        throw new UnsupportedOperationException("Could not create Binding data representation for root");
+    public D deserialize(final NormalizedNode<?, ?> normalizedNode) {
+        throw new UnsupportedOperationException(
+                "Could not create Binding data representation for root");
     }
 
-    ContainerNodeCodecContext getRpc(final Class<? extends DataContainer> rpcInputOrOutput) {
+
+    ContainerNodeCodecContext<?> getRpc(final Class<? extends DataContainer> rpcInputOrOutput) {
         return rpcDataByClass.getUnchecked(rpcInputOrOutput);
     }
 
-    NotificationCodecContext getNotification(final Class<? extends Notification> notification) {
+    NotificationCodecContext<?> getNotification(final Class<? extends Notification> notification) {
         return notificationsByClass.getUnchecked(notification);
     }
 
-    NotificationCodecContext getNotification(final SchemaPath notification) {
+    NotificationCodecContext<?> getNotification(final SchemaPath notification) {
         return notificationsByPath.getUnchecked(notification);
     }
 
-    ContainerNodeCodecContext getRpc(final SchemaPath notification) {
+    ContainerNodeCodecContext<?> getRpc(final SchemaPath notification) {
         return rpcDataByPath.getUnchecked(notification);
     }
 
-    private DataContainerCodecContext<?> createDataTreeChildContext(final Class<?> key) {
+    private DataContainerCodecContext<?,?> createDataTreeChildContext(final Class<?> key) {
         final Class<Object> parent = ClassLoaderUtils.findFirstGenericArgument(key, ChildOf.class);
         Preconditions.checkArgument(DataRoot.class.isAssignableFrom(parent));
         final QName qname = BindingReflections.findQName(key);
@@ -162,7 +170,7 @@ final class SchemaRootCodecContext extends DataContainerCodecContext<SchemaConte
         return DataContainerCodecPrototype.from(key, childSchema, factory()).get();
     }
 
-    private ContainerNodeCodecContext createRpcDataContext(final Class<?> key) {
+    private ContainerNodeCodecContext<?> createRpcDataContext(final Class<?> key) {
         Preconditions.checkArgument(DataContainer.class.isAssignableFrom(key));
         final QName qname = BindingReflections.findQName(key);
         final QNameModule module = qname.getModule();
@@ -189,10 +197,10 @@ final class SchemaRootCodecContext extends DataContainerCodecContext<SchemaConte
         Preconditions.checkArgument(rpc != null, "Supplied class %s is not valid RPC class.", key);
         final ContainerSchemaNode schema = SchemaNodeUtils.getRpcDataSchema(rpc, qname);
         Preconditions.checkArgument(schema != null, "Schema for %s does not define input / output.", rpc.getQName());
-        return (ContainerNodeCodecContext) DataContainerCodecPrototype.from(key, schema, factory()).get();
+        return (ContainerNodeCodecContext<?>) DataContainerCodecPrototype.from(key, schema, factory()).get();
     }
 
-    private NotificationCodecContext createNotificationDataContext(final Class<?> notificationType) {
+    private NotificationCodecContext<?> createNotificationDataContext(final Class<?> notificationType) {
         Preconditions.checkArgument(Notification.class.isAssignableFrom(notificationType));
         Preconditions.checkArgument(notificationType.isInterface(), "Supplied class must be interface.");
         final QName qname = BindingReflections.findQName(notificationType);
@@ -204,7 +212,12 @@ final class SchemaRootCodecContext extends DataContainerCodecContext<SchemaConte
                 SchemaPath.create(true, qname));
         Preconditions.checkArgument(schema != null, "Supplied %s is not valid notification", notificationType);
 
-        return new NotificationCodecContext(notificationType, schema, factory());
+        return new NotificationCodecContext<>(notificationType, schema, factory());
+    }
+
+    @Override
+    protected Object deserializeObject(NormalizedNode<?, ?> normalizedNode) {
+        throw new UnsupportedOperationException("Unable to deserialize root");
     }
 
 }
\ No newline at end of file
index ed8a2bc80ae37a632f03bb3024d5d129ed202c98..00702f07296d5e92d886d9020a746f9d67e3bd3a 100644 (file)
@@ -8,14 +8,12 @@
 package org.opendaylight.yangtools.binding.data.codec.impl;
 
 import com.google.common.collect.ImmutableSet;
-
 import java.lang.reflect.Constructor;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.util.HashSet;
 import java.util.Set;
 import java.util.concurrent.Callable;
-
 import org.opendaylight.yangtools.concepts.Codec;
 import org.opendaylight.yangtools.yang.binding.BindingMapping;
 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
@@ -24,8 +22,8 @@ import org.opendaylight.yangtools.yang.model.util.UnionType;
 
 final class UnionTypeCodec extends ReflectionBasedCodec {
 
-    private Constructor<?> charConstructor;
-    private ImmutableSet<UnionValueOptionContext> typeCodecs;
+    private final ImmutableSet<UnionValueOptionContext> typeCodecs;
+    private final Constructor<?> charConstructor;
 
     private UnionTypeCodec(final Class<?> unionCls,final Set<UnionValueOptionContext> codecs) {
         super(unionCls);
@@ -37,7 +35,7 @@ final class UnionTypeCodec extends ReflectionBasedCodec {
         }
     }
 
-    static final Callable<UnionTypeCodec> loader(final Class<?> unionCls, final UnionTypeDefinition unionType) {
+    static Callable<UnionTypeCodec> loader(final Class<?> unionCls, final UnionTypeDefinition unionType) {
         return new Callable<UnionTypeCodec>() {
             @Override
             public UnionTypeCodec call() throws NoSuchMethodException, SecurityException {
@@ -54,7 +52,7 @@ final class UnionTypeCodec extends ReflectionBasedCodec {
         };
     }
 
-    private static Codec<Object, Object> getCodecForType(Class valueType, TypeDefinition subtype) {
+    private static Codec<Object, Object> getCodecForType(final Class<?> valueType, final TypeDefinition<?> subtype) {
         if (subtype.getBaseType() instanceof UnionType) {
             try {
                 return UnionTypeCodec.loader(valueType, (UnionType) subtype.getBaseType()).call();
@@ -77,10 +75,10 @@ final class UnionTypeCodec extends ReflectionBasedCodec {
 
     @Override
     public Object serialize(final Object input) {
-        if(input != null) {
-            for(UnionValueOptionContext valCtx : typeCodecs) {
+        if (input != null) {
+            for (UnionValueOptionContext valCtx : typeCodecs) {
                 Object domValue = valCtx.serialize(input);
-                if(domValue != null) {
+                if (domValue != null) {
                     return domValue;
                 }
             }
index 1308846cc8ebb79351382e93cf51e14850c704f9..e44ae3128f48b7839b4d66aefdd131255f630d1c 100644 (file)
@@ -24,7 +24,7 @@ final class ValueContext {
     private final Class<?> identifier;
     private final String getterName;
 
-    ValueContext(final Class<?> identifier, final LeafNodeCodecContext leaf) {
+    ValueContext(final Class<?> identifier, final LeafNodeCodecContext <?>leaf) {
         getterName = BindingCodecContext.GETTER_PREFIX + BindingMapping.getClassName(leaf.getDomPathArgument().getNodeType());
         try {
             getter = LOOKUP.unreflect(identifier.getMethod(getterName)).asType(OBJECT_METHOD);
index d327a468d54a1e40c9e1216f8be175cd460a2264..d69970b93fad9af9fc3ce9e7545b31da730c5275 100644 (file)
@@ -63,14 +63,14 @@ abstract class ValueTypeCodec implements Codec<Object, Object> {
     public static final SchemaUnawareCodec EMPTY_CODEC = new SchemaUnawareCodec() {
 
         @Override
-        public Object serialize(Object arg0) {
+        public Object serialize(final Object arg0) {
             // Empty type has null value in NormalizedNode and Composite Node
             // representation
             return null;
         }
 
         @Override
-        public Object deserialize(Object arg0) {
+        public Object deserialize(final Object arg0) {
             /* Empty type has boolean.TRUE representation in Binding-aware world
             *  otherwise it is null / false.
             *  So when codec is triggered, empty leaf is present, that means we
@@ -83,7 +83,7 @@ abstract class ValueTypeCodec implements Codec<Object, Object> {
     private static final Callable<? extends SchemaUnawareCodec> EMPTY_LOADER = new Callable<SchemaUnawareCodec>() {
 
         @Override
-        public SchemaUnawareCodec call() throws Exception {
+        public SchemaUnawareCodec call() {
             return EMPTY_CODEC;
         }
     };
index b276bbd534ce608c2f5b660fc4d45f7de0f7aba3..dd0e316fe3bda5cc566db8ae037ef18b7bbeb837 100644 (file)
@@ -11,7 +11,6 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
-
 import com.google.common.collect.Iterables;
 import javassist.ClassPool;
 import org.junit.Before;
@@ -81,7 +80,7 @@ public class InstanceIdentifierSerializeDeserializeTest extends AbstractBindingR
         assertEquals(TopLevelList.class, instanceIdentifier.getTargetType());
         assertFalse(instanceIdentifier.isWildcarded());
         assertTrue(last instanceof InstanceIdentifier.IdentifiableItem);
-        final Identifier key = ((InstanceIdentifier.IdentifiableItem) last).getKey();
+        final Identifier<?> key = ((InstanceIdentifier.IdentifiableItem<?, ?>) last).getKey();
         assertEquals(TopLevelListKey.class, key.getClass());
         assertEquals(TOP_LEVEL_LIST_KEY_VALUE, ((TopLevelListKey)key).getName());
     }
diff --git a/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/AbstractTransformerGenerator.java b/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/AbstractTransformerGenerator.java
deleted file mode 100644 (file)
index 7258175..0000000
+++ /dev/null
@@ -1,143 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.sal.binding.generator.impl;
-
-import com.google.common.base.Preconditions;
-
-import java.util.Map;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ConcurrentHashMap;
-
-import javassist.ClassPool;
-
-import org.eclipse.xtext.xbase.lib.Extension;
-import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
-import org.opendaylight.yangtools.sal.binding.generator.util.JavassistUtils;
-import org.opendaylight.yangtools.util.ClassLoaderUtils;
-import org.opendaylight.yangtools.yang.binding.BindingCodec;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-
-/**
- * Abstract base class which defines the baseline for the real {@link TransformerGenerator}.
- * This class exists to expose the basic interface and common interactions with the rest
- * of the package.
- */
-abstract class AbstractTransformerGenerator {
-    private static final Map<SchemaPath, InstanceIdentifier<?>> PATH_TO_BINDING_IDENTIFIER = new ConcurrentHashMap<>();
-
-    /*
-     * The generator has to always use this strategy, otherwise we may end up
-     * will VerificationErrors.
-     */
-    @Extension
-    protected static final ClassLoadingStrategy CLASS_LOADING_STRATEGY = GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy();
-    @Extension
-    protected final TypeResolver typeResolver;
-    @Extension
-    protected final JavassistUtils javAssist;
-
-    /*
-     * This is effectively final, but we have an implementation circle, where this
-     * class notifies LazyGeneratedCodecRegistry and it calls our methods. The
-     * listener is initialized to non-null before it is exposed.
-     */
-    private GeneratorListener listener;
-
-    protected AbstractTransformerGenerator(final TypeResolver typeResolver, final ClassPool pool) {
-        this.typeResolver = Preconditions.checkNotNull(typeResolver);
-        this.javAssist = JavassistUtils.forClassPool(pool);
-    }
-
-    protected final GeneratorListener getListener() {
-        if (listener == null) {
-            synchronized (this) {
-                Preconditions.checkState(listener != null, "Implementation not fully initialized");
-            }
-        }
-
-        return listener;
-    }
-
-    synchronized final void setListener(final GeneratorListener listener) {
-        Preconditions.checkState(this.listener == null, "Implementation already initialized");
-        this.listener = Preconditions.checkNotNull(listener);
-    }
-
-    protected final <V> V runOnClassLoader(final ClassLoader cls, final Callable<V> function) throws Exception {
-        synchronized (javAssist) {
-            javAssist.appendClassLoaderIfMissing(cls);
-            return ClassLoaderUtils.withClassLoader(cls, function);
-        }
-    }
-
-    protected final InstanceIdentifier<?> getBindingIdentifierByPath(final SchemaPath path) {
-        return PATH_TO_BINDING_IDENTIFIER.get(path);
-    }
-
-    protected final void putPathToBindingIdentifier(final SchemaPath path, final InstanceIdentifier<?> bindingIdentifier) {
-        PATH_TO_BINDING_IDENTIFIER.put(path, bindingIdentifier);
-    }
-
-    protected final InstanceIdentifier<?> putPathToBindingIdentifier(final SchemaPath path,
-            final InstanceIdentifier<?> bindingIdentifier, final Class<?> childClass) {
-        @SuppressWarnings({ "unchecked", "rawtypes" })
-        InstanceIdentifier<?> newId = bindingIdentifier.builder().child((Class) childClass).build();
-        PATH_TO_BINDING_IDENTIFIER.put(path, newId);
-        return newId;
-    }
-
-    protected abstract Class<? extends BindingCodec<Map<QName, Object>, Object>> augmentationTransformerForImpl(Class<?> inputType);
-    protected abstract Class<? extends BindingCodec<Object, Object>> caseCodecForImpl(Class<?> inputType, ChoiceCaseNode node);
-    protected abstract Class<? extends BindingCodec<Map<QName, Object>, Object>> keyTransformerForIdentifiableImpl(Class<?> parentType);
-    protected abstract Class<? extends BindingCodec<Map<QName, Object>, Object>> keyTransformerForIdentifierImpl(Class<?> inputType);
-    protected abstract Class<? extends BindingCodec<Map<QName, Object>, Object>> transformerForImpl(Class<?> inputType);
-
-    // Called from LazyGeneratedCodecRegistry
-    final Class<? extends BindingCodec<Map<QName, Object>, Object>> augmentationTransformerFor(final Class<?> inputType) throws TransformerGeneratorException {
-        try {
-            return augmentationTransformerForImpl(inputType);
-        } catch (Exception e) {
-            throw TransformerGeneratorException.wrap(inputType, e);
-        }
-    }
-
-    final Class<? extends BindingCodec<Object, Object>> caseCodecFor(final Class<?> inputType, final ChoiceCaseNode node) throws TransformerGeneratorException {
-        try {
-            return caseCodecForImpl(inputType, node);
-        } catch (Exception e) {
-            throw TransformerGeneratorException.wrap(inputType, e);
-        }
-    }
-
-    final Class<? extends BindingCodec<Map<QName, Object>, Object>> keyTransformerForIdentifiable(final Class<?> parentType) throws TransformerGeneratorException {
-        try {
-            return keyTransformerForIdentifiableImpl(parentType);
-        } catch (Exception e) {
-            throw TransformerGeneratorException.wrap(parentType, e);
-        }
-    }
-
-    final Class<? extends BindingCodec<Map<QName, Object>, Object>> keyTransformerForIdentifier(final Class<?> inputType) throws TransformerGeneratorException {
-        try {
-            return keyTransformerForIdentifierImpl(inputType);
-        } catch (Exception e) {
-            throw TransformerGeneratorException.wrap(inputType, e);
-        }
-    }
-
-    final Class<? extends BindingCodec<Map<QName, Object>, Object>> transformerFor(final Class<?> inputType) throws TransformerGeneratorException {
-        try {
-            return transformerForImpl(inputType);
-        } catch (Exception e) {
-            throw TransformerGeneratorException.wrap(inputType, e);
-        }
-    }
-}
diff --git a/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/BindingClassListener.java b/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/BindingClassListener.java
deleted file mode 100644 (file)
index d641d2b..0000000
+++ /dev/null
@@ -1,15 +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.yangtools.sal.binding.generator.impl;
-
-public interface BindingClassListener {
-
-    void onBindingClassCaptured(Class<?> cls);
-
-    void onBindingClassProcessed(Class<?> cls);
-}
index ee0eb2e40db83280e0110fcc1ea49796402688a2..66f3bc042408f6a475a772aa41ef78541aabbbab 100644 (file)
@@ -25,6 +25,7 @@ import static org.opendaylight.yangtools.binding.generator.util.Types.typeForCla
 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findNodeInSchemaContext;
 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
+
 import com.google.common.base.Preconditions;
 import com.google.common.base.Splitter;
 import com.google.common.collect.Iterables;
@@ -71,7 +72,7 @@ import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
@@ -94,8 +95,10 @@ import org.opendaylight.yangtools.yang.model.api.UsesNode;
 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
+import org.opendaylight.yangtools.yang.model.util.BaseTypes;
 import org.opendaylight.yangtools.yang.model.util.DataNodeIterator;
 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
+import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
 import org.opendaylight.yangtools.yang.model.util.UnionType;
 import org.opendaylight.yangtools.yang.parser.builder.util.Comparators;
 import org.opendaylight.yangtools.yang.parser.util.ModuleDependencySort;
@@ -107,6 +110,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
     private static final Splitter COLON_SPLITTER = Splitter.on(':');
     private static final Splitter BSDOT_SPLITTER = Splitter.on("\\.");
     private static final char NEW_LINE = '\n';
+    private static final String QNAME_FQCN = QName.class.getName();
 
     /**
      * Constant with the concrete name of identifier.
@@ -228,20 +232,20 @@ public class BindingGeneratorImpl implements BindingGenerator {
 
         schemaContext = context;
         typeProvider = new TypeProviderImpl(context);
-        Module[] modulesArray = new Module[context.getModules().size()];
+        final Module[] modulesArray = new Module[context.getModules().size()];
         context.getModules().toArray(modulesArray);
         final List<Module> contextModules = ModuleDependencySort.sort(modulesArray);
         genTypeBuilders = new HashMap<>();
 
-        for (Module contextModule : contextModules) {
+        for (final Module contextModule : contextModules) {
             moduleToGenTypes(contextModule, context);
         }
-        for (Module contextModule : contextModules) {
+        for (final Module contextModule : contextModules) {
             allAugmentsToGenTypes(contextModule);
         }
 
         final List<Type> filteredGenTypes = new ArrayList<>();
-        for (Module m : modules) {
+        for (final Module m : modules) {
             final ModuleContext ctx = checkNotNull(genCtx.get(m), "Module context not found for module %s", m);
             filteredGenTypes.addAll(ctx.getGeneratedTypes());
             final Set<Type> additionalTypes = ((TypeProviderImpl) typeProvider).getAdditionalTypes().get(m);
@@ -290,7 +294,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
         final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
         checkState(typeDefinitions != null, "Type Definitions for module Â«module.name» cannot be NULL.");
 
-        for (TypeDefinition<?> typedef : typeDefinitions) {
+        for (final TypeDefinition<?> typedef : typeDefinitions) {
             if (typedef != null) {
                 final Type type = ((TypeProviderImpl) typeProvider).generatedTypeForExtendedDefinitionType(typedef,
                         typedef);
@@ -348,7 +352,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
                 genType.addImplementsType(identifiableMarker);
             }
 
-            for (DataSchemaNode schemaNode : node.getChildNodes()) {
+            for (final DataSchemaNode schemaNode : node.getChildNodes()) {
                 if (!schemaNode.isAugmenting()) {
                     addSchemaNodeToListBuilders(basePackageName, schemaNode, genType, genTOBuilder, listKeys, module);
                 }
@@ -367,8 +371,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
 
     private void processUsesAugments(final DataNodeContainer node, final Module module) {
         final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
-        for (UsesNode usesNode : node.getUses()) {
-            for (AugmentationSchema augment : usesNode.getAugmentations()) {
+        for (final UsesNode usesNode : node.getUses()) {
+            for (final AugmentationSchema augment : usesNode.getAugmentations()) {
                 usesAugmentationToGenTypes(basePackageName, augment, module, usesNode, node);
                 processUsesAugments(augment, module);
             }
@@ -397,7 +401,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
 
         final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
         final List<AugmentationSchema> augmentations = resolveAugmentations(module);
-        for (AugmentationSchema augment : augmentations) {
+        for (final AugmentationSchema augment : augmentations) {
             augmentationToGenTypes(basePackageName, augment, module);
         }
     }
@@ -421,7 +425,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
         checkState(module.getAugmentations() != null, "Augmentations Set cannot be NULL.");
 
         final Set<AugmentationSchema> augmentations = module.getAugmentations();
-        List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
+        final List<AugmentationSchema> sortedAugmentations = new ArrayList<>(augmentations);
         Collections.sort(sortedAugmentations, Comparators.AUGMENT_COMP);
 
         return sortedAugmentations;
@@ -479,7 +483,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
         interfaceBuilder.addImplementsType(Types.typeForClass(RpcService.class));
         interfaceBuilder.setDescription(createDescription(rpcDefinitions, module.getName(), module.getModuleSourcePath()));
 
-        for (RpcDefinition rpc : rpcDefinitions) {
+        for (final RpcDefinition rpc : rpcDefinitions) {
             if (rpc != null) {
                 final String rpcName = BindingMapping.getClassName(rpc.getQName());
                 final String rpcMethodName = BindingMapping.getPropertyName(rpcName);
@@ -550,7 +554,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
 
 
 
-        for (NotificationDefinition notification : notifications) {
+        for (final NotificationDefinition notification : notifications) {
             if (notification != null) {
                 processUsesAugments(notification, module);
 
@@ -590,7 +594,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
         final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
 
         if (schemaIdentities != null && !schemaIdentities.isEmpty()) {
-            for (IdentitySchemaNode identity : schemaIdentities) {
+            for (final IdentitySchemaNode identity : schemaIdentities) {
                 identityToGenType(module, basePackageName, identity, context);
             }
         }
@@ -652,7 +656,9 @@ public class BindingGeneratorImpl implements BindingGenerator {
 
     private static Constant qnameConstant(final GeneratedTypeBuilderBase<?> toBuilder, final String constantName,
             final QName name) {
-        StringBuilder sb = new StringBuilder("org.opendaylight.yangtools.yang.common.QName");
+        final StringBuilder sb = new StringBuilder(QNAME_FQCN);
+        sb.append(".cachedReference(");
+        sb.append(QNAME_FQCN);
         sb.append(".create(");
         sb.append('"');
         sb.append(name.getNamespace());
@@ -660,7 +666,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
         sb.append(name.getFormattedRevision());
         sb.append("\",\"");
         sb.append(name.getLocalName());
-        sb.append("\");");
+        sb.append("\"))");
 
         return toBuilder.addConstant(typeForClass(QName.class), constantName, sb.toString());
     }
@@ -682,7 +688,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
         final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
         final List<GroupingDefinition> groupingsSortedByDependencies = new GroupingDefinitionDependencySort()
         .sort(groupings);
-        for (GroupingDefinition grouping : groupingsSortedByDependencies) {
+        for (final GroupingDefinition grouping : groupingsSortedByDependencies) {
             groupingToGenType(basePackageName, grouping, module);
         }
     }
@@ -724,17 +730,21 @@ public class BindingGeneratorImpl implements BindingGenerator {
      *            builder
      * @param typeBuilder
      *            GeneratedTypeBuilder to which will be enum builder assigned
+     * @param module
+     *            Module in which type should be generated
      * @return enumeration builder which contains data from
      *         <code>enumTypeDef</code>
      */
     private EnumBuilder resolveInnerEnumFromTypeDefinition(final EnumTypeDefinition enumTypeDef, final QName enumName,
-            final GeneratedTypeBuilder typeBuilder) {
+            final GeneratedTypeBuilder typeBuilder, Module module) {
         if ((enumTypeDef != null) && (typeBuilder != null) && (enumTypeDef.getQName() != null)
                 && (enumTypeDef.getQName().getLocalName() != null)) {
             final String enumerationName = BindingMapping.getClassName(enumName);
             final EnumBuilder enumBuilder = typeBuilder.addEnumeration(enumerationName);
             enumBuilder.setDescription(enumTypeDef.getDescription());
             enumBuilder.updateEnumPairsFromEnumTypeDef(enumTypeDef);
+            ModuleContext ctx = genCtx.get(module);
+            ctx.addInnerTypedefType(enumTypeDef.getPath(), enumBuilder);
             return enumBuilder;
         }
         return null;
@@ -824,15 +834,15 @@ public class BindingGeneratorImpl implements BindingGenerator {
             throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
         }
 
-        if (!(targetSchemaNode instanceof ChoiceNode)) {
-            String packageName = augmentPackageName;
+        if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
+            final String packageName = augmentPackageName;
             final Type targetType = new ReferencedTypeImpl(targetTypeBuilder.getPackageName(),
                     targetTypeBuilder.getName());
             addRawAugmentGenTypeDefinition(module, packageName, augmentPackageName, targetType, augSchema);
 
         } else {
             generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
-                    (ChoiceNode) targetSchemaNode, augSchema.getChildNodes());
+                    (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes());
         }
     }
 
@@ -845,7 +855,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
 
         processUsesAugments(augSchema, module);
         final SchemaPath targetPath = augSchema.getTargetPath();
-        SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
+        final SchemaNode targetSchemaNode = findOriginalTargetFromGrouping(targetPath, usesNode);
         if (targetSchemaNode == null) {
             throw new IllegalArgumentException("augment target not found: " + targetPath);
         }
@@ -858,7 +868,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
             throw new NullPointerException("Target type not yet generated: " + targetSchemaNode);
         }
 
-        if (!(targetSchemaNode instanceof ChoiceNode)) {
+        if (!(targetSchemaNode instanceof ChoiceSchemaNode)) {
             String packageName = augmentPackageName;
             if (usesNodeParent instanceof SchemaNode) {
                 packageName = packageNameForGeneratedType(augmentPackageName, ((SchemaNode) usesNodeParent).getPath(),
@@ -868,7 +878,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
                     augSchema);
         } else {
             generateTypesFromAugmentedChoiceCases(module, augmentPackageName, targetTypeBuilder.toInstance(),
-                    (ChoiceNode) targetSchemaNode, augSchema.getChildNodes());
+                    (ChoiceSchemaNode) targetSchemaNode, augSchema.getChildNodes());
         }
     }
 
@@ -882,21 +892,21 @@ public class BindingGeneratorImpl implements BindingGenerator {
      * @return node from its original location in grouping
      */
     private DataSchemaNode findOriginalTargetFromGrouping(final SchemaPath targetPath, final UsesNode parentUsesNode) {
-        SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
+        final SchemaNode targetGrouping = findNodeInSchemaContext(schemaContext, parentUsesNode.getGroupingPath()
                 .getPathFromRoot());
         if (!(targetGrouping instanceof GroupingDefinition)) {
             throw new IllegalArgumentException("Failed to generate code for augment in " + parentUsesNode);
         }
 
-        GroupingDefinition grouping = (GroupingDefinition) targetGrouping;
+        final GroupingDefinition grouping = (GroupingDefinition) targetGrouping;
         SchemaNode result = grouping;
-        for (QName node : targetPath.getPathFromRoot()) {
+        for (final QName node : targetPath.getPathFromRoot()) {
             // finding by local name is valid, grouping cannot contain nodes
             // with same name and different namespace
             if (result instanceof DataNodeContainer) {
                 result = ((DataNodeContainer) result).getDataChildByName(node.getLocalName());
-            } else if (result instanceof ChoiceNode) {
-                result = ((ChoiceNode) result).getCaseNodeByName(node.getLocalName());
+            } else if (result instanceof ChoiceSchemaNode) {
+                result = ((ChoiceSchemaNode) result).getCaseNodeByName(node.getLocalName());
             }
         }
         if (result == null) {
@@ -904,7 +914,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
         }
 
         boolean fromUses = ((DataSchemaNode) result).isAddedByUses();
-        Iterator<UsesNode> groupingUses = grouping.getUses().iterator();
+        final Iterator<UsesNode> groupingUses = grouping.getUses().iterator();
         while (groupingUses.hasNext() && fromUses) {
             result = findOriginalTargetFromGrouping(targetPath, groupingUses.next());
             if (result != null) {
@@ -981,7 +991,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
      * @return nodeParameter of UnknownSchemaNode
      */
     private String getAugmentIdentifier(final List<UnknownSchemaNode> unknownSchemaNodes) {
-        for (UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
+        for (final UnknownSchemaNode unknownSchemaNode : unknownSchemaNodes) {
             final QName nodeType = unknownSchemaNode.getNodeType();
             if (AUGMENT_IDENTIFIER_NAME.equals(nodeType.getLocalName())
                     && YANG_EXT_NAMESPACE.equals(nodeType.getNamespace().toString())) {
@@ -1041,7 +1051,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
     private GeneratedTypeBuilder resolveDataSchemaNodes(final Module module, final String basePackageName,
             final GeneratedTypeBuilder parent, final GeneratedTypeBuilder childOf, final Iterable<DataSchemaNode> schemaNodes) {
         if (schemaNodes != null && parent != null) {
-            for (DataSchemaNode schemaNode : schemaNodes) {
+            for (final DataSchemaNode schemaNode : schemaNodes) {
                 if (!schemaNode.isAugmenting() && !schemaNode.isAddedByUses()) {
                     addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, parent, childOf, module);
                 }
@@ -1076,7 +1086,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
             final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf,
             final Iterable<DataSchemaNode> schemaNodes) {
         if ((schemaNodes != null) && (typeBuilder != null)) {
-            for (DataSchemaNode schemaNode : schemaNodes) {
+            for (final DataSchemaNode schemaNode : schemaNodes) {
                 if (!schemaNode.isAugmenting()) {
                     addSchemaNodeToBuilderAsMethod(basePackageName, schemaNode, typeBuilder, childOf, module);
                 }
@@ -1106,15 +1116,15 @@ public class BindingGeneratorImpl implements BindingGenerator {
             final GeneratedTypeBuilder typeBuilder, final GeneratedTypeBuilder childOf, final Module module) {
         if (node != null && typeBuilder != null) {
             if (node instanceof LeafSchemaNode) {
-                resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node);
+                resolveLeafSchemaNodeAsMethod(typeBuilder, (LeafSchemaNode) node, module);
             } else if (node instanceof LeafListSchemaNode) {
-                resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node);
+                resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) node,module);
             } else if (node instanceof ContainerSchemaNode) {
                 containerToGenType(module, basePackageName, typeBuilder, childOf, (ContainerSchemaNode) node);
             } else if (node instanceof ListSchemaNode) {
                 listToGenType(module, basePackageName, typeBuilder, childOf, (ListSchemaNode) node);
-            } else if (node instanceof ChoiceNode) {
-                choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceNode) node);
+            } else if (node instanceof ChoiceSchemaNode) {
+                choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) node);
             } else {
                 // TODO: anyxml not yet supported
                 LOG.debug("Unable to add schema node {} as method in {}: unsupported type of node.", node.getClass(),
@@ -1147,7 +1157,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
      *             </ul>
      */
     private void choiceToGeneratedType(final Module module, final String basePackageName,
-            final GeneratedTypeBuilder parent, final ChoiceNode choiceNode) {
+            final GeneratedTypeBuilder parent, final ChoiceSchemaNode choiceNode) {
         checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
         checkArgument(choiceNode != null, "Choice Schema Node cannot be NULL.");
 
@@ -1190,7 +1200,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
      *             </ul>
      */
     private void generateTypesFromChoiceCases(final Module module, final String basePackageName,
-            final Type refChoiceType, final ChoiceNode choiceNode) {
+            final Type refChoiceType, final ChoiceSchemaNode choiceNode) {
         checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
         checkArgument(refChoiceType != null, "Referenced Choice Type cannot be NULL.");
         checkArgument(choiceNode != null, "ChoiceNode cannot be NULL.");
@@ -1200,7 +1210,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
             return;
         }
 
-        for (ChoiceCaseNode caseNode : caseNodes) {
+        for (final ChoiceCaseNode caseNode : caseNodes) {
             if (caseNode != null && !caseNode.isAddedByUses() && !caseNode.isAugmenting()) {
                 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
                 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
@@ -1273,12 +1283,12 @@ public class BindingGeneratorImpl implements BindingGenerator {
      *             </ul>
      */
     private void generateTypesFromAugmentedChoiceCases(final Module module, final String basePackageName,
-            final Type targetType, final ChoiceNode targetNode, final Iterable<DataSchemaNode> augmentedNodes) {
+            final Type targetType, final ChoiceSchemaNode targetNode, final Iterable<DataSchemaNode> augmentedNodes) {
         checkArgument(basePackageName != null, "Base Package Name cannot be NULL.");
         checkArgument(targetType != null, "Referenced Choice Type cannot be NULL.");
         checkArgument(augmentedNodes != null, "Set of Choice Case Nodes cannot be NULL.");
 
-        for (DataSchemaNode caseNode : augmentedNodes) {
+        for (final DataSchemaNode caseNode : augmentedNodes) {
             if (caseNode != null) {
                 final String packageName = packageNameForGeneratedType(basePackageName, caseNode.getPath());
                 final GeneratedTypeBuilder caseTypeBuilder = addDefaultInterfaceDefinition(packageName, caseNode, module);
@@ -1329,6 +1339,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
      * @param leaf
      *            leaf schema node which is mapped as getter method which is
      *            added to <code>typeBuilder</code>
+     * @param module
+     *            Module in which type was defined
      * @return boolean value
      *         <ul>
      *         <li>false - if <code>leaf</code> or <code>typeBuilder</code> are
@@ -1336,7 +1348,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
      *         <li>true - in other cases</li>
      *         </ul>
      */
-    private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf) {
+    private Type resolveLeafSchemaNodeAsMethod(final GeneratedTypeBuilder typeBuilder, final LeafSchemaNode leaf, Module module) {
         Type returnType = null;
         if ((leaf != null) && (typeBuilder != null)) {
             final String leafName = leaf.getQName().getLocalName();
@@ -1354,7 +1366,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
                     returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
                     final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
                     final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, leaf.getQName(),
-                            typeBuilder);
+                            typeBuilder,module);
 
                     if (enumBuilder != null) {
                         returnType = enumBuilder.toInstance(typeBuilder);
@@ -1385,7 +1397,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
 
     private void processContextRefExtension(final LeafSchemaNode leaf, final MethodSignatureBuilder getter,
             final Module module) {
-        for (UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
+        for (final UnknownSchemaNode node : leaf.getUnknownSchemaNodes()) {
             final QName nodeType = node.getNodeType();
             if ("context-reference".equals(nodeType.getLocalName())) {
                 final String nodeParam = node.getNodeParameter();
@@ -1398,7 +1410,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
                     identity = findIdentityByName(module.getIdentities(), iterator.next());
                     basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
                 } else if (length == 2) {
-                    String prefix = iterator.next();
+                    final String prefix = iterator.next();
                     final Module dependentModule = findModuleFromImports(module.getImports(), prefix);
                     if (dependentModule == null) {
                         throw new IllegalArgumentException("Failed to process context-reference: unknown prefix "
@@ -1426,7 +1438,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
     }
 
     private IdentitySchemaNode findIdentityByName(final Set<IdentitySchemaNode> identities, final String name) {
-        for (IdentitySchemaNode id : identities) {
+        for (final IdentitySchemaNode id : identities) {
             if (id.getQName().getLocalName().equals(name)) {
                 return id;
             }
@@ -1435,7 +1447,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
     }
 
     private Module findModuleFromImports(final Set<ModuleImport> imports, final String prefix) {
-        for (ModuleImport imp : imports) {
+        for (final ModuleImport imp : imports) {
             if (imp.getPrefix().equals(prefix)) {
                 return schemaContext.findModuleByName(imp.getModuleName(), imp.getRevision());
             }
@@ -1451,23 +1463,27 @@ public class BindingGeneratorImpl implements BindingGenerator {
             if (leafDesc == null) {
                 leafDesc = "";
             }
-
-            if (leafName != null) {
-                Type returnType = null;
-                final TypeDefinition<?> typeDef = leaf.getType();
-                if (typeDef instanceof UnionTypeDefinition) {
-                    // GeneratedType for this type definition should be already
-                    // created
-                    QName qname = typeDef.getQName();
-                    Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
-                            qname.getRevision());
-                    final ModuleContext mc = genCtx.get(unionModule);
-                    returnType = mc.getTypedefs().get(typeDef.getPath());
-                } else {
-                    returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
-                }
-                return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
+            Type returnType = null;
+            final TypeDefinition<?> typeDef = leaf.getType();
+            if (typeDef instanceof UnionTypeDefinition) {
+                // GeneratedType for this type definition should be already
+                // created
+                final QName qname = typeDef.getQName();
+                final Module unionModule = schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
+                        qname.getRevision());
+                final ModuleContext mc = genCtx.get(unionModule);
+                returnType = mc.getTypedefs().get(typeDef.getPath());
+            } else if (typeDef instanceof EnumTypeDefinition && BaseTypes.ENUMERATION_QNAME.equals(typeDef.getQName())) {
+                // Annonymous enumeration (already generated, since it is inherited via uses).
+                LeafSchemaNode originalLeaf = (LeafSchemaNode) SchemaNodeUtils.getRootOriginalIfPossible(leaf);
+                QName qname = originalLeaf.getQName();
+                final Module enumModule =  schemaContext.findModuleByNamespaceAndRevision(qname.getNamespace(),
+                        qname.getRevision());
+                returnType = genCtx.get(enumModule).getInnerType(originalLeaf.getType().getPath());
+            } else {
+                returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, leaf);
             }
+            return resolveLeafSchemaNodeAsProperty(toBuilder, leaf, returnType, isReadOnly);
         }
         return false;
     }
@@ -1520,6 +1536,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
      * @param node
      *            leaf list schema node which is added to
      *            <code>typeBuilder</code> as getter method
+     * @param module
      * @return boolean value
      *         <ul>
      *         <li>true - if <code>node</code>, <code>typeBuilder</code>,
@@ -1527,7 +1544,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
      *         <li>false - other cases</li>
      *         </ul>
      */
-    private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node) {
+    private boolean resolveLeafListSchemaNode(final GeneratedTypeBuilder typeBuilder, final LeafListSchemaNode node, Module module) {
         if ((node != null) && (typeBuilder != null)) {
             final QName nodeName = node.getQName();
 
@@ -1540,7 +1557,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
                     returnType = typeProvider.javaTypeForSchemaDefinitionType(typeDef, node);
                     final EnumTypeDefinition enumTypeDef = (EnumTypeDefinition) typeDef;
                     final EnumBuilder enumBuilder = resolveInnerEnumFromTypeDefinition(enumTypeDef, nodeName,
-                            typeBuilder);
+                            typeBuilder,module);
                     returnType = new ReferencedTypeImpl(enumBuilder.getPackageName(), enumBuilder.getName());
                     ((TypeProviderImpl) typeProvider).putReferencedType(node.getPath(), returnType);
                 } else if (typeDef instanceof UnionType) {
@@ -1578,10 +1595,11 @@ public class BindingGeneratorImpl implements BindingGenerator {
         genTOBuilder.setIsUnion(true);
         ((TypeProviderImpl) typeProvider).addUnitsToGenTO(genTOBuilder, typeDef.getUnits());
 
-        // union builder
-        final GeneratedTOBuilder unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),
-                genTOBuilder.getName() + "Builder");
-        unionBuilder.setIsUnionBuilder(true);
+
+
+        final GeneratedTOBuilder unionBuilder = createUnionBuilder(genTOBuilder,typeBuilder);
+
+
         final MethodSignatureBuilder method = unionBuilder.addMethod("getDefaultInstance");
         method.setReturnType(returnType);
         method.addParameter(Types.STRING, "defaultValue");
@@ -1598,6 +1616,22 @@ public class BindingGeneratorImpl implements BindingGenerator {
         return returnType.toInstance();
     }
 
+    private GeneratedTOBuilder createUnionBuilder(final GeneratedTOBuilder genTOBuilder, final GeneratedTypeBuilder typeBuilder) {
+
+        final String outerCls = Types.getOuterClassName(genTOBuilder);
+        final StringBuilder name;
+        if(outerCls != null) {
+            name = new StringBuilder(outerCls);
+        } else {
+            name = new StringBuilder();
+        }
+        name.append(genTOBuilder.getName());
+        name.append("Builder");
+        final GeneratedTOBuilderImpl unionBuilder = new GeneratedTOBuilderImpl(typeBuilder.getPackageName(),name.toString());
+        unionBuilder.setIsUnionBuilder(true);
+        return unionBuilder;
+    }
+
     private GeneratedTypeBuilder addDefaultInterfaceDefinition(final String packageName, final SchemaNode schemaNode,
             final Module module) {
         return addDefaultInterfaceDefinition(packageName, schemaNode, null, module);
@@ -1740,7 +1774,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
         } else {
             method.append("get");
         }
-        String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
+        final String name = BindingMapping.toFirstUpper(BindingMapping.getPropertyName(localName));
         method.append(name);
         return method.toString();
     }
@@ -1808,7 +1842,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
         if (schemaNode instanceof LeafSchemaNode) {
             final LeafSchemaNode leaf = (LeafSchemaNode) schemaNode;
             final String leafName = leaf.getQName().getLocalName();
-            final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf);
+            final Type type = resolveLeafSchemaNodeAsMethod(typeBuilder, leaf,module);
             if (listKeys.contains(leafName)) {
                 if (type == null) {
                     resolveLeafSchemaNodeAsProperty(genTOBuilder, leaf, true, module);
@@ -1818,11 +1852,11 @@ public class BindingGeneratorImpl implements BindingGenerator {
             }
         } else if (!schemaNode.isAddedByUses()) {
             if (schemaNode instanceof LeafListSchemaNode) {
-                resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode);
+                resolveLeafListSchemaNode(typeBuilder, (LeafListSchemaNode) schemaNode, module);
             } else if (schemaNode instanceof ContainerSchemaNode) {
                 containerToGenType(module, basePackageName, typeBuilder, typeBuilder, (ContainerSchemaNode) schemaNode);
-            } else if (schemaNode instanceof ChoiceNode) {
-                choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceNode) schemaNode);
+            } else if (schemaNode instanceof ChoiceSchemaNode) {
+                choiceToGeneratedType(module, basePackageName, typeBuilder, (ChoiceSchemaNode) schemaNode);
             } else if (schemaNode instanceof ListSchemaNode) {
                 listToGenType(module, basePackageName, typeBuilder, typeBuilder, (ListSchemaNode) schemaNode);
             }
@@ -1834,7 +1868,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
         checkArgument(typeBuilder != null, "Generated Type Builder cannot be NULL.");
 
         if (genTOBuilder != null) {
-            GeneratedTransferObject genTO = genTOBuilder.toInstance();
+            final GeneratedTransferObject genTO = genTOBuilder.toInstance();
             constructGetter(typeBuilder, "key", "Returns Primary Key of Yang List Type", genTO);
             genCtx.get(module).addGeneratedTOBuilder(genTOBuilder);
         }
@@ -1853,9 +1887,9 @@ public class BindingGeneratorImpl implements BindingGenerator {
     private List<String> listKeys(final ListSchemaNode list) {
         final List<String> listKeys = new ArrayList<>();
 
-        List<QName> keyDefinition = list.getKeyDefinition();
+        final List<QName> keyDefinition = list.getKeyDefinition();
         if (keyDefinition != null) {
-            for (QName keyDef : keyDefinition) {
+            for (final QName keyDef : keyDefinition) {
                 listKeys.add(keyDef.getLocalName());
             }
         }
@@ -1922,7 +1956,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
                 throw new IllegalStateException("No GeneratedTOBuilder objects generated from union " + typeDef);
             }
             resultTOBuilder = types.remove(0);
-            for (GeneratedTOBuilder genTOBuilder : types) {
+            for (final GeneratedTOBuilder genTOBuilder : types) {
                 resultTOBuilder.addEnclosingTransferObject(genTOBuilder);
             }
 
@@ -1937,7 +1971,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
                     packageName, typeDef, classNameFromLeaf, parentModule.getName()));
         }
         if (genTOBuilders != null && !genTOBuilders.isEmpty()) {
-            for (GeneratedTOBuilder genTOBuilder : genTOBuilders) {
+            for (final GeneratedTOBuilder genTOBuilder : genTOBuilders) {
                 typeBuilder.addEnclosingTransferObject(genTOBuilder);
             }
             return genTOBuilders.get(0);
@@ -1964,7 +1998,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
      */
     private GeneratedTypeBuilder addImplementedInterfaceFromUses(final DataNodeContainer dataNodeContainer,
             final GeneratedTypeBuilder builder) {
-        for (UsesNode usesNode : dataNodeContainer.getUses()) {
+        for (final UsesNode usesNode : dataNodeContainer.getUses()) {
             if (usesNode.getGroupingPath() != null) {
                 final GeneratedType genType = findGroupingByPath(usesNode.getGroupingPath()).toInstance();
                 if (genType == null) {
@@ -2031,7 +2065,7 @@ public class BindingGeneratorImpl implements BindingGenerator {
             final Module module = findParentModule(schemaContext, schemaNode);
             final StringBuilder linkToBuilderClass = new StringBuilder();
             final String[] namespace = Iterables.toArray(BSDOT_SPLITTER.split(fullyQualifiedName), String.class);
-            String className = namespace[namespace.length - 1];
+            final String className = namespace[namespace.length - 1];
 
             if (hasBuilderClass(schemaNode)) {
                 linkToBuilderClass.append(className);
@@ -2122,8 +2156,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
     }
 
     private GeneratedTypeBuilder findChildNodeByPath(final SchemaPath path) {
-        for (ModuleContext ctx : genCtx.values()) {
-            GeneratedTypeBuilder result = ctx.getChildNode(path);
+        for (final ModuleContext ctx : genCtx.values()) {
+            final GeneratedTypeBuilder result = ctx.getChildNode(path);
             if (result != null) {
                 return result;
             }
@@ -2132,8 +2166,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
     }
 
     private GeneratedTypeBuilder findGroupingByPath(final SchemaPath path) {
-        for (ModuleContext ctx : genCtx.values()) {
-            GeneratedTypeBuilder result = ctx.getGrouping(path);
+        for (final ModuleContext ctx : genCtx.values()) {
+            final GeneratedTypeBuilder result = ctx.getGrouping(path);
             if (result != null) {
                 return result;
             }
@@ -2142,8 +2176,8 @@ public class BindingGeneratorImpl implements BindingGenerator {
     }
 
     private GeneratedTypeBuilder findCaseByPath(final SchemaPath path) {
-        for (ModuleContext ctx : genCtx.values()) {
-            GeneratedTypeBuilder result = ctx.getCase(path);
+        for (final ModuleContext ctx : genCtx.values()) {
+            final GeneratedTypeBuilder result = ctx.getCase(path);
             if (result != null) {
                 return result;
             }
index 283a262e58817cd634e891b34677c1776008b708..4f8b5acb1821184260b1e670bb3313adf6ef96d3 100644 (file)
@@ -17,7 +17,7 @@ import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
@@ -90,8 +90,8 @@ public final class BindingSchemaContextUtils {
             final QName targetQName) {
 
         for (DataSchemaNode child : ctx.getChildNodes()) {
-            if (child instanceof ChoiceNode) {
-                DataNodeContainer potential = findInCases(((ChoiceNode) child), targetQName);
+            if (child instanceof ChoiceSchemaNode) {
+                DataNodeContainer potential = findInCases(((ChoiceSchemaNode) child), targetQName);
                 if (potential != null) {
                     return Optional.of(potential);
                 }
@@ -107,7 +107,7 @@ public final class BindingSchemaContextUtils {
         return Optional.absent();
     }
 
-    private static DataNodeContainer findInCases(final ChoiceNode choiceNode, final QName targetQName) {
+    private static DataNodeContainer findInCases(final ChoiceSchemaNode choiceNode, final QName targetQName) {
         for (ChoiceCaseNode caze : choiceNode.getCases()) {
             Optional<DataNodeContainer> potential = findDataNodeContainer(caze, targetQName);
             if (potential.isPresent()) {
@@ -165,24 +165,24 @@ public final class BindingSchemaContextUtils {
         return augmentations;
     }
 
-    public static Optional<ChoiceNode> findInstantiatedChoice(final DataNodeContainer parent, final Class<?> choiceClass) {
+    public static Optional<ChoiceSchemaNode> findInstantiatedChoice(final DataNodeContainer parent, final Class<?> choiceClass) {
         return findInstantiatedChoice(parent, BindingReflections.findQName(choiceClass));
     }
 
-    public static Optional<ChoiceNode> findInstantiatedChoice(final DataNodeContainer ctxNode, final QName choiceName) {
+    public static Optional<ChoiceSchemaNode> findInstantiatedChoice(final DataNodeContainer ctxNode, final QName choiceName) {
         DataSchemaNode potential = ctxNode.getDataChildByName(choiceName);
         if (potential == null) {
             potential = ctxNode.getDataChildByName(choiceName.getLocalName());
         }
 
-        if (potential instanceof ChoiceNode) {
-            return Optional.of((ChoiceNode) potential);
+        if (potential instanceof ChoiceSchemaNode) {
+            return Optional.of((ChoiceSchemaNode) potential);
         }
 
         return Optional.absent();
     }
 
-    public static Optional<ChoiceCaseNode> findInstantiatedCase(final ChoiceNode instantiatedChoice, final ChoiceCaseNode originalDefinition) {
+    public static Optional<ChoiceCaseNode> findInstantiatedCase(final ChoiceSchemaNode instantiatedChoice, final ChoiceCaseNode originalDefinition) {
         ChoiceCaseNode potential = instantiatedChoice.getCaseNodeByName(originalDefinition.getQName());
         if(originalDefinition.equals(potential)) {
             return Optional.of(potential);
diff --git a/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/CodecMapping.java b/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/CodecMapping.java
deleted file mode 100644 (file)
index 4622ab7..0000000
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.sal.binding.generator.impl;
-
-import java.lang.reflect.Field;
-import java.util.Map;
-import org.opendaylight.yangtools.yang.binding.BindingCodec;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.impl.codec.IdentityCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.InstanceIdentifierCodec;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public final class CodecMapping {
-
-    private static final Logger LOG = LoggerFactory.getLogger(CodecMapping.class);
-
-    public static final String INSTANCE_IDENTIFIER_CODEC = "INSTANCE_IDENTIFIER_CODEC";
-    public static final String IDENTITYREF_CODEC = "IDENTITYREF_CODEC";
-
-    public static final String CLASS_TO_CASE_MAP = "CLASS_TO_CASE";
-    public static final String COMPOSITE_TO_CASE = "COMPOSITE_TO_CASE";
-    public static final String AUGMENTATION_CODEC = "AUGMENTATION_CODEC";
-    public static final String DISPATCH_CODEC = "DISPATCH_CODEC";
-
-    private CodecMapping() {
-        throw new UnsupportedOperationException("Utility class should not be instantiated");
-    }
-
-    public static void setIdentifierCodec(Class<?> obj,InstanceIdentifierCodec codec) {
-        Field instanceIdField;
-        try {
-            instanceIdField = obj.getField(INSTANCE_IDENTIFIER_CODEC);
-            if (instanceIdField != null) {
-                instanceIdField.set(null, codec);
-            }
-        } catch (NoSuchFieldException e) {
-           LOG.trace("Instance identifier codec is not needed for {}",obj.getName(),e);
-        } catch (SecurityException | IllegalAccessException e) {
-            LOG.error("Instance identifier could not be set for {}",obj.getName(),e);
-        }
-    }
-
-    public static void setIdentityRefCodec(Class<?> obj,IdentityCodec<?> codec) {
-        Field instanceIdField;
-        try {
-            instanceIdField = obj.getField(IDENTITYREF_CODEC);
-            if (instanceIdField != null) {
-                instanceIdField.set(null, codec);
-            }
-        } catch (NoSuchFieldException e) {
-           LOG.trace("Instance identifier codec is not needed for {}",obj.getName(),e);
-        } catch (SecurityException | IllegalAccessException e) {
-            LOG.error("Instance identifier could not be set for {}",obj.getName(),e);
-        }
-    }
-
-    public static void setClassToCaseMap(Class<? extends BindingCodec<?,?>> codec,
-            Map<Class<?>,BindingCodec<?,?>> classToCaseRawCodec) {
-        Field instanceIdField;
-        try {
-            instanceIdField = codec.getField(CLASS_TO_CASE_MAP);
-            instanceIdField.set(null, classToCaseRawCodec);
-        } catch (NoSuchFieldException e) {
-            LOG.debug("BUG: Class to case mappping is not needed for {}",codec.getName(),e);
-        } catch (SecurityException | IllegalAccessException e) {
-            LOG.error("Class to case mappping could not be set for {}",codec.getName(),e);
-        }
-    }
-
-    public static void setCompositeNodeToCaseMap(Class<? extends BindingCodec<?,?>> codec,
-            Map<CompositeNode,BindingCodec<?,?>> compositeToCase) {
-        Field instanceIdField;
-        try {
-            instanceIdField = codec.getField(COMPOSITE_TO_CASE);
-            instanceIdField.set(null, compositeToCase);
-        } catch (NoSuchFieldException e) {
-            LOG.debug("BUG: Class to case mappping is not needed for {}",codec.getName(),e);
-        } catch (SecurityException | IllegalAccessException e) {
-            LOG.error("Composite node to case mappping could not be set for {}",codec.getName(),e);
-        }
-    }
-
-    public static void setDispatchCodec(Class<? extends BindingCodec<?,?>> codec,
-            BindingCodec<?, ?> dispatchCodec) {
-        Field instanceIdField;
-        try {
-            instanceIdField = codec.getField(DISPATCH_CODEC);
-            instanceIdField.set(null, dispatchCodec);
-        } catch (NoSuchFieldException e) {
-            LOG.debug("BUG: dispatch codec is not needed for {}",codec.getName(),e);
-        } catch (SecurityException | IllegalAccessException e) {
-            LOG.error("Dispatch codec could not be set for {}",codec.getName(),e);
-        }
-    }
-
-    public static void setAugmentationCodec(Class<? extends BindingCodec<?,?>> dataCodec,
-            BindingCodec<?,?> augmentableCodec) {
-            Field instanceIdField;
-            try {
-                instanceIdField = dataCodec.getField(AUGMENTATION_CODEC);
-                instanceIdField.set(null, augmentableCodec);
-            } catch (NoSuchFieldException e) {
-                LOG.debug("BUG: Augmentation codec is not needed for {}",dataCodec.getName(),e);
-            } catch (SecurityException | IllegalAccessException e) {
-                LOG.error("Augmentation codec could not be set for {}",dataCodec.getName(),e);
-            }
-    }
-
-
-    public static BindingCodec<?,?> getAugmentationCodec(Class<? extends BindingCodec<?,?>> dataCodec) {
-            Field instanceIdField;
-            try {
-                instanceIdField = dataCodec.getField(AUGMENTATION_CODEC);
-                return (BindingCodec<?,?>) instanceIdField.get(null);
-            } catch (NoSuchFieldException e) {
-                LOG.debug("BUG: Augmentation codec is not needed for {}",dataCodec.getName(),e);
-            } catch (SecurityException | IllegalAccessException e) {
-                LOG.error("Augmentation codec could not be set for {}",dataCodec.getName(),e);
-            }
-            return null;
-    }
-}
diff --git a/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/GeneratorListener.java b/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/GeneratorListener.java
deleted file mode 100644 (file)
index a675509..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.sal.binding.generator.impl;
-
-import java.util.Map;
-
-import org.opendaylight.yangtools.yang.binding.BindingCodec;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
-
-public interface GeneratorListener {
-    void onClassProcessed(Class<?> cl);
-
-    void onCodecCreated(Class<?> codec);
-    void onValueCodecCreated(Class<?> valueClass, Class<?> valueCodec);
-    void onCaseCodecCreated(Class<?> choiceClass, Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec);
-    void onDataContainerCodecCreated(Class<?> dataClass, Class<? extends BindingCodec<?, ?>> dataCodec);
-
-    void onChoiceCodecCreated(Class<?> choiceClass,
-                              Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec, ChoiceNode schema);
-}
diff --git a/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/InstanceIdentifierCodecImpl.java b/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/InstanceIdentifierCodecImpl.java
deleted file mode 100644 (file)
index aeda45c..0000000
+++ /dev/null
@@ -1,254 +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.yangtools.sal.binding.generator.impl;
-
-import com.google.common.collect.ImmutableList;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.WeakHashMap;
-import java.util.concurrent.ConcurrentHashMap;
-import org.opendaylight.yangtools.concepts.Identifiable;
-import org.opendaylight.yangtools.yang.binding.Augmentation;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.IdentifiableItem;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
-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.api.Node;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
-import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
-import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
-import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
-import org.opendaylight.yangtools.yang.data.impl.codec.IdentifierCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.InstanceIdentifierCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.ValueWithQName;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class InstanceIdentifierCodecImpl implements InstanceIdentifierCodec {
-    private static final Logger LOG = LoggerFactory.getLogger(InstanceIdentifierCodecImpl.class);
-
-    private final CodecRegistry codecRegistry;
-
-    private final Map<Class<?>,Set<List<QName>>> augmentationAdapted = new WeakHashMap<>();
-
-    private final Map<Class<?>, Map<List<QName>, Class<?>>> classToPreviousAugment = Collections
-            .synchronizedMap(new WeakHashMap<Class<?>, Map<List<QName>, Class<?>>>());
-
-    public InstanceIdentifierCodecImpl(final CodecRegistry registry) {
-        this.codecRegistry = registry;
-    }
-
-    @Override
-    public InstanceIdentifier<? extends Object> deserialize(
-            final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier input) {
-        Class<?> baType = null;
-        Iterable<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument> biArgs = input.getPathArguments();
-        List<QName> scannedPath = new ArrayList<>();
-        List<InstanceIdentifier.PathArgument> baArgs = new ArrayList<InstanceIdentifier.PathArgument>();
-        for (org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument biArg : biArgs) {
-
-            scannedPath.add(biArg.getNodeType());
-            org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument baArg = deserializePathArgument(
-                    biArg, scannedPath);
-            if (baArg != null) {
-                baType = baArg.getType();
-            }
-            Map<List<QName>, Class<?>> injectAugment = classToPreviousAugment.get(baType);
-            if (injectAugment != null) {
-                @SuppressWarnings("unchecked")
-                Class<? extends DataObject> augment = (Class<? extends DataObject>) injectAugment.get(scannedPath);
-                if (augment != null) {
-                    baArgs.add(new Item(augment));
-                }
-            }
-            baArgs.add(baArg);
-        }
-        InstanceIdentifier<?> ret = InstanceIdentifier.create(baArgs);
-        LOG.debug("DOM Instance Identifier {} deserialized to {}", input, ret);
-        return ret;
-    }
-
-    @Override
-    public InstanceIdentifier<? extends Object> deserialize(
-            final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier input,
-            final InstanceIdentifier<?> bindingIdentifier) {
-        return deserialize(input);
-    }
-
-    private InstanceIdentifier.PathArgument deserializeNodeIdentifier(
-            final NodeIdentifier argument, final List<QName> processedPath) {
-        @SuppressWarnings("rawtypes")
-        final Class cls = codecRegistry.getClassForPath(processedPath);
-        @SuppressWarnings("unchecked")
-        Item<DataObject> item = new Item<>(cls);
-        return item;
-    }
-
-    private InstanceIdentifier.PathArgument deserializeNodeIdentifierWithPrecicates(
-            final NodeIdentifierWithPredicates argument, final List<QName> processedPath) {
-        @SuppressWarnings("rawtypes")
-        final Class type = codecRegistry.getClassForPath(processedPath);
-        @SuppressWarnings({ "unchecked", "rawtypes" })
-        final IdentifierCodec codec = codecRegistry
-                .<Identifiable<? extends Object>> getIdentifierCodecForIdentifiable(type);
-        CompositeNode _compositeNode = this.toCompositeNode(argument);
-        @SuppressWarnings("unchecked")
-        ValueWithQName<CompositeNode> deserialize = codec.deserialize(_compositeNode);
-        Object value = null;
-        if (deserialize != null) {
-            value = deserialize.getValue();
-        }
-        return CodecTypeUtils.newIdentifiableItem(type, value);
-    }
-
-    public CompositeNode toCompositeNode(final NodeIdentifierWithPredicates predicates) {
-        Set<Map.Entry<QName, Object>> keyValues = predicates.getKeyValues().entrySet();
-        List<Node<?>> values = new ArrayList<>(keyValues.size());
-        for (Map.Entry<QName, Object> keyValue : keyValues) {
-            values.add(new SimpleNodeTOImpl<Object>(keyValue.getKey(), null, keyValue.getValue()));
-        }
-        return new CompositeNodeTOImpl(predicates.getNodeType(), null, values);
-    }
-
-    @Override
-    public org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier serialize(final InstanceIdentifier<?> input) {
-        Class<?> previousAugmentation = null;
-        Iterable<InstanceIdentifier.PathArgument> pathArgs = input.getPathArguments();
-        QName previousQName = null;
-        List<PathArgument> components = new ArrayList<>();
-        List<QName> qnamePath = new ArrayList<>();
-        for (InstanceIdentifier.PathArgument baArg : pathArgs) {
-            if (!Augmentation.class.isAssignableFrom(baArg.getType())) {
-                PathArgument biArg = serializePathArgumentAndUpdateMapping(qnamePath, baArg, previousQName,previousAugmentation);
-                components.add(biArg);
-                qnamePath.add(biArg.getNodeType());
-                previousQName = biArg.getNodeType();
-                previousAugmentation = null;
-            } else {
-                previousQName = codecRegistry.getQNameForAugmentation(baArg.getType());
-                previousAugmentation = baArg.getType();
-                ensureAugmentation(qnamePath,previousQName,baArg.getType());
-            }
-        }
-        org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier ret =
-                org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.create(components);
-        LOG.debug("Binding Instance Identifier {} serialized to DOM InstanceIdentifier {}", input, ret);
-        return ret;
-    }
-
-    private synchronized void ensureAugmentation(final List<QName> augPath, final QName augQName, final Class<? extends DataObject> type) {
-        Set<List<QName>> augPotential = augmentationAdapted.get(type);
-        if(augPotential == null) {
-            augPotential = new HashSet<>();
-            augmentationAdapted.put(type, augPotential);
-        }
-        ImmutableList<QName> augTargetPath = ImmutableList.copyOf(augPath);
-        if(augPotential.contains(augPath)) {
-            return;
-        }
-
-        for(Class<? extends DataObject> child : BindingReflections.getChildrenClasses(type)) {
-            Item<? extends DataObject> baArg = new Item<>(child);
-            PathArgument biArg = serializePathArgumentAndUpdateMapping(augPath, baArg, augQName,type);
-        }
-        augPotential.add(augTargetPath);
-    }
-
-
-    public Class<? extends Object> updateAugmentationInjection(final Class<? extends DataObject> class1,
-            final List<QName> list, final Class<?> augmentation) {
-        if (classToPreviousAugment.get(class1) == null) {
-            classToPreviousAugment.put(class1, new ConcurrentHashMap<List<QName>, Class<?>>());
-        }
-        return classToPreviousAugment.get(class1).put(list, augmentation);
-    }
-
-    private PathArgument serializeItem(final Item<?> argument, final QName previousQname) {
-        Class<?> type = argument.getType();
-        QName qname = BindingReflections.findQName(type);
-        if (previousQname == null || (BindingReflections.isAugmentationChild(argument.getType()))) {
-            return new NodeIdentifier(qname);
-        }
-        return new NodeIdentifier(QName.create(previousQname, qname.getLocalName()));
-    }
-
-    private PathArgument serializeIdentifiableItem(final IdentifiableItem<?,?> argument, final QName previousQname) {
-        @SuppressWarnings("rawtypes")
-        Class type = argument.getType();
-        @SuppressWarnings("unchecked")
-        IdentifierCodec<? extends Object> keyCodec = codecRegistry.getIdentifierCodecForIdentifiable(type);
-        QName qname = BindingReflections.findQName(type);
-        if (previousQname != null && !(BindingReflections.isAugmentationChild(argument.getType()))) {
-            qname = QName.create(previousQname, qname.getLocalName());
-        }
-        @SuppressWarnings({ "rawtypes", "unchecked" })
-        ValueWithQName combinedInput = new ValueWithQName(previousQname, argument.getKey());
-        @SuppressWarnings("unchecked")
-        CompositeNode compositeOutput = keyCodec.serialize(combinedInput);
-
-        final Map<QName, Object> predicates = new LinkedHashMap<>();
-        for (Node<?> outputValue : compositeOutput.getValue()) {
-            predicates.put(outputValue.getNodeType(), outputValue.getValue());
-        }
-        if (previousQname == null) {
-            return new NodeIdentifierWithPredicates(qname, predicates);
-        }
-        return new NodeIdentifierWithPredicates(qname, predicates);
-    }
-
-    private org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument deserializePathArgument(
-            final PathArgument argument, final List<QName> processedPath) {
-        if (argument instanceof NodeIdentifier) {
-            return deserializeNodeIdentifier((NodeIdentifier) argument, processedPath);
-        } else if (argument instanceof NodeIdentifierWithPredicates) {
-            return deserializeNodeIdentifierWithPrecicates((NodeIdentifierWithPredicates) argument, processedPath);
-        } else {
-            throw new IllegalArgumentException("Unhandled parameter types: "
-                    + Arrays.<Object> asList(argument, processedPath).toString());
-        }
-    }
-
-    private PathArgument serializePathArgumentAndUpdateMapping(final List<QName> parentPath, final InstanceIdentifier.PathArgument baArg, final QName previousQName, final Class<?> previousAugmentation) {
-        org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument biArg = serializePathArgument(baArg, previousQName);
-        List<QName> qnamePath = new ArrayList<>(parentPath);
-        qnamePath.add(biArg.getNodeType());
-        ImmutableList<QName> currentPath = ImmutableList.copyOf(qnamePath);
-        codecRegistry.putPathToClass(currentPath, baArg.getType());
-        if (previousAugmentation != null) {
-            updateAugmentationInjection(baArg.getType(), currentPath, previousAugmentation);
-        }
-        return biArg;
-    }
-
-    private PathArgument serializePathArgument(
-            final InstanceIdentifier.PathArgument argument,
-            final QName previousQname) {
-        if (argument instanceof IdentifiableItem) {
-            return serializeIdentifiableItem((IdentifiableItem<?,?>) argument, previousQname);
-        } else if (argument instanceof Item) {
-            return serializeItem((Item<?>) argument, previousQname);
-        } else {
-            throw new IllegalArgumentException("Unhandled parameter types: "
-                    + Arrays.<Object> asList(argument, previousQname).toString());
-        }
-    }
-
-
-
-}
diff --git a/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/IntermediateMapping.java b/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/IntermediateMapping.java
deleted file mode 100644 (file)
index 29318f0..0000000
+++ /dev/null
@@ -1,83 +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.yangtools.sal.binding.generator.impl;
-
-import com.google.common.base.Preconditions;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
-import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
-
-/**
- * @deprecated Use {@link NormalizedNode} and their stream writer codec suite.
- */
-@Deprecated
-public class IntermediateMapping {
-    private IntermediateMapping() {
-        throw new UnsupportedOperationException("Utility class should not be instantiated");
-    }
-
-    public static Node<? extends Object> toNode(final Map<? extends Object, ? extends Object> map) {
-        if ((map instanceof Node<?>)) {
-            return ((Node<?>) map);
-        }
-        @SuppressWarnings("unchecked")
-        final Map<QName, Object> nodeMap = ((Map<QName, Object>) map);
-        Preconditions.checkArgument(map.size() == 1);
-        final Entry<QName, Object> elem = nodeMap.entrySet().iterator().next();
-        final QName qname = elem.getKey();
-        final Object value = elem.getValue();
-        return toNodeImpl(qname, value);
-    }
-
-    protected static Node<? extends Object> _toNodeImpl(final QName name, final List<? extends Object> objects) {
-        List<Node<? extends Object>> values = new ArrayList<>(objects.size());
-        for (Object obj : objects) {
-            if ((obj instanceof Node<?>)) {
-                values.add(((Node<?>) obj));
-            } else {
-                if ((obj instanceof Map<?, ?>)) {
-                    Node<? extends Object> _node = IntermediateMapping.toNode(((Map<?, ?>) obj));
-                    values.add(_node);
-                }
-            }
-        }
-        return new CompositeNodeTOImpl(name, null, values);
-    }
-
-    protected static Node<? extends Object> _toNodeImpl(final QName name, final Map<QName, Object> object) {
-        throw new UnsupportedOperationException("Unsupported node hierarchy.");
-    }
-
-    protected static Node<? extends Object> _toNodeImpl(final QName name, final Object object) {
-        return new SimpleNodeTOImpl<Object>(name, null, object);
-    }
-
-    @SuppressWarnings("unchecked")
-    public static Node<? extends Object> toNodeImpl(final QName name, final Object objects) {
-        if (objects instanceof List) {
-            return _toNodeImpl(name, (List<?>) objects);
-        } else if (objects instanceof Map) {
-            return _toNodeImpl(name, (Map<QName, Object>) objects);
-        } else if (objects != null) {
-            return _toNodeImpl(name, objects);
-        } else {
-            throw new IllegalArgumentException("Unhandled parameter types: "
-                    + Arrays.<Object> asList(name, objects).toString());
-        }
-    }
-
-}
diff --git a/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/LazyGeneratedCodecRegistry.java b/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/LazyGeneratedCodecRegistry.java
deleted file mode 100644 (file)
index 8a4c1c9..0000000
+++ /dev/null
@@ -1,1425 +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.yangtools.sal.binding.generator.impl;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.BiMap;
-import com.google.common.collect.HashBiMap;
-import com.google.common.collect.HashMultimap;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Multimap;
-import com.google.common.collect.Multimaps;
-import java.util.AbstractMap.SimpleEntry;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.WeakHashMap;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
-import org.opendaylight.yangtools.binding.generator.util.Types;
-import org.opendaylight.yangtools.concepts.Delegator;
-import org.opendaylight.yangtools.concepts.Identifiable;
-import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
-import org.opendaylight.yangtools.sal.binding.generator.util.CodeGenerationException;
-import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
-import org.opendaylight.yangtools.sal.binding.model.api.Type;
-import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
-import org.opendaylight.yangtools.util.ClassLoaderUtils;
-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.BindingCodec;
-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.Identifier;
-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.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
-import org.opendaylight.yangtools.yang.data.impl.codec.AugmentationCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.ChoiceCaseCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.ChoiceCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
-import org.opendaylight.yangtools.yang.data.impl.codec.DataContainerCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.DomCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.IdentifierCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.IdentityCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.InstanceIdentifierCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.ValueWithQName;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
-import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
-import org.opendaylight.yangtools.yang.model.api.SchemaNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-class LazyGeneratedCodecRegistry implements CodecRegistry, SchemaContextListener, GeneratorListener {
-
-    private static final Logger LOG = LoggerFactory.getLogger(LazyGeneratedCodecRegistry.class);
-
-    // Concrete class to codecs
-    private static final Map<Class<?>, DataContainerCodec<?>> containerCodecs = Collections
-            .synchronizedMap(new WeakHashMap<Class<?>, DataContainerCodec<?>>());
-    private static final Map<Class<?>, IdentifierCodec<?>> identifierCodecs = Collections
-            .synchronizedMap(new WeakHashMap<Class<?>, IdentifierCodec<?>>());
-    private static final Map<Class<?>, PublicChoiceCodecImpl<?>> choiceCodecs = Collections
-            .synchronizedMap(new WeakHashMap<Class<?>, PublicChoiceCodecImpl<?>>());
-    private static final Map<Class<?>, ChoiceCaseCodecImpl<?>> caseCodecs = Collections
-            .synchronizedMap(new WeakHashMap<Class<?>, ChoiceCaseCodecImpl<?>>());
-    private static final Map<Class<?>, AugmentableDispatchCodec> augmentableCodecs = Collections
-            .synchronizedMap(new WeakHashMap<Class<?>, AugmentableDispatchCodec>());
-    private static final Map<Class<?>, AugmentationCodecWrapper<?>> augmentationCodecs = Collections
-            .synchronizedMap(new WeakHashMap<Class<?>, AugmentationCodecWrapper<?>>());
-
-    private static final Map<Class<?>, LocationAwareDispatchCodec<?>> dispatchCodecs = Collections
-            .synchronizedMap(new WeakHashMap<Class<?>, LocationAwareDispatchCodec<?>>());
-
-    private static final Map<Class<?>, QName> identityQNames = Collections
-            .synchronizedMap(new WeakHashMap<Class<?>, QName>());
-    private static final Map<QName, Type> qnamesToIdentityMap = new ConcurrentHashMap<>();
-
-    private static final ConcurrentMap<Type, ChoiceCaseNode> caseTypeToCaseSchema = new ConcurrentHashMap<>();
-
-    private static final Map<SchemaPath, Type> pathToType = new ConcurrentHashMap<>();
-    private static final Map<List<QName>, Type> pathToInstantiatedType = new ConcurrentHashMap<>();
-    private static final Map<Type, QName> typeToQname = new ConcurrentHashMap<>();
-    private static final BiMap<Type, AugmentationSchema> typeToAugment = HashBiMap
-            .create(new ConcurrentHashMap<Type, AugmentationSchema>());
-
-    private static final Multimap<Type, Type> augmentableToAugmentations = Multimaps.synchronizedMultimap(HashMultimap
-            .<Type, Type> create());
-    private static final Multimap<Type, Type> choiceToCases = Multimaps.synchronizedMultimap(HashMultimap
-            .<Type, Type> create());
-
-    private final InstanceIdentifierCodec instanceIdentifierCodec = new InstanceIdentifierCodecImpl(this);
-    private final IdentityCompositeCodec identityRefCodec = new IdentityCompositeCodec();
-    private final ClassLoadingStrategy classLoadingStrategy;
-    private final AbstractTransformerGenerator generator;
-    private final SchemaLock lock;
-
-    // FIXME: how is this protected?
-    private SchemaContext currentSchema;
-
-    LazyGeneratedCodecRegistry(final SchemaLock lock, final AbstractTransformerGenerator generator,
-            final ClassLoadingStrategy classLoadingStrategy) {
-        this.lock = Preconditions.checkNotNull(lock);
-        this.classLoadingStrategy = Preconditions.checkNotNull(classLoadingStrategy);
-        this.generator = Preconditions.checkNotNull(generator);
-    }
-
-    public SchemaLock getLock() {
-        return lock;
-    }
-
-    @Override
-    public InstanceIdentifierCodec getInstanceIdentifierCodec() {
-        return instanceIdentifierCodec;
-    }
-
-    @SuppressWarnings("unchecked")
-    @Override
-    public <T extends Augmentation<?>> AugmentationCodecWrapper<T> getCodecForAugmentation(final Class<T> augClass) {
-        AugmentationCodecWrapper<T> codec = null;
-        @SuppressWarnings("rawtypes")
-        AugmentationCodecWrapper potentialCodec = augmentationCodecs.get(augClass);
-        if (potentialCodec != null) {
-            codec = potentialCodec;
-        } else {
-            lock.waitForSchema(augClass);
-            Class<? extends BindingCodec<Map<QName, Object>, Object>> augmentRawCodec = generator
-                    .augmentationTransformerFor(augClass);
-
-            BindingCodec<Map<QName, Object>, Object> rawCodec = newInstanceOf(augmentRawCodec);
-            codec = new AugmentationCodecWrapper<T>(rawCodec, augClass);
-            augmentationCodecs.put(augClass, codec);
-        }
-
-        final Class<? extends Augmentable<?>> objectSupertype;
-        try {
-            objectSupertype = BindingReflections.findAugmentationTarget(augClass);
-        } catch (Exception e) {
-            LOG.warn("Failed to find target for augmentation {}, ignoring it", augClass, e);
-            return codec;
-        }
-
-        if (objectSupertype == null) {
-            LOG.warn("Augmentation target for {} not found, ignoring it", augClass);
-            return codec;
-        }
-
-        getAugmentableCodec(objectSupertype).addImplementation(codec);
-        return codec;
-    }
-
-    @SuppressWarnings("unchecked")
-    @Override
-    public QName getQNameForAugmentation(final Class<?> cls) {
-        Preconditions.checkArgument(Augmentation.class.isAssignableFrom(cls));
-        return getCodecForAugmentation((Class<? extends Augmentation<?>>) cls).getAugmentationQName();
-    }
-
-    @Override
-    public Class<?> getClassForPath(final List<QName> names) {
-        DataSchemaNode node = getSchemaNode(names);
-        Preconditions.checkArgument(node != null, "Path %s points to invalid schema location", names);
-        SchemaNode originalDefinition = SchemaNodeUtils.getRootOriginalIfPossible(node);
-        if (originalDefinition instanceof DataSchemaNode) {
-            node = (DataSchemaNode) originalDefinition;
-        }
-        final SchemaPath path = node.getPath();
-        final Type t = pathToType.get(path);
-
-        final Type type;
-        if (t != null) {
-            type = new ReferencedTypeImpl(t.getPackageName(), t.getName());
-        } else {
-            type = pathToInstantiatedType.get(names);
-            Preconditions.checkState(type != null, "Failed to lookup instantiated type for path %s", path);
-        }
-
-        try {
-            return classLoadingStrategy.loadClass(type);
-        } catch (ClassNotFoundException e) {
-            throw new IllegalStateException(String.format("Could not find loaded class for path: %s and type: %s",
-                    path, type.getFullyQualifiedName()));
-        }
-    }
-
-    @Override
-    public void putPathToClass(final List<QName> names, final Class<?> cls) {
-        final Type reference = Types.typeForClass(cls);
-        pathToInstantiatedType.put(names, reference);
-        LOG.trace("Path {} attached to class {} reference {}", names, cls, reference);
-        bindingClassEncountered(cls);
-    }
-
-    @Override
-    public IdentifierCodec<?> getKeyCodecForPath(final List<QName> names) {
-        @SuppressWarnings("unchecked")
-        Class<? extends Identifiable<?>> cls = (Class<? extends Identifiable<?>>) getClassForPath(names);
-        return getIdentifierCodecForIdentifiable(cls);
-    }
-
-    @Override
-    public <T extends DataContainer> DataContainerCodec<T> getCodecForDataObject(final Class<T> type) {
-        @SuppressWarnings("unchecked")
-        DataContainerCodec<T> ret = (DataContainerCodec<T>) containerCodecs.get(type);
-        if (ret != null) {
-            return ret;
-        }
-        Class<? extends BindingCodec<Map<QName, Object>, Object>> newType = generator.transformerFor(type);
-        BindingCodec<Map<QName, Object>, Object> rawCodec = newInstanceOf(newType);
-        DataContainerCodecImpl<T> newWrapper = new DataContainerCodecImpl<>(rawCodec);
-        containerCodecs.put(type, newWrapper);
-        return newWrapper;
-    }
-
-    @Override
-    @SuppressWarnings("rawtypes")
-    public void bindingClassEncountered(final Class cls) {
-        if (Augmentation.class.isAssignableFrom(cls)) {
-            // Intentionally NOOP
-        } else if (DataObject.class.isAssignableFrom(cls)) {
-            getCodecForDataObject((Class<? extends DataObject>) cls);
-        }
-    }
-
-    @Override
-    public void onClassProcessed(final Class<?> cls) {
-
-    }
-
-    private DataSchemaNode getSchemaNode(final List<QName> path) {
-        QName firstNode = path.get(0);
-        DataNodeContainer previous = currentSchema.findModuleByNamespaceAndRevision(firstNode.getNamespace(),
-                firstNode.getRevision());
-        Preconditions.checkArgument(previous != null, "Failed to find module %s for path %s", firstNode, path);
-
-        Iterator<QName> iterator = path.iterator();
-        while (iterator.hasNext()) {
-            QName arg = iterator.next();
-            DataSchemaNode currentNode = previous.getDataChildByName(arg);
-            if (currentNode == null) {
-                currentNode = searchInChoices(previous, arg);
-            }
-            if (currentNode instanceof DataNodeContainer) {
-                previous = (DataNodeContainer) currentNode;
-            } else if (currentNode instanceof LeafSchemaNode || currentNode instanceof LeafListSchemaNode) {
-                Preconditions.checkState(!iterator.hasNext(), "Path tries to nest inside leaf node.");
-                return currentNode;
-            }
-        }
-        return (DataSchemaNode) previous;
-    }
-
-    private DataSchemaNode searchInChoices(final DataNodeContainer node, final QName arg) {
-        for (DataSchemaNode child : node.getChildNodes()) {
-            if (child instanceof ChoiceNode) {
-                ChoiceNode choiceNode = (ChoiceNode) child;
-                DataSchemaNode potential = searchInCases(choiceNode, arg);
-                if (potential != null) {
-                    return potential;
-                }
-            }
-        }
-        return null;
-    }
-
-    private DataSchemaNode searchInCases(final ChoiceNode choiceNode, final QName arg) {
-        Set<ChoiceCaseNode> cases = choiceNode.getCases();
-        for (ChoiceCaseNode caseNode : cases) {
-            DataSchemaNode node = caseNode.getDataChildByName(arg);
-            if (node != null) {
-                return node;
-            }
-        }
-        return null;
-    }
-
-    private static <T> T newInstanceOf(final Class<?> cls) {
-        try {
-            @SuppressWarnings("unchecked")
-            T ret = (T) cls.newInstance();
-            return ret;
-        } catch (InstantiationException e) {
-            LOG.error("Failed to instantiate codec {}", cls.getSimpleName(), e);
-            throw new IllegalStateException(String.format("Failed to instantiate codec %s", cls), e);
-        } catch (IllegalAccessException e) {
-            LOG.debug(
-                    "Run-time consistency issue: constructor for {} is not available. This indicates either a code generation bug or a misconfiguration of JVM.",
-                    cls.getSimpleName(), e);
-            throw new IllegalStateException(String.format("Cannot access contructor of %s", cls), e);
-        }
-    }
-
-    @SuppressWarnings("unchecked")
-    @Override
-    public IdentifierCodec<?> getIdentifierCodecForIdentifiable(final Class identifiable) {
-
-        Class identifier = ClassLoaderUtils.findFirstGenericArgument(identifiable,
-                org.opendaylight.yangtools.yang.binding.Identifiable.class);
-        IdentifierCodec<?> obj = identifierCodecs.get(identifier);
-        if (obj != null) {
-            return obj;
-        }
-        return createIdentifierCodec(identifier, identifiable);
-    }
-
-    @Override
-    public <T extends Identifier<?>> IdentifierCodec<T> getCodecForIdentifier(final Class<T> identifier) {
-        @SuppressWarnings("unchecked")
-        IdentifierCodec<T> obj = (IdentifierCodec<T>) identifierCodecs.get(identifier);
-        if (obj != null) {
-            return obj;
-        }
-        Class<? extends Identifiable<T>> identifiable = ClassLoaderUtils.findFirstGenericArgument(identifier,
-                Identifier.class);
-        return createIdentifierCodec(identifier, identifiable);
-    }
-
-    private <T extends Identifier<?>> IdentifierCodec<T> createIdentifierCodec(final Class<T> identifier,
-            final Class<? extends Identifiable<T>> identifiable) {
-        Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
-                .keyTransformerForIdentifiable(identifiable);
-        BindingCodec<Map<QName, Object>, Object> newInstance;
-        newInstance = newInstanceOf(newCodec);
-        IdentifierCodecImpl<T> newWrapper = new IdentifierCodecImpl<>(newInstance);
-        identifierCodecs.put(identifier, newWrapper);
-        return newWrapper;
-    }
-
-    @Override
-    public IdentityCodec<?> getIdentityCodec() {
-        return identityRefCodec;
-    }
-
-    @SuppressWarnings("unchecked")
-    @Override
-    public <T extends BaseIdentity> IdentityCodec<T> getCodecForIdentity(final Class<T> codec) {
-        bindingClassEncountered(codec);
-        return identityRefCodec;
-    }
-
-    @Override
-    public void onCodecCreated(final Class<?> cls) {
-        CodecMapping.setIdentifierCodec(cls, instanceIdentifierCodec);
-        CodecMapping.setIdentityRefCodec(cls, identityRefCodec);
-    }
-
-    @SuppressWarnings("rawtypes")
-    public ChoiceCaseCodecImpl getCaseCodecFor(final Class caseClass) {
-        ChoiceCaseCodecImpl<?> potential = caseCodecs.get(caseClass);
-        if (potential != null) {
-            return potential;
-        }
-        ConcreteType typeref = Types.typeForClass(caseClass);
-        ChoiceCaseNode caseSchema = caseTypeToCaseSchema.get(typeref);
-
-        Preconditions.checkState(caseSchema != null, "Case schema is not available for %s", caseClass.getName());
-        Class<? extends BindingCodec> newCodec = generator.caseCodecFor(caseClass, caseSchema);
-        BindingCodec newInstance = newInstanceOf(newCodec);
-        @SuppressWarnings("unchecked")
-        ChoiceCaseCodecImpl caseCodec = new ChoiceCaseCodecImpl(caseClass, caseSchema, newInstance);
-        caseCodecs.put(caseClass, caseCodec);
-        return caseCodec;
-    }
-
-    public void onModuleContextAdded(final SchemaContext schemaContext, final Module module, final ModuleContext context) {
-        pathToType.putAll(context.getChildNodes());
-
-        BiMap<Type, AugmentationSchema> bimap = context.getTypeToAugmentation();
-        for (Map.Entry<Type, AugmentationSchema> entry : bimap.entrySet()) {
-            Type key = entry.getKey();
-            AugmentationSchema value = entry.getValue();
-            Collection<DataSchemaNode> augmentedNodes = value.getChildNodes();
-            if (augmentedNodes != null && !augmentedNodes.isEmpty()) {
-                typeToAugment.put(key, value);
-            }
-        }
-
-        qnamesToIdentityMap.putAll(context.getIdentities());
-        for (Entry<QName, GeneratedTOBuilder> identity : context.getIdentities().entrySet()) {
-            typeToQname.put(
-                    new ReferencedTypeImpl(identity.getValue().getPackageName(), identity.getValue().getName()),
-                    identity.getKey());
-        }
-
-        synchronized (augmentableToAugmentations) {
-            augmentableToAugmentations.putAll(context.getAugmentableToAugmentations());
-        }
-        synchronized (choiceToCases) {
-            choiceToCases.putAll(context.getChoiceToCases());
-        }
-        synchronized (caseTypeToCaseSchema) {
-            caseTypeToCaseSchema.putAll(context.getCaseTypeToSchemas());
-        }
-    }
-
-    @Override
-    public void onGlobalContextUpdated(final SchemaContext context) {
-        currentSchema = context;
-        resetDispatchCodecsAdaptation();
-
-    }
-
-    /**
-     * Resets / clears adaptation for all schema context sensitive codecs in
-     * order for them to adapt to new schema context and maybe newly discovered
-     * augmentations This ensure correct behaviour for augmentations and
-     * augmented cases for preexisting codecs, which augmentations were
-     * introduced at later point in time.
-     *
-     * This also makes removed augmentations unavailable.
-     */
-    private void resetDispatchCodecsAdaptation() {
-        synchronized (dispatchCodecs) {
-            for (LocationAwareDispatchCodec<?> codec : dispatchCodecs.values()) {
-                codec.resetCodec(this);
-            }
-        }
-    }
-
-    @SuppressWarnings({ "unchecked", "rawtypes" })
-    @Override
-    public void onChoiceCodecCreated(final Class<?> choiceClass,
-            final Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec, final ChoiceNode schema) {
-        ChoiceCodec<?> oldCodec = choiceCodecs.get(choiceClass);
-        Preconditions.checkState(oldCodec == null);
-        BindingCodec<Map<QName, Object>, Object> delegate = newInstanceOf(choiceCodec);
-        PublicChoiceCodecImpl<?> newCodec = new PublicChoiceCodecImpl(delegate);
-        DispatchChoiceCodecImpl dispatchCodec = new DispatchChoiceCodecImpl(choiceClass, this);
-        choiceCodecs.put(choiceClass, newCodec);
-        synchronized (dispatchCodecs) {
-            dispatchCodecs.put(choiceClass, dispatchCodec);
-        }
-        CodecMapping.setDispatchCodec(choiceCodec, dispatchCodec);
-    }
-
-    @Override
-    public void onValueCodecCreated(final Class<?> valueClass, final Class<?> valueCodec) {
-    }
-
-    @Override
-    public void onCaseCodecCreated(final Class<?> choiceClass,
-            final Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec) {
-    }
-
-    @Override
-    public void onDataContainerCodecCreated(final Class<?> dataClass,
-            final Class<? extends BindingCodec<?, ?>> dataCodec) {
-        if (Augmentable.class.isAssignableFrom(dataClass)) {
-            AugmentableDispatchCodec augmentableCodec = getAugmentableCodec(dataClass);
-            CodecMapping.setAugmentationCodec(dataCodec, augmentableCodec);
-        }
-    }
-
-    public synchronized AugmentableDispatchCodec getAugmentableCodec(final Class<?> dataClass) {
-        AugmentableDispatchCodec ret = augmentableCodecs.get(dataClass);
-        if (ret != null) {
-            return ret;
-        }
-        ret = new AugmentableDispatchCodec(dataClass, this);
-        augmentableCodecs.put(dataClass, ret);
-        synchronized (dispatchCodecs) {
-            dispatchCodecs.put(dataClass, ret);
-        }
-        ret.tryToLoadImplementations();
-        return ret;
-    }
-
-    private static abstract class IntermediateCodec<T> implements DomCodec<T>,
-            Delegator<BindingCodec<Map<QName, Object>, Object>> {
-
-        private final BindingCodec<Map<QName, Object>, Object> delegate;
-
-        @Override
-        public BindingCodec<Map<QName, Object>, Object> getDelegate() {
-            return delegate;
-        }
-
-        public IntermediateCodec(final BindingCodec<Map<QName, Object>, Object> delegate) {
-            this.delegate = delegate;
-        }
-
-        @Override
-        public Node<?> serialize(final ValueWithQName<T> input) {
-            Map<QName, Object> intermediateOutput = delegate.serialize(input);
-            return IntermediateMapping.toNode(intermediateOutput);
-        }
-
-    }
-
-    private static class IdentifierCodecImpl<T extends Identifier<?>> extends IntermediateCodec<T> implements
-            IdentifierCodec<T> {
-
-        public IdentifierCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
-            super(delegate);
-        }
-
-        @Override
-        public ValueWithQName<T> deserialize(final Node<?> input) {
-            QName qname = input.getNodeType();
-            @SuppressWarnings("unchecked")
-            T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
-            return new ValueWithQName<T>(qname, value);
-        }
-
-        @Override
-        public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
-            QName qname = input.getNodeType();
-            @SuppressWarnings("unchecked")
-            T value = (T) getDelegate().deserialize((Map<QName, Object>) input, bindingIdentifier);
-            return new ValueWithQName<T>(qname, value);
-        }
-
-        @Override
-        public CompositeNode serialize(final ValueWithQName<T> input) {
-            return (CompositeNode) super.serialize(input);
-        }
-    }
-
-    private static class DataContainerCodecImpl<T extends DataContainer> extends IntermediateCodec<T> implements
-            DataContainerCodec<T> {
-
-        public DataContainerCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
-            super(delegate);
-        }
-
-        @Override
-        public ValueWithQName<T> deserialize(final Node<?> input) {
-            if (input == null) {
-                return null;
-            }
-            QName qname = input.getNodeType();
-            @SuppressWarnings("unchecked")
-            T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
-            return new ValueWithQName<T>(qname, value);
-        }
-
-        @Override
-        public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
-            if (input == null) {
-                return null;
-            }
-            QName qname = input.getNodeType();
-            @SuppressWarnings("unchecked")
-            T value = (T) getDelegate().deserialize((Map<QName, Object>) input, bindingIdentifier);
-            return new ValueWithQName<T>(qname, value);
-        }
-
-        @Override
-        public CompositeNode serialize(final ValueWithQName<T> input) {
-            return (CompositeNode) super.serialize(input);
-        }
-    }
-
-    private interface LocationAwareBindingCodec<P, I> extends BindingCodec<P, I> {
-
-        boolean isApplicable(InstanceIdentifier<?> parentPath, CompositeNode data);
-
-        public Class<?> getDataType();
-
-    }
-
-    @SuppressWarnings("rawtypes")
-    private static abstract class LocationAwareDispatchCodec<T extends LocationAwareBindingCodec> implements
-            BindingCodec {
-
-        private final Map<Class, T> implementations = Collections.synchronizedMap(new WeakHashMap<Class, T>());
-        private final Set<InstanceIdentifier<?>> adaptedForPaths = new HashSet<>();
-        private LazyGeneratedCodecRegistry registry;
-
-        protected LocationAwareDispatchCodec(final LazyGeneratedCodecRegistry registry) {
-            this.registry = registry;
-        }
-
-        protected Map<Class, T> getImplementations() {
-            return implementations;
-        }
-
-        /**
-         * Resets codec adaptation based on location and schema context.
-         *
-         * This is required if new cases / augmentations were introduced or
-         * removed and first use of codec is triggered by invocation from DOM to
-         * Java, so the implementations may change and this may require loading
-         * of new codecs and/or removal of existing ones.
-         *
-         */
-        public synchronized void resetCodec(final LazyGeneratedCodecRegistry currentRegistry) {
-            registry = currentRegistry;
-            adaptedForPaths.clear();
-            resetAdaptationImpl();
-        }
-
-        protected void resetAdaptationImpl() {
-            // Intentionally NOOP, subclasses may specify their custom
-            // behaviour.
-        }
-
-        protected final LazyGeneratedCodecRegistry getRegistry() {
-            return registry;
-        }
-
-        protected void addImplementation(final T implementation) {
-            implementations.put(implementation.getDataType(), implementation);
-        }
-
-        @Override
-        public final Object deserialize(final Object input) {
-            throw new UnsupportedOperationException("Invocation of deserialize without Tree location is unsupported");
-        }
-
-        @Override
-        public final Object deserialize(final Object parent, final InstanceIdentifier parentPath) {
-            adaptForPath(parentPath);
-            Preconditions.checkArgument(parent instanceof CompositeNode, "node must be of CompositeNode type.");
-            CompositeNode parentData = (CompositeNode) parent;
-            ArrayList<T> applicable = new ArrayList<>(implementations.size());
-
-            /*
-             * Codecs are filtered to only ones, which are applicable in
-             * supplied parent context.
-             */
-            for (T impl : getImplementations().values()) {
-                @SuppressWarnings("unchecked")
-                boolean codecApplicable = impl.isApplicable(parentPath, parentData);
-                if (codecApplicable) {
-                    applicable.add(impl);
-                }
-            }
-            LOG.trace("{}: Deserializing mixins from {}, Schema Location {}, Applicable Codecs: {}, All Codecs: {}",
-                    this, parent, parentPath, applicable, getImplementations().values());
-
-            /*
-             * In case of none is applicable, we return null. Since there is no
-             * mixin which is applicable in this location.
-             */
-            if (applicable.isEmpty()) {
-                return null;
-            }
-            return deserializeImpl(parentData, parentPath, applicable);
-        }
-
-        protected abstract Object deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> parentPath,
-                Iterable<T> applicableCodecs);
-
-        @Override
-        public Object serialize(final Object input) {
-            Preconditions.checkArgument(input instanceof DataContainer);
-            Class<? extends DataContainer> inputType = ((DataContainer) input).getImplementedInterface();
-            T implementation = implementations.get(inputType);
-            if (implementation == null) {
-                implementation = tryToLoadImplementationImpl(inputType);
-            }
-            return implementation;
-        }
-
-        private T tryToLoadImplementationImpl(final Class<? extends DataContainer> inputType) {
-            T implementation = tryToLoadImplementation(inputType);
-            Preconditions.checkArgument(implementation != null, "Data type %s is not supported.", inputType);
-            addImplementation(implementation);
-            return implementation;
-        }
-
-        protected final synchronized void adaptForPath(final InstanceIdentifier<?> path) {
-            if (adaptedForPaths.contains(path)) {
-                return;
-            }
-            LOG.debug("Adapting mixin codec {} for path {}", this, path);
-            /**
-             * We search in schema context if the use of this location aware
-             * codec (augmentable codec, case codec) makes sense on provided
-             * location (path)
-             *
-             */
-            Optional<DataNodeContainer> contextNode = BindingSchemaContextUtils.findDataNodeContainer(
-                    getRegistry().currentSchema, path);
-            /**
-             * If context node is present, this codec makes sense on provided
-             * location.
-             *
-             */
-            if (contextNode.isPresent()) {
-                synchronized (this) {
-                    /**
-                     *
-                     * We adapt (turn on / off) possible implementations of
-                     * child codecs (augmentations, cases) based on this
-                     * location.
-                     *
-                     *
-                     */
-
-                    adaptForPathImpl(path, contextNode.get());
-                    try {
-                        /**
-                         * We trigger serialization of instance identifier, to
-                         * make sure instance identifier codec is aware of
-                         * combination of this path / augmentation / case
-                         */
-                        getRegistry().getInstanceIdentifierCodec().serialize(path);
-                    } catch (Exception e) {
-                        LOG.warn("Exception during preparation of instance identifier codec for  path {}.", path, e);
-                    }
-                    adaptedForPaths.add(path);
-                }
-            } else {
-                LOG.debug("Context node (parent node) not found for {}", path);
-            }
-        }
-
-        protected abstract T tryToLoadImplementation(Class<? extends DataContainer> inputType);
-
-        protected abstract void tryToLoadImplementations();
-
-        protected abstract void adaptForPathImpl(InstanceIdentifier<?> path, DataNodeContainer ctx);
-    }
-
-    @SuppressWarnings("rawtypes")
-    private static class ChoiceCaseCodecImpl<T extends DataContainer> implements ChoiceCaseCodec<T>, //
-            Delegator<BindingCodec>, LocationAwareBindingCodec<Node<?>, ValueWithQName<T>> {
-        private final BindingCodec delegate;
-        private final ChoiceCaseNode schema;
-        private final Map<InstanceIdentifier<?>, ChoiceCaseNode> instantiatedLocations;
-        private final Class<?> dataType;
-
-        public ChoiceCaseCodecImpl(final Class<?> caseClass, final ChoiceCaseNode caseNode,
-                final BindingCodec newInstance) {
-            this.delegate = newInstance;
-            this.dataType = caseClass;
-            this.schema = caseNode;
-            instantiatedLocations = new HashMap<>();
-        }
-
-        @Override
-        public ValueWithQName<T> deserialize(final Node<?> input) {
-            throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
-        }
-
-        @Override
-        public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
-            if (input == null) {
-                return null;
-            }
-            QName qname = input.getNodeType();
-            synchronized (instantiatedLocations) {
-                ChoiceCaseNode instantiation = instantiatedLocations.get(bindingIdentifier);
-                if (instantiation != null) {
-                    qname = instantiatedLocations.get(bindingIdentifier).getQName();
-                }
-            }
-            @SuppressWarnings("unchecked")
-            T value = (T) getDelegate().deserialize(new SimpleEntry(qname, input), bindingIdentifier);
-            return new ValueWithQName<T>(qname, value);
-        }
-
-        @Override
-        public CompositeNode serialize(final ValueWithQName<T> input) {
-            throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
-        }
-
-        @Override
-        public BindingCodec getDelegate() {
-            return delegate;
-        }
-
-        public ChoiceCaseNode getSchema() {
-            return schema;
-        }
-
-        @Override
-        @Deprecated
-        public boolean isAcceptable(final Node<?> input) {
-            return checkAgainstSchema(schema, input);
-        }
-
-        private static boolean checkAgainstSchema(final ChoiceCaseNode schema, final Node<?> node) {
-            if (node instanceof CompositeNode) {
-                CompositeNode input = (CompositeNode) node;
-                for (Node<?> childNode : input.getValue()) {
-                    QName child = childNode.getNodeType();
-                    if (schema.getDataChildByName(child) != null) {
-                        return true;
-                    }
-                }
-            }
-            return false;
-        }
-
-        @Override
-        public Class<?> getDataType() {
-            return dataType;
-        }
-
-        public void adaptForPath(final InstanceIdentifier<?> augTarget, final ChoiceCaseNode choiceCaseNode) {
-            synchronized (instantiatedLocations) {
-                instantiatedLocations.put(augTarget, choiceCaseNode);
-            }
-        }
-
-        @Override
-        public boolean isApplicable(final InstanceIdentifier path, final CompositeNode input) {
-            ChoiceCaseNode instantiatedSchema = null;
-            synchronized (instantiatedLocations) {
-                instantiatedSchema = instantiatedLocations.get(path);
-            }
-            if (instantiatedSchema == null) {
-                return false;
-            }
-            return checkAgainstSchema(instantiatedSchema, input);
-        }
-
-        protected boolean isAugmenting(final QName choiceName, final QName proposedQName) {
-            if (schema.isAugmenting()) {
-                return true;
-            }
-            // Choice QName
-            QName parentQName = Iterables.get(schema.getPath().getPathTowardsRoot(), 1);
-            if (!parentQName.getNamespace().equals(schema.getQName().getNamespace())) {
-                return true;
-            }
-            if (!parentQName.equals(choiceName)) {
-                // This item is instantiation of choice via uses in other YANG
-                // module
-                if (choiceName.getNamespace().equals(schema.getQName().getNamespace())) {
-                    // Original definition of grouping is in same namespace
-                    // as original definition of case
-                    // so for sure case is introduced via instantiation of
-                    // grouping
-                    return false;
-                }
-                // Since we are still here, that means case has same namespace
-                // as its parent, which is instantiation of grouping
-                // but case namespace is different from parent node
-                // so it is augmentation.
-                return true;
-            }
-            return false;
-        }
-
-        @Override
-        public String toString() {
-            return "ChoiceCaseCodec [case=" + dataType + ", knownLocations=" + instantiatedLocations.keySet() + "]";
-        }
-    }
-
-    private static class PublicChoiceCodecImpl<T> implements ChoiceCodec<T>,
-            Delegator<BindingCodec<Map<QName, Object>, Object>> {
-
-        private final BindingCodec<Map<QName, Object>, Object> delegate;
-
-        public PublicChoiceCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
-            this.delegate = delegate;
-        }
-
-        @Override
-        public ValueWithQName<T> deserialize(final Node<?> input) {
-            throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
-        }
-
-        @Override
-        public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
-            throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
-        }
-
-        @Override
-        public Node<?> serialize(final ValueWithQName<T> input) {
-            throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
-        }
-
-        @Override
-        public BindingCodec<Map<QName, Object>, Object> getDelegate() {
-            return delegate;
-        }
-
-    }
-
-    class DispatchChoiceCodecImpl extends LocationAwareDispatchCodec<ChoiceCaseCodecImpl<?>> {
-        private final Class<?> choiceType;
-        private final QName choiceName;
-
-        private DispatchChoiceCodecImpl(final Class<?> type, final LazyGeneratedCodecRegistry registry) {
-            super(registry);
-            choiceType = type;
-            choiceName = BindingReflections.findQName(type);
-        }
-
-        @Override
-        public Object deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> path,
-                final Iterable<ChoiceCaseCodecImpl<?>> codecs) {
-            ChoiceCaseCodecImpl<?> caseCodec = Iterables.getOnlyElement(codecs);
-            ValueWithQName<?> value = caseCodec.deserialize(input, path);
-            if (value != null) {
-                return value.getValue();
-            }
-            return null;
-        }
-
-        @SuppressWarnings("unchecked")
-        @Override
-        public Object serialize(final Object input) {
-            Preconditions.checkArgument(input instanceof Map.Entry<?, ?>, "Input must be QName, Value");
-            @SuppressWarnings("rawtypes")
-            QName derivedQName = (QName) ((Map.Entry) input).getKey();
-            @SuppressWarnings("rawtypes")
-            Object inputValue = ((Map.Entry) input).getValue();
-            Preconditions.checkArgument(inputValue instanceof DataObject);
-            Class<? extends DataContainer> inputType = ((DataObject) inputValue).getImplementedInterface();
-            ChoiceCaseCodecImpl<?> codec = tryToLoadImplementation(inputType);
-            Preconditions.checkState(codec != null, "Unable to get codec for %s", inputType);
-            if (codec.isAugmenting(choiceName, derivedQName)) {
-                // If choice is augmenting we use QName which defined this
-                // augmentation
-                return codec.getDelegate().serialize(new ValueWithQName<>(codec.getSchema().getQName(), inputValue));
-            }
-            return codec.getDelegate().serialize(input);
-        }
-
-        @SuppressWarnings("rawtypes")
-        protected Optional<ChoiceCaseCodecImpl> tryToLoadImplementation(final Type potential) {
-            try {
-                @SuppressWarnings("unchecked")
-                Class<? extends DataContainer> clazz = (Class<? extends DataContainer>) classLoadingStrategy
-                        .loadClass(potential);
-                ChoiceCaseCodecImpl codec = tryToLoadImplementation(clazz);
-                addImplementation(codec);
-                return Optional.of(codec);
-            } catch (ClassNotFoundException e) {
-                LOG.warn("Failed to find class for choice {}", potential, e);
-            }
-            return Optional.absent();
-        }
-
-        @Override
-        protected ChoiceCaseCodecImpl<?> tryToLoadImplementation(final Class<? extends DataContainer> inputType) {
-            ChoiceCaseCodecImpl<?> codec = getCaseCodecFor(inputType);
-            addImplementation(codec);
-            return codec;
-        }
-
-        @Override
-        protected void tryToLoadImplementations() {
-            Type type = referencedType(choiceType);
-            Collection<Type> potentialCases;
-            synchronized (choiceToCases) {
-                potentialCases = choiceToCases.get(type);
-            }
-            for (Type potential : potentialCases) {
-                try {
-                    tryToLoadImplementation(potential);
-                } catch (CodeGenerationException e) {
-                    LOG.warn("Failed to proactively generate choice code for {}", type, e);
-                }
-            }
-        }
-
-        @Override
-        protected void adaptForPathImpl(final InstanceIdentifier<?> augTarget, final DataNodeContainer ctxNode) {
-            tryToLoadImplementations();
-            Optional<ChoiceNode> newChoice = BindingSchemaContextUtils.findInstantiatedChoice(ctxNode, choiceType);
-            if(!newChoice.isPresent()) {
-                // Choice is nested inside other choice, so we need to look two levels deep.
-                in_choices: for(DataSchemaNode child : ctxNode.getChildNodes()) {
-                    if(child instanceof ChoiceNode) {
-                        Optional<ChoiceNode> potential = findChoiceInChoiceCases((ChoiceNode) child, choiceType);
-                        if(potential.isPresent()) {
-                            newChoice = potential;
-                            break in_choices;
-                        }
-                    }
-                }
-            }
-
-            Preconditions.checkState(newChoice.isPresent(), "BUG: Unable to find instantiated choice node in schema.");
-            for (@SuppressWarnings("rawtypes")
-            Entry<Class, ChoiceCaseCodecImpl<?>> codec : getImplementations().entrySet()) {
-                ChoiceCaseCodecImpl<?> caseCodec = codec.getValue();
-                Optional<ChoiceCaseNode> instantiatedSchema = BindingSchemaContextUtils.findInstantiatedCase(
-                        newChoice.get(), caseCodec.getSchema());
-                if (instantiatedSchema.isPresent()) {
-                    caseCodec.adaptForPath(augTarget, instantiatedSchema.get());
-                }
-            }
-        }
-
-        private Optional<ChoiceNode> findChoiceInChoiceCases(final ChoiceNode choice, final Class<?> choiceType) {
-            for(ChoiceCaseNode caze : choice.getCases()) {
-                Optional<ChoiceNode> potential = BindingSchemaContextUtils.findInstantiatedChoice(caze, choiceType);
-                if(potential.isPresent()) {
-                    return potential;
-                }
-            }
-            return Optional.absent();
-        }
-
-        @Override
-        public String toString() {
-            return "DispatchChoiceCodecImpl [choiceType=" + choiceType + "]";
-        }
-    }
-
-    /**
-     *
-     * Dispatch codec for augmented object, which processes augmentations
-     * <p>
-     * This codec is used from DataObject codec generated using
-     * {@link TransformerGenerator#transformerFor(Class)} and is wired during
-     * {@link LazyGeneratedCodecRegistry#onDataContainerCodecCreated(Class, Class)}.
-     * <p>
-     * Instance of this codec is associated with class of Binding DTO which
-     * represents target for augmentations.
-     *
-     */
-    @SuppressWarnings({ "rawtypes", "unchecked" })
-    static class AugmentableDispatchCodec extends LocationAwareDispatchCodec<AugmentationCodecWrapper> {
-
-        private final Class augmentableType;
-
-        /**
-         * Construct augmetable dispatch codec.
-         *
-         * @param type
-         *            Class representing augmentation target
-         * @param registry
-         *            Registry with which this codec is associated.
-         */
-        public AugmentableDispatchCodec(final Class type, final LazyGeneratedCodecRegistry registry) {
-            super(registry);
-            Preconditions.checkArgument(Augmentable.class.isAssignableFrom(type));
-            augmentableType = type;
-        }
-
-        /**
-         * Serializes object to list of values which needs to be injected into
-         * resulting DOM Node. Injection of data to parent DOM Node is handled
-         * by caller (in this case generated codec).
-         *
-         * TODO: Deprecate use of augmentation codec without instance instance
-         * identifier
-         *
-         * @return list of nodes, which needs to be added to parent node.
-         *
-         */
-        @Override
-        public Object serialize(final Object input) {
-            Preconditions.checkArgument(augmentableType.isInstance(input), "Object %s is not instance of %s ", input,
-                    augmentableType);
-            if (input instanceof Augmentable<?>) {
-                Map<Class<? extends Augmentation<?>>, Augmentation<?>> augmentations = BindingReflections
-                        .getAugmentations((Augmentable<?>) input);
-                return serializeImpl(augmentations);
-            }
-            return null;
-        }
-
-        /**
-         *
-         * Serialization of augmentations, returns list of composite nodes,
-         * which needs to be injected to parent node.
-         *
-         * @param input
-         *            Map of classes to augmentations
-         * @return List of nodes, which should be added to parent node.
-         */
-        private List serializeImpl(final Map<Class<? extends Augmentation<?>>, Augmentation<?>> input) {
-            List ret = new ArrayList<>();
-            for (Entry<Class<? extends Augmentation<?>>, Augmentation<?>> entry : input.entrySet()) {
-                AugmentationCodec codec = getRegistry().getCodecForAugmentation(entry.getKey());
-                CompositeNode node = codec.serialize(new ValueWithQName(null, entry.getValue()));
-                ret.addAll(node.getValue());
-            }
-            return ret;
-        }
-
-        /**
-         *
-         * Deserialization of augmentation which is location aware.
-         *
-         * Note: In case of composite nodes as an input, each codec is invoked
-         * since there is no augmentation identifier and we need to look for
-         * concrete classes. FIXME: Maybe faster variation will be by extending
-         * {@link AugmentationCodecWrapper} to look for particular QNames, which
-         * will filter incoming set of codecs.
-         *
-         *
-         * @param input
-         *            Input representation of data
-         * @param path
-         *            Wildcarded instance identifier representing location of
-         *            augmentation parent in conceptual schema tree
-         * @param codecs
-         *            Set of codecs which are applicable for supplied
-         *            <code>path</code>, selected by caller to be used by
-         *            deserialization
-         *
-         *
-         */
-        @Override
-        public Map<Class, Augmentation> deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> path,
-                final Iterable<AugmentationCodecWrapper> codecs) {
-            LOG.trace("{}: Going to deserialize augmentations from {} in location {}. Available codecs {}", this,
-                    input, path, codecs);
-            Map<Class, Augmentation> ret = new HashMap<>();
-            for (AugmentationCodecWrapper codec : codecs) {
-                // We add Augmentation Identifier to path, in order to
-                // correctly identify children.
-                Class type = codec.getDataType();
-                final InstanceIdentifier augmentPath = path.augmentation(type);
-                ValueWithQName<?> value = codec.deserialize(input, augmentPath);
-                if (value != null && value.getValue() != null) {
-                    ret.put(type, (Augmentation) value.getValue());
-                }
-            }
-            return ret;
-        }
-
-        /**
-         *
-         * Tries to load implementation of concrete augmentation codec for
-         * supplied type
-         *
-         * Loading of codec may fail, because of supplied type may not be
-         * visible by classloaders known by registry. If class was not found
-         * returns {@link Optional#absent()}.
-         *
-         * @param potential
-         *            Augmentation class identifier for which codecs should be
-         *            loaded.
-         * @return Optional with codec for supplied type
-         *
-         */
-        protected Optional<AugmentationCodecWrapper> tryToLoadImplementation(final Type potential) {
-            try {
-                Class<? extends Augmentation<?>> clazz = (Class<? extends Augmentation<?>>) getRegistry().classLoadingStrategy
-                        .loadClass(potential);
-                return Optional.of(tryToLoadImplementation(clazz));
-            } catch (ClassNotFoundException e) {
-                LOG.warn("Failed to find class for augmentation of {}", potential, e);
-            }
-            return Optional.absent();
-        }
-
-        @Override
-        protected AugmentationCodecWrapper tryToLoadImplementation(final Class inputType) {
-            AugmentationCodecWrapper<? extends Augmentation<?>> potentialImpl = getRegistry().getCodecForAugmentation(
-                    inputType);
-            addImplementation(potentialImpl);
-            return potentialImpl;
-        }
-
-        @Override
-        protected void tryToLoadImplementations() {
-            Type type = referencedType(augmentableType);
-            Collection<Type> potentialAugmentations;
-            synchronized (augmentableToAugmentations) {
-                potentialAugmentations = new ArrayList(augmentableToAugmentations.get(type));
-            }
-            for (Type potential : potentialAugmentations) {
-                try {
-                    tryToLoadImplementation(potential);
-                } catch (CodeGenerationException e) {
-                    LOG.warn("Failed to proactively generate augment code for {}", type, e);
-                }
-            }
-        }
-
-        @Override
-        protected void adaptForPathImpl(final InstanceIdentifier<?> augTarget, final DataNodeContainer ctxNode) {
-            if (ctxNode instanceof AugmentationTarget) {
-                Set<AugmentationSchema> availableAugmentations = ((AugmentationTarget) ctxNode)
-                        .getAvailableAugmentations();
-                if (!availableAugmentations.isEmpty()) {
-                    updateAugmentationMapping(augTarget, availableAugmentations);
-                }
-            }
-        }
-
-        /**
-         *
-         * Adapts augmentation codec for specific provider location (target)
-         *
-         * Since augmentation are not forward-referencing and may be discovered
-         * during runtime, we need to adapt {@link AugmentableDispatchCodec},
-         * {@link AugmentationCodecWrapper} and {@link InstanceIdentifierCodec}
-         * for this newly discovered location where augmentation may be used.
-         *
-         * Adaptation consists of:
-         * <ol>
-         * <li>scan of available (valid) augmentations for current location
-         * <li>lookup for Java classes derived from this augmentations
-         * <li>generation of missing codecs
-         * <li>updating Augmentation codecs to work with new location
-         * <li>updating Instance Identifier to work with new location
-         *
-         */
-        private void updateAugmentationMapping(final InstanceIdentifier<?> augTarget,
-                final Set<AugmentationSchema> availableAugmentations) {
-            for (AugmentationSchema aug : availableAugmentations) {
-
-                Type potentialType = getTypeForAugmentation(aug);
-                if (potentialType != null) {
-                    Optional<AugmentationCodecWrapper> potentialImpl = tryToLoadImplementation(potentialType);
-                    if (potentialImpl.isPresent()) {
-                        potentialImpl.get().addApplicableFor(augTarget, aug);
-                        Class augType = potentialImpl.get().getDataType();
-                        InstanceIdentifier augPath = augTarget.augmentation(augType);
-                        try {
-
-                            org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier domPath = getRegistry()
-                                    .getInstanceIdentifierCodec().serialize(augPath);
-                            if (domPath == null) {
-                                LOG.error("Unable to serialize instance identifier for {}", augPath);
-                            }
-                        } catch (Exception e) {
-                            LOG.error("Unable to serialize instance identifiers for {}", augPath, e);
-                        }
-
-                    }
-                } else {
-                    // Omits warning for empty augmentations since they are not
-                    // represented in data
-                    if (!aug.getChildNodes().isEmpty()) {
-                        LOG.warn("Could not find generated type for augmentation {} with children {}", aug,
-                                aug.getChildNodes());
-                    }
-                }
-            }
-        }
-
-        private Type getTypeForAugmentation(final AugmentationSchema aug) {
-            Optional<AugmentationSchema> currentAug = Optional.of(aug);
-            while (currentAug.isPresent()) {
-                Type potentialType = typeToAugment.inverse().get(currentAug.get());
-                if (potentialType != null) {
-                    return potentialType;
-                }
-                currentAug = currentAug.get().getOriginalDefinition();
-            }
-            return null;
-        }
-
-        @Override
-        public String toString() {
-            return "AugmentableDispatchCodec [augmentable=" + augmentableType + "]";
-        }
-
-    }
-
-    @SuppressWarnings("rawtypes")
-    private static class AugmentationCodecWrapper<T extends Augmentation<?>> implements AugmentationCodec<T>,
-            Delegator<BindingCodec>, LocationAwareBindingCodec<Node<?>, ValueWithQName<T>> {
-
-        private final BindingCodec delegate;
-        private final QName augmentationQName;
-        private final Multimap<InstanceIdentifier<?>, QName> validAugmentationTargets;
-        private final Class<?> augmentationType;
-
-        public AugmentationCodecWrapper(final BindingCodec<Map<QName, Object>, Object> rawCodec, final Class<?> dataType) {
-            this.delegate = rawCodec;
-            this.augmentationType = dataType;
-            this.augmentationQName = BindingReflections.findQName(rawCodec.getClass());
-            this.validAugmentationTargets = Multimaps.synchronizedSetMultimap(HashMultimap
-                    .<InstanceIdentifier<?>, QName> create());
-        }
-
-        public void addApplicableFor(final InstanceIdentifier<?> path, final AugmentationSchema aug) {
-            for (DataSchemaNode child : aug.getChildNodes()) {
-                validAugmentationTargets.put(path, child.getQName());
-            }
-        }
-
-        @Override
-        public BindingCodec getDelegate() {
-            return delegate;
-        }
-
-        @Override
-        public CompositeNode serialize(final ValueWithQName<T> input) {
-            @SuppressWarnings("unchecked")
-            List<Map<QName, Object>> rawValues = (List<Map<QName, Object>>) getDelegate().serialize(input);
-            List<Node<?>> serialized = new ArrayList<>(rawValues.size());
-            for (Map<QName, Object> val : rawValues) {
-                serialized.add(IntermediateMapping.toNode(val));
-            }
-            return new CompositeNodeTOImpl(input.getQname(), null, serialized);
-        }
-
-        @Override
-        @SuppressWarnings("unchecked")
-        public ValueWithQName<T> deserialize(final Node<?> input) {
-            Object rawCodecValue = getDelegate().deserialize(input);
-            return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
-        }
-
-        @Override
-        @SuppressWarnings("unchecked")
-        public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
-            Object rawCodecValue = getDelegate().deserialize(input, bindingIdentifier);
-            return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
-        }
-
-        @Override
-        public QName getAugmentationQName() {
-            return augmentationQName;
-        }
-
-        @Override
-        public boolean isAcceptable(final InstanceIdentifier<?> path) {
-            if (path == null) {
-                return false;
-            }
-            return validAugmentationTargets.containsKey(path);
-        }
-
-        @Override
-        public boolean isApplicable(final InstanceIdentifier parentPath, final CompositeNode parentData) {
-            return isAcceptable(parentPath);
-        }
-
-        @Override
-        public Class<?> getDataType() {
-            return augmentationType;
-        }
-
-        @Override
-        public String toString() {
-            return "AugmentationCodecWrapper [augmentation=" + augmentationType + ", knownLocations="
-                    + validAugmentationTargets.keySet() + "]";
-        }
-    }
-
-    @SuppressWarnings("rawtypes")
-    private class IdentityCompositeCodec implements IdentityCodec {
-
-        @Override
-        public Object deserialize(final Object input) {
-            Preconditions.checkArgument(input instanceof QName);
-            return deserialize((QName) input);
-        }
-
-        @Override
-        public Class<?> deserialize(final QName input) {
-            if (input == null) {
-                return null;
-            }
-            Type type = qnamesToIdentityMap.get(input);
-            if (type == null) {
-                String packageName = BindingMapping.getRootPackageName(input);
-                String className = BindingMapping.getClassName(input);
-                type = new ReferencedTypeImpl(packageName, className);
-            }
-            try {
-                final Class<?> cls = classLoadingStrategy.loadClass(type);
-                if (cls != null) {
-                    serialize(cls);
-                    return cls;
-                }
-            } catch (Exception e) {
-                LOG.warn("Identity {} was not deserialized, because of missing class {}", input,
-                        type.getFullyQualifiedName(), e);
-            }
-            return null;
-
-        }
-
-        @Override
-        public Object deserialize(final Object input, final InstanceIdentifier bindingIdentifier) {
-            return deserialize(input);
-        }
-
-        @Override
-        public QName serialize(final Class input) {
-            Preconditions.checkArgument(BaseIdentity.class.isAssignableFrom(input));
-            bindingClassEncountered(input);
-            QName qname = identityQNames.get(input);
-            if (qname != null) {
-                return qname;
-            }
-            qname = BindingReflections.findQName(input);
-            if (qname != null) {
-                identityQNames.put(input, qname);
-            }
-            return qname;
-        }
-
-        @Override
-        public Object serialize(final Object input) {
-            Preconditions.checkArgument(input instanceof Class);
-            return serialize((Class) input);
-        }
-
-    }
-
-    private static final Type referencedType(final Class<?> augmentableType) {
-        return new ReferencedTypeImpl(augmentableType.getPackage().getName(), augmentableType.getSimpleName());
-    }
-
-}
index 8fd13c3cf999807ae8288205505f76a50a139de4..aac2135c7d8d7023e32c1543c151027222e23c58 100644 (file)
@@ -21,6 +21,7 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import org.opendaylight.yangtools.sal.binding.model.api.Type;
+import org.opendaylight.yangtools.sal.binding.model.api.type.builder.EnumBuilder;
 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
 import org.opendaylight.yangtools.yang.common.QName;
@@ -50,6 +51,7 @@ public final class ModuleContext {
     private final BiMap<Type,ChoiceCaseNode> caseTypeToSchema = HashBiMap.create();
 
     private final Multimap<Type, Type> augmentableToAugmentations = HashMultimap.create();
+    private final Map<SchemaPath, Type> innerTypes = new HashMap<>();
 
     List<Type> getGeneratedTypes() {
         List<Type> result = new ArrayList<>();
@@ -215,4 +217,18 @@ public final class ModuleContext {
         typeToSchema.put(type, typedef);
     }
 
+    /**
+     * Adds mapping between schema path and inner enum.
+     *
+     * @param path
+     * @param enumBuilder
+     */
+    void addInnerTypedefType(SchemaPath path, EnumBuilder enumBuilder) {
+        innerTypes.put(path, enumBuilder);
+    }
+
+    public Type getInnerType(SchemaPath path) {
+        return innerTypes.get(path);
+    }
+
 }
diff --git a/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/RuntimeGeneratedMappingServiceImpl.java b/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/RuntimeGeneratedMappingServiceImpl.java
deleted file mode 100644 (file)
index 98a8150..0000000
+++ /dev/null
@@ -1,457 +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.yangtools.sal.binding.generator.impl;
-
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.HashMultimap;
-import com.google.common.collect.Multimap;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.SettableFuture;
-import javassist.ClassPool;
-import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil;
-import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
-import org.opendaylight.yangtools.binding.generator.util.Types;
-import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
-import org.opendaylight.yangtools.sal.binding.generator.util.YangSchemaUtils;
-import org.opendaylight.yangtools.sal.binding.model.api.Type;
-import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
-import org.opendaylight.yangtools.yang.binding.Augmentation;
-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.IdentifiableItem;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
-import org.opendaylight.yangtools.yang.binding.RpcService;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
-import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
-import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
-import org.opendaylight.yangtools.yang.data.impl.codec.AugmentationCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
-import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
-import org.opendaylight.yangtools.yang.data.impl.codec.DataContainerCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
-import org.opendaylight.yangtools.yang.data.impl.codec.InstanceIdentifierCodec;
-import org.opendaylight.yangtools.yang.data.impl.codec.ValueWithQName;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-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.SchemaContextHolder;
-import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
-import org.opendaylight.yangtools.yang.model.api.SchemaNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import javax.annotation.concurrent.GuardedBy;
-import java.net.URI;
-import java.util.AbstractMap.SimpleEntry;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.ExecutionException;
-
-public class RuntimeGeneratedMappingServiceImpl implements BindingIndependentMappingService, SchemaContextListener,
-SchemaLock, AutoCloseable, SchemaContextHolder, TypeResolver {
-
-    private static final Logger LOG = LoggerFactory.getLogger(RuntimeGeneratedMappingServiceImpl.class);
-
-    private final ConcurrentMap<Type, Set<QName>> serviceTypeToRpc = new ConcurrentHashMap<>();
-
-    /**
-     * This is map of types which users are waiting for.
-     */
-    @GuardedBy("this")
-    private final Multimap<Type, SettableFuture<Type>> promisedTypes = HashMultimap.create();
-
-    private final ClassLoadingStrategy classLoadingStrategy;
-
-    private final AbstractTransformerGenerator binding;
-    private final LazyGeneratedCodecRegistry registry;
-    private final ClassPool pool;
-
-    /*
-     * FIXME: updated here, access from AbstractTransformer
-     */
-    private final Map<Type, AugmentationSchema> typeToAugmentation = new ConcurrentHashMap<>();
-    private final ConcurrentMap<Type, GeneratedTypeBuilder> typeToDefinition = new ConcurrentHashMap<>();
-    private final ConcurrentMap<Type, SchemaNode> typeToSchemaNode = new ConcurrentHashMap<>();
-    private final Map<SchemaPath, GeneratedTypeBuilder> pathToType = new ConcurrentHashMap<>();
-
-    // FIXME: need to figure these out
-    private final ConcurrentMap<Type, Type> typeDefinitions = new ConcurrentHashMap<>();
-    private SchemaContext schemaContext;
-
-    public RuntimeGeneratedMappingServiceImpl(final ClassPool pool) {
-        this(pool, GeneratedClassLoadingStrategy.getTCCLClassLoadingStrategy());
-    }
-
-    public RuntimeGeneratedMappingServiceImpl(final ClassPool pool, final ClassLoadingStrategy strat) {
-        this.pool = Preconditions.checkNotNull(pool);
-        this.classLoadingStrategy = Preconditions.checkNotNull(strat);
-        // FIXME: this escapes constructor
-        binding = new TransformerGenerator(this, pool);
-        registry = new LazyGeneratedCodecRegistry(this, binding, classLoadingStrategy);
-        binding.setListener(registry);
-
-        // if (ctx !== null) {
-        // listenerRegistration = ctx.registerService(SchemaContextListener,
-        // this, new Hashtable<String, String>());
-        // }
-    }
-
-    @Override
-    public synchronized SchemaContext getSchemaContext() {
-        return schemaContext;
-    }
-
-    @Override
-    public synchronized void onGlobalContextUpdated(final SchemaContext context) {
-        this.schemaContext = Preconditions.checkNotNull(context);
-        this.recreateBindingContext(context);
-        this.registry.onGlobalContextUpdated(context);
-    }
-
-    @GuardedBy("this")
-    private void recreateBindingContext(final SchemaContext schemaContext) {
-        BindingGeneratorImpl newBinding = new BindingGeneratorImpl(false);
-        newBinding.generateTypes(schemaContext);
-
-        for (Map.Entry<Module, ModuleContext> entry : newBinding.getModuleContexts().entrySet()) {
-
-            registry.onModuleContextAdded(schemaContext, entry.getKey(), entry.getValue());
-            pathToType.putAll(entry.getValue().getChildNodes());
-            Module module = entry.getKey();
-            ModuleContext context = entry.getValue();
-            updateBindingFor(context.getChildNodes(), schemaContext);
-            updateBindingFor(context.getCases(), schemaContext);
-            String namespace = BindingGeneratorUtil.moduleNamespaceToPackageName(module);
-
-            if (!module.getRpcs().isEmpty()) {
-                Set<QName> rpcs = new HashSet<>();
-                for (RpcDefinition rpc : module.getRpcs()) {
-                    rpcs.add(rpc.getQName());
-                }
-                Type serviceClass = new ReferencedTypeImpl(namespace, BindingMapping.getClassName(module.getName())
-                        + "Service");
-                serviceTypeToRpc.put(serviceClass, rpcs);
-                updatePromisedSchemas(serviceClass);
-            }
-
-            Map<SchemaPath, Type> typedefs = context.getTypedefs();
-            for (Map.Entry<SchemaPath, Type> typedef : typedefs.entrySet()) {
-                Type value = typedef.getValue();
-                Type typeRef = new ReferencedTypeImpl(value.getPackageName(), value.getName());
-                typeDefinitions.put(typeRef, value);
-                TypeDefinition<?> schemaNode = YangSchemaUtils.findTypeDefinition(schemaContext, typedef.getKey());
-                if (schemaNode != null) {
-
-                    typeToSchemaNode.put(typeRef, schemaNode);
-                } else {
-                    LOG.error("Type definition for {} is not available", value);
-                }
-            }
-            List<GeneratedTypeBuilder> augmentations = context.getAugmentations();
-            for (GeneratedTypeBuilder augmentation : augmentations) {
-                typeToDefinition.put(augmentation, augmentation);
-            }
-            typeToAugmentation.putAll(context.getTypeToAugmentation());
-            for (GeneratedTypeBuilder augmentation : augmentations) {
-                updatePromisedSchemas(augmentation);
-            }
-        }
-    }
-
-    @Override
-    public CompositeNode toDataDom(final DataObject data) {
-        return toCompositeNodeImpl(data);
-    }
-
-    @Override
-    public Entry<YangInstanceIdentifier, CompositeNode> toDataDom(
-            final Entry<org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject>, DataObject> entry) {
-        try {
-            org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier key = toDataDom(entry.getKey());
-            CompositeNode data;
-            if (Augmentation.class.isAssignableFrom(entry.getKey().getTargetType())) {
-                data = toCompositeNodeImplAugument(key, entry.getValue());
-            } else {
-                data = toCompositeNodeImpl(key, entry.getValue());
-            }
-            return new SimpleEntry<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, CompositeNode>(key,
-                    data);
-
-        } catch (Exception e) {
-            LOG.error("Error during serialization for {}.", entry.getKey(), e);
-            throw e;
-        }
-    }
-
-    private CompositeNode toCompositeNodeImpl(final DataObject object) {
-        Class<? extends DataContainer> cls = object.getImplementedInterface();
-        waitForSchema(cls);
-        DataContainerCodec<DataObject> codec = (DataContainerCodec<DataObject>) registry.getCodecForDataObject(cls);
-        return codec.serialize(new ValueWithQName<DataObject>(null, object));
-    }
-
-    private CompositeNode toCompositeNodeImpl(final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier identifier,
-            final DataObject object) {
-        PathArgument last = identifier.getLastPathArgument();
-        Class<? extends DataContainer> cls = object.getImplementedInterface();
-        waitForSchema(cls);
-        DataContainerCodec<DataObject> codec = (DataContainerCodec<DataObject>) registry.getCodecForDataObject(cls);
-        return codec.serialize(new ValueWithQName<DataObject>(last.getNodeType(), object));
-    }
-
-    private CompositeNode toCompositeNodeImplAugument(
-            final org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier identifier, final DataObject object) {
-
-        // val cls = object.implementedInterface;
-        // waitForSchema(cls);
-        org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument last = identifier.getLastPathArgument();
-        AugmentationCodec codec = registry.getCodecForAugmentation((Class) object.getImplementedInterface());
-        CompositeNode ret = codec.serialize(new ValueWithQName<DataObject>(last.getNodeType(), object));
-        if (last instanceof NodeIdentifierWithPredicates) {
-            NodeIdentifierWithPredicates predicates = (NodeIdentifierWithPredicates) last;
-            List<Node<?>> newNodes = new ArrayList<Node<?>>(predicates.getKeyValues().size());
-            for (Map.Entry<QName, Object> predicate : predicates.getKeyValues().entrySet()) {
-                newNodes.add(new SimpleNodeTOImpl<Object>(predicate.getKey(), null, predicate.getValue()));
-            }
-            newNodes.addAll(ret.getValue());
-            return new CompositeNodeTOImpl(last.getNodeType(), null, newNodes);
-        }
-        return ret;
-    }
-
-    @Override
-    public void waitForSchema(final Class<?> cls) {
-        final ListenableFuture<Type> f = getSchemaDefinition(cls);
-        if (f != null) {
-            try {
-                f.get();
-            } catch (InterruptedException | ExecutionException e) {
-                LOG.warn("Waiting for schema for class {} failed", cls, e);
-                throw new IllegalStateException(String.format("Failed to get schema for %s", cls), e);
-            }
-            LOG.info("Schema for {} became available, thread unblocked", cls);
-        }
-    }
-
-    @Override
-    public YangInstanceIdentifier toDataDom(
-            final org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject> path) {
-        for (final org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument arg : path.getPathArguments()) {
-            this.waitForSchema(arg.getType());
-        }
-
-        final InstanceIdentifierCodec c = registry.getInstanceIdentifierCodec();
-        Preconditions.checkState(c != null, "InstanceIdentifierCodec not present");
-        return c.serialize(path);
-    }
-
-    @Override
-    public DataObject dataObjectFromDataDom(
-            final org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject> path,
-            final CompositeNode domData) throws DeserializationException {
-        if (domData == null) {
-            return null;
-        }
-
-        try {
-            final Class<? extends DataContainer> container = path.getTargetType();
-            // FIXME: deprecate use without iid
-            final org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject> wildcardedPath = createWildcarded(path);
-
-            final DataContainerCodec<? extends DataContainer> transformer = registry.getCodecForDataObject(container);
-            Preconditions.checkState(transformer != null, "Failed to find codec for type %s", container);
-
-            final ValueWithQName<? extends DataContainer> deserialize = transformer.deserialize(domData, wildcardedPath);
-            if (deserialize == null) {
-                return null;
-            }
-
-            return (DataObject) deserialize.getValue();
-        } catch (Exception e) {
-            LOG.warn("Failed to deserialize path {} data {}", path, domData);
-            throw new DeserializationException("Data deserialization failed", e);
-        }
-    }
-
-    @Override
-    public org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends Object> fromDataDom(final YangInstanceIdentifier entry) throws DeserializationException {
-        try {
-            final InstanceIdentifierCodec c = registry.getInstanceIdentifierCodec();
-            Preconditions.checkState(c != null, "InstanceIdentifierCodec not present");
-            return c.deserialize(entry);
-        } catch (Exception e) {
-            LOG.warn("Failed to deserialize entry {}", entry);
-            throw new DeserializationException("Entry deserialization failed", e);
-        }
-    }
-
-    @Override
-    public CodecRegistry getCodecRegistry() {
-        return this.registry;
-    }
-
-    private void updateBindingFor(final Map<SchemaPath, GeneratedTypeBuilder> map, final SchemaContext module) {
-        for (Map.Entry<SchemaPath, GeneratedTypeBuilder> entry : map.entrySet()) {
-            SchemaNode schemaNode = SchemaContextUtil.findDataSchemaNode(module, entry.getKey());
-
-            // LOG.info("{} : {}",entry.key,entry.value.fullyQualifiedName)
-            Type typeRef = new ReferencedTypeImpl(entry.getValue().getPackageName(), entry.getValue().getName());
-            typeToDefinition.put(typeRef, entry.getValue());
-            if (schemaNode != null) {
-                typeToSchemaNode.put(typeRef, schemaNode);
-                updatePromisedSchemas(entry.getValue());
-            }
-        }
-    }
-
-
-    @Override
-    public Set<QName> getRpcQNamesFor(final Class<? extends RpcService> service) {
-        Set<QName> serviceRef = serviceTypeToRpc.get(new ReferencedTypeImpl(service.getPackage().getName(), service
-                .getSimpleName()));
-        if (serviceRef == null) {
-            waitForSchema(service);
-            serviceRef = serviceTypeToRpc.get(new ReferencedTypeImpl(service.getPackage().getName(), service
-                    .getSimpleName()));
-            }
-        return serviceRef;
-    }
-
-    private ListenableFuture<Type> getSchemaDefinition(final Class<?> cls) {
-        final Type type = Types.typeForClass(cls);
-        synchronized (this) {
-            if (typeToDefinition.containsKey(type)) {
-                return null;
-            }
-
-            LOG.info("Thread is going to wait for schema for: {}", type.getFullyQualifiedName());
-            final SettableFuture<Type> f = SettableFuture.create();
-            promisedTypes.put(type, f);
-            return f;
-        }
-    }
-
-    @GuardedBy("this")
-    private void updatePromisedSchemas(final Type builder) {
-        final Type ref = new ReferencedTypeImpl(builder.getPackageName(), builder.getName());
-        final Collection<SettableFuture<Type>> futures = promisedTypes.get(ref);
-
-        if (futures != null) {
-            for (SettableFuture<Type> future : futures) {
-                future.set(builder);
-            }
-            promisedTypes.removeAll(builder);
-        }
-    }
-
-    @Override
-    public void close() {
-        // Nothing to do
-    }
-
-    @Override
-    public DataContainer dataObjectFromDataDom(final Class<? extends DataContainer> container,
-            final CompositeNode domData) {
-        // FIXME: Add check for valids inputs
-        // which are Notification and Rpc Input / Rpc Output
-
-        org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataContainer> id = org.opendaylight.yangtools.yang.binding.InstanceIdentifier
-                .create((Class) container);
-        Preconditions.checkNotNull(id, "Failed to create path for type %s", container);
-
-        try {
-            return dataObjectFromDataDom(id, domData);
-        } catch (DeserializationException e) {
-            LOG.warn("Conversion of class {} path {} data {} failed", container, id, domData, e);
-            throw new IllegalStateException("Failed to create data object", e);
-        }
-    }
-
-    @Override
-    public synchronized Optional<Class<? extends RpcService>> getRpcServiceClassFor(final String namespace, final String revision) {
-        Module module = null;
-        if (schemaContext != null) {
-            module = schemaContext.findModuleByNamespaceAndRevision(URI.create(namespace), QName.parseRevision(revision));
-        }
-        if (module == null) {
-            return Optional.absent();
-        }
-        try {
-            Optional<Type> rpcTypeName = getRpcServiceType(module);
-            if (rpcTypeName.isPresent()) {
-                Class<?> rpcClass = classLoadingStrategy.loadClass(rpcTypeName.get().getFullyQualifiedName());
-                return Optional.<Class<? extends RpcService>> of((Class<? extends RpcService>) rpcClass);
-            }
-        } catch (Exception e) {
-            LOG.debug("RPC class not present for {},{}", namespace, revision, e);
-        }
-        return Optional.absent();
-    }
-
-    public Optional<Type> getRpcServiceType(final Module module) {
-        String namespace = BindingGeneratorUtil.moduleNamespaceToPackageName(module);
-        if (module.getRpcs().isEmpty()) {
-            return Optional.<Type> absent();
-        }
-        return Optional.<Type> of(new ReferencedTypeImpl(namespace, BindingMapping.getClassName(module.getName())
-                + BindingMapping.RPC_SERVICE_SUFFIX));
-    }
-
-    @SuppressWarnings({ "rawtypes", "unchecked" })
-    private static final org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject> createWildcarded(
-            final org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject> path) {
-
-        LinkedList<org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument> wildcardedArgs = new LinkedList<>();
-        for(org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument pathArg : path.getPathArguments()) {
-            if(pathArg instanceof IdentifiableItem<?,?>) {
-                pathArg = new Item(pathArg.getType());
-            }
-            wildcardedArgs.add(pathArg);
-        }
-        return org.opendaylight.yangtools.yang.binding.InstanceIdentifier.create(wildcardedArgs);
-    }
-
-    @Override
-    public final AugmentationSchema getAugmentation(final Type type) {
-        return typeToAugmentation.get(type);
-    }
-
-    @Override
-    public final GeneratedTypeBuilder getDefinition(final Type type) {
-        return typeToDefinition.get(type);
-    }
-
-    @Override
-    public final SchemaNode getSchemaNode(final Type type) {
-        return typeToSchemaNode.get(type);
-    }
-
-    @Override
-    public final GeneratedTypeBuilder getTypeBuilder(final SchemaPath path) {
-        return pathToType.get(path);
-    }
-}
diff --git a/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/StaticFieldInitializer.java b/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/StaticFieldInitializer.java
deleted file mode 100644 (file)
index 2e29724..0000000
+++ /dev/null
@@ -1,13 +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.yangtools.sal.binding.generator.impl;
-
-public interface StaticFieldInitializer {
-
-    void initializeStaticFields(Class<?> cls);
-}
diff --git a/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/TransformerGenerator.xtend b/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/TransformerGenerator.xtend
deleted file mode 100644 (file)
index 889f8eb..0000000
+++ /dev/null
@@ -1,1707 +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.yangtools.sal.binding.generator.impl
-
-import com.google.common.base.Joiner
-import com.google.common.base.Supplier
-import java.io.File
-import java.security.ProtectionDomain
-import java.util.AbstractMap.SimpleEntry
-import java.util.Collection
-import java.util.Collections
-import java.util.HashMap
-import java.util.HashSet
-import java.util.Iterator
-import java.util.List
-import java.util.Map
-import java.util.Map.Entry
-import java.util.Set
-import java.util.TreeSet
-import javassist.CannotCompileException
-import javassist.ClassPool
-import javassist.CtClass
-import javassist.CtField
-import javassist.CtMethod
-import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl
-import org.opendaylight.yangtools.binding.generator.util.Types
-import org.opendaylight.yangtools.sal.binding.generator.util.CodeGenerationException
-import org.opendaylight.yangtools.sal.binding.generator.util.SourceCodeGenerator
-import org.opendaylight.yangtools.sal.binding.generator.util.SourceCodeGeneratorFactory
-import org.opendaylight.yangtools.sal.binding.generator.util.XtendHelper
-import org.opendaylight.yangtools.sal.binding.model.api.Enumeration
-import org.opendaylight.yangtools.sal.binding.model.api.GeneratedProperty
-import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject
-import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType
-import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType
-import org.opendaylight.yangtools.sal.binding.model.api.Type
-import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder
-import org.opendaylight.yangtools.util.ClassLoaderUtils
-import org.opendaylight.yangtools.yang.binding.Augmentation
-import org.opendaylight.yangtools.yang.binding.BindingCodec
-import org.opendaylight.yangtools.yang.binding.BindingDeserializer
-import org.opendaylight.yangtools.yang.binding.BindingMapping
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier
-import org.opendaylight.yangtools.yang.common.QName
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema
-import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
-import org.opendaylight.yangtools.yang.model.api.DataNodeContainer
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode
-import org.opendaylight.yangtools.yang.model.api.NotificationDefinition
-import org.opendaylight.yangtools.yang.model.api.SchemaNode
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition
-import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition
-import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit
-import org.opendaylight.yangtools.yang.model.api.type.EmptyTypeDefinition
-import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition
-import org.opendaylight.yangtools.yang.model.util.EnumerationType
-import org.opendaylight.yangtools.yang.model.util.ExtendedType
-import org.slf4j.LoggerFactory
-
-import static com.google.common.base.Preconditions.*
-import static javassist.Modifier.*
-import static org.opendaylight.yangtools.sal.binding.generator.impl.CodecMapping.*
-
-import static extension org.opendaylight.yangtools.sal.binding.generator.util.YangSchemaUtils.*
-
-class TransformerGenerator extends AbstractTransformerGenerator {
-    private static val LOG = LoggerFactory.getLogger(TransformerGenerator)
-
-    public static val STRING = Types.typeForClass(String);
-    public static val BOOLEAN = Types.typeForClass(Boolean);
-    public static val INTEGER = Types.typeForClass(Integer);
-    public static val INSTANCE_IDENTIFIER = Types.typeForClass(InstanceIdentifier);
-    //public static val DECIMAL = Types.typeForClass(Decimal);
-    public static val LONG = Types.typeForClass(Long);
-    public static val CLASS_TYPE = Types.typeForClass(Class);
-
-    @Property
-    var File classFileCapturePath;
-
-    val CtClass BINDING_CODEC
-    val CtClass ctQName
-
-    val SourceCodeGeneratorFactory sourceCodeGeneratorFactory = new SourceCodeGeneratorFactory();
-
-    public new(TypeResolver typeResolver, ClassPool pool) {
-        super(typeResolver, pool)
-
-        BINDING_CODEC = BindingCodec.asCtClass;
-        ctQName = QName.asCtClass
-    }
-
-    override transformerForImpl(Class inputType) {
-        return runOnClassLoader(inputType.classLoader) [ |
-            val ret = getGeneratedClass(inputType)
-            if (ret !== null) {
-                listener.onClassProcessed(inputType);
-                return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
-            }
-            val ref = Types.typeForClass(inputType)
-            val node = getSchemaNode(ref)
-            createMapping(inputType, node, null)
-            val typeSpecBuilder = getDefinition(ref)
-            checkState(typeSpecBuilder !== null, "Could not find typedefinition for %s", inputType.name);
-            val typeSpec = typeSpecBuilder.toInstance();
-            val newret = generateTransformerFor(inputType, typeSpec, node);
-            listener.onClassProcessed(inputType);
-            return newret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
-        ]
-    }
-
-    def Class<? extends BindingCodec<Map<QName, Object>, Object>> transformerFor(Class<?> inputType, DataSchemaNode node) {
-        return runOnClassLoader(inputType.classLoader) [ |
-            createMapping(inputType, node, null)
-            val ret = getGeneratedClass(inputType)
-            if (ret !== null) {
-                listener.onClassProcessed(inputType);
-                return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
-            }
-            val ref = Types.typeForClass(inputType)
-            var typeSpecBuilder = getDefinition(ref)
-            if (typeSpecBuilder == null) {
-                typeSpecBuilder = getTypeBuilder(node.path);
-            }
-
-            checkState(typeSpecBuilder !== null, "Could not find TypeDefinition for %s, $s", inputType.name, node);
-            val typeSpec = typeSpecBuilder.toInstance();
-            val newret = generateTransformerFor(inputType, typeSpec, node);
-            listener.onClassProcessed(inputType);
-            return newret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
-        ]
-    }
-
-    override augmentationTransformerForImpl(Class inputType) {
-        return runOnClassLoader(inputType.classLoader) [ |
-
-            val ret = getGeneratedClass(inputType)
-            if (ret !== null) {
-                return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
-            }
-            val ref = Types.typeForClass(inputType)
-            val node = getAugmentation(ref)
-            val typeSpecBuilder = getDefinition(ref)
-            val typeSpec = typeSpecBuilder.toInstance();
-            //mappingForNodes(node.childNodes, typeSpec.allProperties, bindingId)
-            val newret = generateAugmentationTransformerFor(inputType, typeSpec, node);
-            listener.onClassProcessed(inputType);
-            return newret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
-        ]
-    }
-
-    override caseCodecForImpl(Class inputType, ChoiceCaseNode node) {
-        return runOnClassLoader(inputType.classLoader) [ |
-            createMapping(inputType, node, null)
-            val ret = getGeneratedClass(inputType)
-            if (ret !== null) {
-                return ret as Class<? extends BindingCodec<Object, Object>>;
-            }
-            val ref = Types.typeForClass(inputType)
-            val typeSpecBuilder = getDefinition(ref)
-            val typeSpec = typeSpecBuilder.toInstance();
-            val newret = generateCaseCodec(inputType, typeSpec, node);
-            return newret as Class<? extends BindingCodec<Object, Object>>;
-        ]
-    }
-
-    override keyTransformerForIdentifiableImpl(Class parentType) {
-        return runOnClassLoader(parentType.classLoader) [ |
-            val inputName = parentType.name + "Key";
-            val inputType = loadClass(inputName);
-            val ret = getGeneratedClass(inputType)
-            if (ret !== null) {
-                return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
-            }
-            val ref = Types.typeForClass(parentType)
-            val node = getSchemaNode(ref) as ListSchemaNode
-            val typeSpecBuilder = getDefinition(ref)
-            val typeSpec = typeSpecBuilder.identifierDefinition;
-            val newret = generateKeyTransformerFor(inputType, typeSpec, node);
-            return newret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
-        ]
-    }
-
-    private def void createMapping(Class<?> inputType, SchemaNode node, InstanceIdentifier<?> parentId) {
-        var ClassLoader cl = inputType.classLoader
-        if (cl === null) {
-            cl = Thread.currentThread.contextClassLoader
-        }
-
-        val Supplier<?> sup = [ |
-            if (!(node instanceof DataNodeContainer)) {
-                return null
-            }
-            var InstanceIdentifier<?> bindingId = getBindingIdentifierByPath(node.path)
-            if (bindingId != null) {
-                return null
-            }
-            val ref = Types.typeForClass(inputType)
-            var typeSpecBuilder = getDefinition(ref)
-            if (typeSpecBuilder == null) {
-                typeSpecBuilder = getTypeBuilder(node.path);
-            }
-            checkState(typeSpecBuilder !== null, "Could not find type definition for %s, $s", inputType.name, node);
-            val typeSpec = typeSpecBuilder.toInstance();
-            var InstanceIdentifier<?> parent
-            if (parentId == null) {
-                bindingId = InstanceIdentifier.create(inputType as Class)
-                parent = bindingId
-                putPathToBindingIdentifier(node.path, bindingId)
-            } else {
-                parent = putPathToBindingIdentifier(node.path, parentId, inputType)
-            }
-            val Map<String, Type> properties = typeSpec.allProperties
-            if (node instanceof DataNodeContainer) {
-                mappingForNodes((node as DataNodeContainer).childNodes, properties, parent)
-            } else if (node instanceof ChoiceNode) {
-                mappingForNodes((node as ChoiceNode).cases, properties, parent)
-            }
-            return null ]
-        ClassLoaderUtils.withClassLoader(cl, sup)
-    }
-
-    private def void mappingForNodes(Collection<? extends DataSchemaNode> childNodes, Map<String, Type> properties,
-        InstanceIdentifier<?> parent) {
-        for (DataSchemaNode child : childNodes) {
-            val signature = properties.getFor(child)
-            if (signature != null) {
-                val Type childType = signature.value
-                var Class<?> childTypeClass = null;
-                if (child instanceof ListSchemaNode && childType instanceof ParameterizedType) {
-                    childTypeClass = loadClass((childType as ParameterizedType).actualTypeArguments.get(0))
-                } else {
-                    childTypeClass = loadClass(childType)
-                }
-                createMapping(childTypeClass, child, parent)
-            }
-        }
-    }
-
-    def getIdentifierDefinition(GeneratedTypeBuilder builder) {
-        val inst = builder.toInstance
-        val keyMethod = inst.methodDefinitions.findFirst[name == "getKey"]
-        return keyMethod.returnType as GeneratedTransferObject
-    }
-
-    override keyTransformerForIdentifierImpl(Class inputType) {
-        return runOnClassLoader(inputType.classLoader) [ |
-            val ret = getGeneratedClass(inputType)
-            if (ret !== null) {
-                return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
-            }
-            val ref = Types.typeForClass(inputType)
-            val node = getSchemaNode(ref) as ListSchemaNode
-            val typeSpecBuilder = getDefinition(ref)
-            val typeSpec = typeSpecBuilder.toInstance();
-            val newret = generateKeyTransformerFor(inputType, typeSpec, node);
-            return newret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
-        ]
-    }
-
-    private def Class<?> keyTransformerFor(Class<?> inputType, GeneratedType type, ListSchemaNode schema) {
-        return runOnClassLoader(inputType.classLoader) [ |
-            val transformer = getGeneratedClass(inputType)
-            if (transformer != null) {
-                return transformer;
-            }
-            val newret = generateKeyTransformerFor(inputType, type, schema);
-            return newret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
-        ]
-    }
-
-    private def Class<?> getGeneratedClass(Class<? extends Object> cls) {
-
-        try {
-            return loadClass(cls.codecClassName)
-        } catch (ClassNotFoundException e) {
-            return null;
-        }
-    }
-
-    private def Class<?> keyTransformer(GeneratedType type, ListSchemaNode node) {
-        val cls = loadClass(type.resolvedName + "Key");
-        keyTransformerFor(cls, type, node);
-    }
-
-    private def serializer(Type type, DataSchemaNode node) {
-        val cls = loadClass(type.resolvedName);
-        transformerFor(cls, node);
-    }
-
-    private def Class<?> valueSerializer(GeneratedTransferObject type, TypeDefinition<?> typeDefinition) {
-        val cls = loadClass(type.resolvedName);
-        val transformer = cls.generatedClass;
-        if (transformer !== null) {
-            return transformer;
-        }
-        var baseType = typeDefinition;
-        while (baseType.baseType != null) {
-            baseType = baseType.baseType;
-        }
-        val finalType = baseType;
-        return runOnClassLoader(cls.classLoader) [ |
-            val valueTransformer = generateValueTransformer(cls, type, finalType);
-            return valueTransformer;
-        ]
-    }
-
-    private def Class<?> valueSerializer(Enumeration type, TypeDefinition<?> typeDefinition) {
-        val cls = loadClass(type.resolvedName);
-        val transformer = cls.generatedClass;
-        if (transformer !== null) {
-            return transformer;
-        }
-
-        return runOnClassLoader(cls.classLoader) [ |
-            val valueTransformer = generateValueTransformer(cls, type, typeDefinition);
-            return valueTransformer;
-        ]
-    }
-
-    private def generateKeyTransformerFor(Class<? extends Object> inputType, GeneratedType typeSpec, ListSchemaNode node) {
-        try {
-
-            val SourceCodeGenerator sourceGenerator = sourceCodeGeneratorFactory.getInstance( null );
-
-            //log.info("Generating DOM Codec for {} with {}", inputType, inputType.classLoader)
-            val properties = typeSpec.allProperties;
-            val ctCls = createClass(inputType.codecClassName) [
-                //staticField(Map,"AUGMENTATION_SERIALIZERS");
-                staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec, sourceGenerator)
-                staticField(it, IDENTITYREF_CODEC, BindingCodec, sourceGenerator)
-                staticQNameField(node.QName, sourceGenerator);
-                implementsType(BINDING_CODEC)
-                method(Object, "toDomStatic", #[QName, Object]) [
-                    modifiers = PUBLIC + FINAL + STATIC
-                    val body = '''
-                        {
-                            Â«QName.name» _resultName;
-                            if($1 != null) {
-                                _resultName = Â«QName.name».create($1,QNAME.getLocalName());
-                            } else {
-                                _resultName = QNAME;
-                            }
-                            java.util.List _childNodes = new java.util.ArrayList();
-                            Â«inputType.resolvedName» value = («inputType.name») $2;
-                            Â«FOR key : node.keyDefinition»
-                                Â«val propertyName = key.getterName»
-                                Â«val keyDef = node.getDataChildByName(key)»
-                                Â«val property = properties.get(propertyName)»
-                                Â«serializeProperty(keyDef, property, propertyName)»;
-                            Â«ENDFOR»
-                            return ($r) java.util.Collections.singletonMap(_resultName,_childNodes);
-                        }
-                    '''
-                    setBodyChecked(body, sourceGenerator)
-                ]
-                method(Object, "fromDomStatic", #[QName, Object]) [
-                    modifiers = PUBLIC + FINAL + STATIC
-                    val body = '''
-                        {
-                            if($2 == null){
-                                return  null;
-                            }
-                            Â«QName.name» _localQName = $1;
-                            java.util.Map _compositeNode = (java.util.Map) $2;
-                            boolean _is_empty = true;
-                            Â«FOR key : node.keyDefinition»
-                                Â«val propertyName = key.getterName»
-                                Â«val keyDef = node.getDataChildByName(key)»
-                                Â«val property = properties.get(propertyName)»
-                                Â«deserializeProperty(keyDef, property, propertyName)»;
-                            Â«ENDFOR»
-                            Â«inputType.resolvedName» _value = new Â«inputType.name»(«node.keyDefinition.
-                            keyConstructorList»);
-                            return _value;
-                        }
-                    '''
-                    setBodyChecked(body, sourceGenerator)
-                ]
-                method(Object, "serialize", Object) [
-                    val body = '''
-                        {
-                            java.util.Map.Entry _input =  (java.util.Map.Entry) $1;
-                            Â«QName.name» _localQName = («QName.name») _input.getKey();
-                            Â«inputType.name» _keyValue = («inputType.name») _input.getValue();
-                            return toDomStatic(_localQName,_keyValue);
-                        }
-                    '''
-                    setBodyChecked(body, sourceGenerator)
-                ]
-                method(Object, "deserialize", Object) [
-                    val body = '''
-                        {
-                            Â«QName.name» _qname = QNAME;
-                            if($1 instanceof java.util.Map.Entry) {
-                                _qname = («QName.name») ((java.util.Map.Entry) $1).getKey();
-                            }
-                            return fromDomStatic(_qname,$1);
-                        }
-                    '''
-                    setBodyChecked(body, sourceGenerator)
-                ]
-            ]
-            val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain)
-            sourceGenerator.outputGeneratedSource( ctCls )
-            LOG.debug("DOM Codec for {} was generated {}", inputType, ret)
-            return ret as Class<? extends BindingCodec<Map<QName,Object>, ?>>;
-        } catch (Exception e) {
-            processException(inputType, e);
-            return null;
-        }
-    }
-
-    private def Class<? extends BindingCodec<Object, Object>> generateCaseCodec(Class<?> inputType, GeneratedType type,
-        ChoiceCaseNode node) {
-        try {
-            val SourceCodeGenerator sourceGenerator = sourceCodeGeneratorFactory.getInstance( null );
-
-            //log.info("Generating DOM Codec for {} with {}, TCCL is: {}", inputType, inputType.classLoader,Thread.currentThread.contextClassLoader)
-            val ctCls = createClass(type.codecClassName) [
-                //staticField(Map,"AUGMENTATION_SERIALIZERS");
-                implementsType(BINDING_CODEC)
-                staticQNameField(node.QName, sourceGenerator);
-                staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec, sourceGenerator)
-                staticField(it, AUGMENTATION_CODEC, BindingCodec, sourceGenerator)
-                staticField(it, IDENTITYREF_CODEC, BindingCodec, sourceGenerator)
-                method(Object, "toDomStatic", #[QName, Object]) [
-                    modifiers = PUBLIC + FINAL + STATIC
-                    val body = '''
-                        {
-                            Â«QName.name» _resultName = Â«QName.name».create($1,QNAME.getLocalName());
-                            java.util.List _childNodes = new java.util.ArrayList();
-                            Â«type.resolvedName» value = («type.resolvedName») $2;
-                            Â«transformDataContainerBody(type, type.allProperties, node)»
-                            return ($r) _childNodes;
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator)
-                ]
-                method(Object, "serialize", Object) [
-                    val body = '''
-                        {
-                            java.util.Map.Entry _input = (java.util.Map.Entry) $1;
-                            Â«QName.name» _localName = QNAME;
-                            if(_input.getKey() != null) {
-                                _localName = («QName.name») _input.getKey();
-                            }
-                            return toDomStatic(_localName,_input.getValue());
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator)
-                ]
-                method(Object, "fromDomStatic", #[QName, Object, InstanceIdentifier]) [
-                    modifiers = PUBLIC + FINAL + STATIC
-                    setBodyChecked( deserializeBody(type, node, getBindingIdentifierByPath(node.path)),
-                                    sourceGenerator )
-                ]
-                method(Object, "deserialize", #[Object, InstanceIdentifier]) [
-                    val body = '''
-                        {
-                            //System.out.println("«type.name»#deserialize: " +$1);
-                            java.util.Map.Entry _input = (java.util.Map.Entry) $1;
-                            return fromDomStatic((«QName.name»)_input.getKey(),_input.getValue(),$2);
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator)
-                ]
-            ]
-
-            val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain)  as Class<? extends BindingCodec<Object, Object>>
-            sourceGenerator.outputGeneratedSource( ctCls )
-            listener?.onDataContainerCodecCreated(inputType, ret);
-            LOG.debug("DOM Codec for {} was generated {}", inputType, ret)
-            return ret;
-        } catch (Exception e) {
-            processException(inputType, e);
-            return null;
-        }
-    }
-
-    private def dispatch  Class<? extends BindingCodec<Map<QName, Object>, Object>> generateTransformerFor(
-        Class<?> inputType, GeneratedType typeSpec, SchemaNode node) {
-        try {
-
-            val SourceCodeGenerator sourceGenerator = sourceCodeGeneratorFactory.getInstance( null );
-
-            //log.info("Generating DOM Codec for {} with {}", inputType, inputType.classLoader)
-            val ctCls = createClass(typeSpec.codecClassName) [
-                //staticField(Map,"AUGMENTATION_SERIALIZERS");
-                staticQNameField(node.QName, sourceGenerator);
-                staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec, sourceGenerator)
-                staticField(it, IDENTITYREF_CODEC, BindingCodec, sourceGenerator)
-                staticField(it, AUGMENTATION_CODEC, BindingCodec, sourceGenerator)
-                implementsType(BINDING_CODEC)
-
-                method(Object, "toDomStatic", #[QName, Object]) [
-                    modifiers = PUBLIC + FINAL + STATIC
-                    setBodyChecked( serializeBodyFacade(typeSpec, node), sourceGenerator )
-                ]
-                method(Object, "serialize", Object) [
-                    val body = '''
-                        {
-                            java.util.Map.Entry _input = (java.util.Map.Entry) $1;
-                            Â«QName.name» _localName = QNAME;
-                            if(_input.getKey() != null) {
-                                _localName = («QName.name») _input.getKey();
-                            }
-                            return toDomStatic(_localName,_input.getValue());
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-
-                method(Object, "fromDomStatic", #[QName, Object, InstanceIdentifier]) [
-                    modifiers = PUBLIC + FINAL + STATIC
-                    setBodyChecked( deserializeBody(typeSpec, node, getBindingIdentifierByPath(node.path)),
-                                    sourceGenerator )
-                ]
-
-                method(Object, "deserialize", #[Object, InstanceIdentifier]) [
-                    val body = '''
-                        {
-                            Â«QName.name» _qname = QNAME;
-                            if($1 instanceof java.util.Map.Entry) {
-                                _qname = («QName.name») ((java.util.Map.Entry) $1).getKey();
-                            }
-                            return fromDomStatic(_qname,$1,$2);
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-            ]
-
-            val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain) as Class<? extends BindingCodec<Map<QName,Object>, Object>>
-
-            sourceGenerator.outputGeneratedSource( ctCls )
-
-            listener?.onDataContainerCodecCreated(inputType, ret);
-            LOG.debug("DOM Codec for {} was generated {}", inputType, ret)
-            return ret;
-        } catch (Exception e) {
-            processException(inputType, e);
-            return null;
-        }
-    }
-
-    private def Class<? extends BindingCodec<Map<QName, Object>, Object>> generateAugmentationTransformerFor(
-        Class<?> inputType, GeneratedType type, AugmentationSchema node) {
-        try {
-
-            val SourceCodeGenerator sourceGenerator = sourceCodeGeneratorFactory.getInstance( null );
-
-            //log.info("Generating DOM Codec for {} with {}", inputType, inputType.classLoader)
-            val properties = type.allProperties
-            val ctCls = createClass(type.codecClassName) [
-                //staticField(Map,"AUGMENTATION_SERIALIZERS");
-                staticQNameField(node.augmentationQName, sourceGenerator);
-                staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec, sourceGenerator)
-                staticField(it, AUGMENTATION_CODEC, BindingCodec, sourceGenerator)
-                staticField(it, IDENTITYREF_CODEC, BindingCodec, sourceGenerator)
-                implementsType(BINDING_CODEC)
-
-                method(Object, "toDomStatic", #[QName, Object]) [
-                    modifiers = PUBLIC + FINAL + STATIC
-                    val body = '''
-                        {
-                            ////System.out.println("Qname " + $1);
-                            ////System.out.println("Value " + $2);
-                            Â«QName.name» _resultName = Â«QName.name».create(QNAME,QNAME.getLocalName());
-                            java.util.List _childNodes = new java.util.ArrayList();
-                            Â«type.resolvedName» value = («type.resolvedName») $2;
-                            Â«FOR child : node.childNodes»
-                                Â«var signature = properties.getFor(child)»
-                                ////System.out.println("«signature.key»" + value.«signature.key»());
-                                Â«serializeProperty(child, signature.value, signature.key)»
-                            Â«ENDFOR»
-                            return ($r) _childNodes;
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-                method(Object, "serialize", Object) [
-                    val body = '''
-                        {
-                            java.util.Map.Entry _input = (java.util.Map.Entry) $1;
-                            Â«QName.name» _localName = QNAME;
-                            if(_input.getKey() != null) {
-                                _localName = («QName.name») _input.getKey();
-                            }
-                            return toDomStatic(_localName,_input.getValue());
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-
-                method(Object, "fromDomStatic", #[QName, Object, InstanceIdentifier]) [
-                    modifiers = PUBLIC + FINAL + STATIC
-                    val body = '''
-                        {
-                            Â«QName.name» _localQName = QNAME;
-
-                            if($2 == null) {
-                            return null;
-                            }
-                            java.util.Map _compositeNode = (java.util.Map) $2;
-                            //System.out.println(_localQName + " " + _compositeNode);
-                            Â«type.builderName» _builder = new Â«type.builderName»();
-                            boolean _is_empty = true;
-                            Â«FOR child : node.childNodes»
-                                Â«val signature = properties.getFor(child)»
-                                Â«deserializeProperty(child, signature.value, signature.key)»
-                                _builder.«signature.key.toSetter»(«signature.key»);
-                            Â«ENDFOR»
-                            if(_is_empty) {
-                            return null;
-                            }
-                            return _builder.build();
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-
-                method(Object, "deserialize", #[Object, InstanceIdentifier]) [
-                    val body = '''
-                        {
-                            return fromDomStatic(QNAME,$1,$2);
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-            ]
-
-            val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain) as Class<? extends BindingCodec<Map<QName,Object>, Object>>
-            sourceGenerator.outputGeneratedSource( ctCls )
-            listener?.onDataContainerCodecCreated(inputType, ret);
-            return ret;
-        } catch (Exception e) {
-            processException(inputType, e);
-            return null;
-        }
-    }
-
-    private def dispatch  Class<? extends BindingCodec<Map<QName, Object>, Object>> generateTransformerFor(
-        Class<?> inputType, GeneratedType typeSpec, ChoiceNode node) {
-        try {
-
-            val SourceCodeGenerator sourceGenerator = sourceCodeGeneratorFactory.getInstance( null );
-
-            //log.info("Generating DOM Codec for {} with {}", inputType, inputType.classLoader)
-            val ctCls = createClass(typeSpec.codecClassName) [
-                //staticField(Map,"AUGMENTATION_SERIALIZERS");
-                //staticQNameField(inputType);
-                staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec, sourceGenerator)
-                staticField(it, IDENTITYREF_CODEC, BindingCodec, sourceGenerator)
-                staticField(it, DISPATCH_CODEC, BindingCodec, sourceGenerator)
-                //staticField(it,QNAME_TO_CASE_MAP,BindingCodec)
-                implementsType(BINDING_CODEC)
-                method(List, "toDomStatic", #[QName, Object]) [
-                    modifiers = PUBLIC + FINAL + STATIC
-                    val body = '''
-                        {
-                            if($2 == null) {
-                                return null;
-                            }
-                            if («DISPATCH_CODEC» == null) {
-                                throw new Â«IllegalStateException.name»("Implementation of codec was not initialized.");
-                            }
-                            java.util.Map.Entry _input = new Â«SimpleEntry.name»($1,$2);
-                            Object _ret =  Â«DISPATCH_CODEC».serialize(_input);
-                            ////System.out.println("«typeSpec.name»#toDomStatic: " + _ret);
-                            return («List.name») _ret;
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-                method(Object, "serialize", Object) [
-                    val body = '''
-                        {
-                            throw new Â«UnsupportedOperationException.name»("Direct invocation not supported.");
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-                method(Object, "fromDomStatic", #[QName, Map, InstanceIdentifier]) [
-                    modifiers = PUBLIC + FINAL + STATIC
-                    val body = '''
-                        {
-                            if («DISPATCH_CODEC» == null) {
-                                throw new Â«IllegalStateException.name»("Implementation of codec was not initialized.");
-                            }
-                            return Â«DISPATCH_CODEC».deserialize($2,$3);
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-                method(Object, "deserialize", #[Object, InstanceIdentifier]) [
-                    val body = '''
-                        {
-                            throw new Â«UnsupportedOperationException.name»("Direct invocation not supported.");
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-            ]
-
-            val rawRet = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain)
-            sourceGenerator.outputGeneratedSource( ctCls )
-            val ret = rawRet as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
-            listener?.onChoiceCodecCreated(inputType, ret, node);
-            LOG.debug("DOM Codec for {} was generated {}", inputType, ret)
-            return ret;
-        } catch (Exception e) {
-            processException(inputType, e);
-            return null;
-        }
-    }
-
-    private def keyConstructorList(List<QName> qnames) {
-        val names = new TreeSet<String>()
-        for (name : qnames) {
-            val fieldName = name.getterName;
-            names.add(fieldName);
-        }
-        return Joiner.on(",").join(names);
-    }
-
-    private def serializeBodyFacade(GeneratedType type, SchemaNode node) {
-        val ret = serializeBody(type, node);
-        return ret;
-    }
-
-    private def String deserializeBody(GeneratedType type, SchemaNode node, InstanceIdentifier<?> bindingId) {
-        val ret = deserializeBodyImpl(type, node, bindingId);
-        return ret;
-    }
-
-    private def deserializeKey(GeneratedType type, ListSchemaNode node) {
-        if (node.keyDefinition != null && !node.keyDefinition.empty) {
-            return '''
-                Â«type.resolvedName»Key getKey = («type.resolvedName»Key) Â«keyTransformer(type, node).canonicalName».fromDomStatic(_localQName,_compositeNode);
-                _builder.setKey(getKey);
-            ''';
-        }
-    }
-
-    private def String deserializeBodyWithAugmentations(GeneratedType type, DataNodeContainer node, InstanceIdentifier<?> bindingId) '''
-        {
-            Â«QName.name» _localQName = Â«QName.name».create($1,QNAME.getLocalName());
-            if($2 == null) {
-                return null;
-            }
-            java.util.Map _compositeNode = (java.util.Map) $2;
-            //System.out.println(_localQName + " " + _compositeNode);
-            Â«type.builderName» _builder = new Â«type.builderName»();
-            Â«deserializeDataNodeContainerBody(type, node, bindingId)»
-            Â«type.deserializeAugmentations»
-            return _builder.build();
-        }
-    '''
-
-    private def dispatch String deserializeBodyImpl(GeneratedType type, SchemaNode node, InstanceIdentifier<?> bindingId) '''
-        {
-            Â«QName.name» _localQName = Â«QName.name».create($1,QNAME.getLocalName());
-
-            if($2 == null) {
-            return null;
-            }
-            java.util.Map _compositeNode = (java.util.Map) $2;
-            Â«type.builderName» _builder = new Â«type.builderName»();
-            return _builder.build();
-        }
-    '''
-
-    private def dispatch String deserializeBodyImpl(GeneratedType type, ListSchemaNode node, InstanceIdentifier<?> bindingId) '''
-        {
-            Â«QName.name» _localQName = Â«QName.name».create($1,QNAME.getLocalName());
-            if($2 == null) {
-                return null;
-            }
-            java.util.Map _compositeNode = (java.util.Map) $2;
-            //System.out.println(_localQName + " " + _compositeNode);
-            Â«type.builderName» _builder = new Â«type.builderName»();
-            Â«deserializeKey(type, node)»
-            Â«deserializeDataNodeContainerBody(type, node, bindingId)»
-            Â«type.deserializeAugmentations»
-            return _builder.build();
-        }
-    '''
-
-    private def dispatch String deserializeBodyImpl(GeneratedType type, ContainerSchemaNode node, InstanceIdentifier<?> bindingId) {
-        return deserializeBodyWithAugmentations(type, node, bindingId);
-    }
-
-    private def dispatch String deserializeBodyImpl(GeneratedType type, NotificationDefinition node, InstanceIdentifier<?> bindingId) {
-        return deserializeBodyWithAugmentations(type, node, bindingId);
-    }
-
-    private def dispatch String deserializeBodyImpl(GeneratedType type, ChoiceCaseNode node, InstanceIdentifier<?> bindingId) {
-        return deserializeBodyWithAugmentations(type, node, bindingId);
-    }
-
-    private def deserializeDataNodeContainerBody(GeneratedType type, DataNodeContainer node, InstanceIdentifier<?> bindingId) {
-        deserializeNodeContainerBodyImpl(type, type.allProperties, node, bindingId);
-    }
-
-    private def deserializeNodeContainerBodyImpl(GeneratedType type, HashMap<String, Type> properties,
-        DataNodeContainer node, InstanceIdentifier<?> bindingId) {
-        val ret = '''
-            boolean _is_empty = true;
-            Â«FOR child : node.childNodes»
-                Â«val signature = properties.getFor(child)»
-                Â«IF signature !== null»
-                    Â«deserializeProperty(child, signature.value, signature.key)»
-                    _builder.«signature.key.toSetter»(«signature.key»);
-                Â«ENDIF»
-            Â«ENDFOR»
-        '''
-        return ret;
-    }
-
-    def deserializeAugmentations(GeneratedType type) '''
-        Â«InstanceIdentifier.resolvedName» iid = $3.builder().child(«type.resolvedName».class).build();
-        java.util.Map _augmentation = (java.util.Map) Â«AUGMENTATION_CODEC».deserialize(_compositeNode,$3);
-        if(_augmentation != null) {
-            Â«Iterator.name» _entries = _augmentation.entrySet().iterator();
-            while(_entries.hasNext()) {
-                java.util.Map.Entry _entry = (java.util.Map.Entry) _entries.next();
-                ////System.out.println("Aug. key:" + _entry.getKey());
-                Class _type = (Class) _entry.getKey();
-                Â«Augmentation.resolvedName» _value = («Augmentation.name») _entry.getValue();
-                if(_value != null) {
-                    _builder.addAugmentation(_type,_value);
-                }
-            }
-        }
-    '''
-
-    private def dispatch CharSequence deserializeProperty(ListSchemaNode schema, ParameterizedType type,
-        String propertyName) '''
-        java.util.List _dom_«propertyName» = _compositeNode.get(«QName.name».create(_localQName,"«schema.QName.
-            localName»"));
-        ////System.out.println("«propertyName»#deCode"+_dom_«propertyName»);
-        java.util.List Â«propertyName» = new java.util.ArrayList();
-        if(_dom_«propertyName» != null) {
-            java.util.List _serialized = new java.util.ArrayList();
-            java.util.Iterator _iterator = _dom_«propertyName».iterator();
-            boolean _hasNext = _iterator.hasNext();
-            while(_hasNext) {
-                Object _listItem = _iterator.next();
-                _is_empty = false;
-                ////System.out.println("  item" + _listItem);
-                Â«val param = type.actualTypeArguments.get(0)»
-                Â«InstanceIdentifier.resolvedName» iid = $3.builder().child(«param.resolvedName».class).build();
-                Object _value = Â«type.actualTypeArguments.get(0).serializer(schema).resolvedName».fromDomStatic(_localQName,_listItem,iid);
-                ////System.out.println("  value" + _value);
-                Â«propertyName».add(_value);
-                _hasNext = _iterator.hasNext();
-            }
-        }
-
-        ////System.out.println(" list" + Â«propertyName»);
-    '''
-
-    private def dispatch CharSequence deserializeProperty(LeafListSchemaNode schema, ParameterizedType type,
-        String propertyName) '''
-        java.util.List _dom_«propertyName» = _compositeNode.get(«QName.name».create(_localQName,"«schema.QName.
-            localName»"));
-        java.util.List Â«propertyName» = new java.util.ArrayList();
-        if(_dom_«propertyName» != null) {
-            java.util.List _serialized = new java.util.ArrayList();
-            java.util.Iterator _iterator = _dom_«propertyName».iterator();
-            boolean _hasNext = _iterator.hasNext();
-            while(_hasNext) {
-                _is_empty = false;
-                Object _listItem = _iterator.next();
-                if(_listItem instanceof java.util.Map.Entry) {
-                    Object _innerValue = ((java.util.Map.Entry) _listItem).getValue();
-                    Object _value = Â«deserializeValue(type.actualTypeArguments.get(0), "_innerValue", schema.type)»;
-                    Â«propertyName».add(_value);
-                }
-                _hasNext = _iterator.hasNext();
-            }
-        }
-    '''
-
-    private def dispatch CharSequence deserializeProperty(LeafSchemaNode schema, Type type, String propertyName) '''
-        java.util.List _dom_«propertyName»_list =
-            _compositeNode.get(«QName.name».create(_localQName,"«schema.QName.localName»"));
-        Â«type.resolvedName» Â«propertyName» = null;
-        if(_dom_«propertyName»_list != null && _dom_«propertyName»_list.size() > 0) {
-            _is_empty = false;
-            java.util.Map.Entry _dom_«propertyName» = (java.util.Map.Entry) _dom_«propertyName»_list.get(0);
-            Object _inner_value = _dom_«propertyName».getValue();
-            Â«propertyName» = Â«deserializeValue(type, "_inner_value", schema.type)»;
-        }
-    '''
-
-    private def dispatch CharSequence deserializeProperty(ContainerSchemaNode schema, Type type,
-        String propertyName) '''
-        java.util.List _dom_«propertyName»_list =
-            _compositeNode.get(«QName.name».create(_localQName,"«schema.QName.localName»"));
-        Â«type.resolvedName» Â«propertyName» = null;
-        if(_dom_«propertyName»_list != null && _dom_«propertyName»_list.size() > 0) {
-            _is_empty = false;
-            java.util.Map _dom_«propertyName» = (java.util.Map) _dom_«propertyName»_list.get(0);
-            Â«InstanceIdentifier.resolvedName» iid = $3.builder().child(«type.resolvedName».class).build();
-            Â«propertyName» =  Â«type.serializer(schema).resolvedName».fromDomStatic(_localQName,_dom_«propertyName»,iid);
-        }
-    '''
-
-    private def dispatch CharSequence deserializeProperty(ChoiceNode schema, Type type, String propertyName) '''
-        Â«type.resolvedName» Â«propertyName» = Â«type.serializer(schema).resolvedName».fromDomStatic(_localQName,_compositeNode,$3);
-        if(«propertyName» != null) {
-            _is_empty = false;
-        }
-    '''
-
-    private def dispatch String deserializeValue(GeneratedTransferObject type, String domParameter,
-        TypeDefinition<?> typeDefinition) '''
-        («type.resolvedName») Â«type.valueSerializer(typeDefinition).resolvedName».fromDomValue(«domParameter»)
-    '''
-
-    private def dispatch String deserializeValue(Enumeration type, String domParameter, TypeDefinition<?> typeDefinition) '''
-        («type.resolvedName») Â«type.valueSerializer(typeDefinition).resolvedName».fromDomValue(«domParameter»)
-    '''
-
-    private def dispatch String deserializeValue(Type type, String domParameter, TypeDefinition<?> typeDef) {
-        if (INSTANCE_IDENTIFIER.equals(type)) {
-            return '''(«InstanceIdentifier.name») Â«INSTANCE_IDENTIFIER_CODEC».deserialize(«domParameter»)'''
-        } else if (CLASS_TYPE.equals(type)) {
-            return '''(«Class.name») Â«IDENTITYREF_CODEC».deserialize(«domParameter»)'''
-        } else if (typeDef!=null && typeDef instanceof EmptyTypeDefinition) {
-            if(domParameter == null) {
-                return ''' Boolean.FALSE '''
-            } else {
-                return ''' Boolean.TRUE '''
-            }
-        }
-        return '''(«type.resolvedName») Â«domParameter»'''
-    }
-
-    private def dispatch Class<? extends BindingCodec<Map<QName, Object>, Object>> generateValueTransformer(
-        Class<?> inputType, GeneratedTransferObject typeSpec, TypeDefinition<?> typeDef) {
-        try {
-
-            val SourceCodeGenerator sourceGenerator = sourceCodeGeneratorFactory.getInstance( null );
-
-            val returnType = typeSpec.valueReturnType;
-            if (returnType == null) {
-                val ctCls = createDummyImplementation(inputType, typeSpec, sourceGenerator);
-                val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain)
-                sourceGenerator.outputGeneratedSource( ctCls )
-                return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
-            }
-
-            val ctCls = createClass(typeSpec.codecClassName) [
-                //staticField(Map,"AUGMENTATION_SERIALIZERS");
-                if (inputType.isYangBindingAvailable) {
-                    implementsType(BINDING_CODEC)
-                    staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec, sourceGenerator)
-                    staticField(it, IDENTITYREF_CODEC, BindingCodec, sourceGenerator)
-                    implementsType(BindingDeserializer.asCtClass)
-                }
-                method(Object, "toDomValue", Object) [
-                    modifiers = PUBLIC + FINAL + STATIC
-                    val ctSpec = typeSpec.asCtClass;
-                    val body = '''
-                        {
-                            ////System.out.println("«inputType.simpleName»#toDomValue: "+$1);
-
-                            if($1 == null) {
-                            return null;
-                            }
-                            Â«typeSpec.resolvedName» _encapsulatedValue = («typeSpec.resolvedName») $1;
-                            ////System.out.println("«inputType.simpleName»#toDomValue:Enc: "+_encapsulatedValue);
-                            Â«returnType.resolvedName» _value =  _encapsulatedValue.getValue();
-                            ////System.out.println("«inputType.simpleName»#toDomValue:DeEnc: "+_value);
-                            Object _domValue = Â«serializeValue(returnType, "_value", null)»;
-                            return _domValue;
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-                method(Object, "serialize", Object) [
-                    val body = '''
-                        {
-                            return toDomValue($1);
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-                method(Object, "fromDomValue", Object) [
-                    modifiers = PUBLIC + FINAL + STATIC
-                    val body = '''
-                        {
-                            ////System.out.println("«inputType.simpleName»#fromDomValue: "+$1);
-
-                            if($1 == null) {
-                            return null;
-                            }
-                            Â«returnType.resolvedName» _simpleValue = Â«deserializeValue(returnType, "$1", null)»;
-                            Â«typeSpec.resolvedName» _value = new Â«typeSpec.resolvedName»(_simpleValue);
-                            return _value;
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-                method(Object, "deserialize", Object) [
-                    val body = '''
-                        {
-                            return fromDomValue($1);
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-            ]
-
-            val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain)
-            sourceGenerator.outputGeneratedSource( ctCls )
-            LOG.debug("DOM Codec for {} was generated {}", inputType, ret)
-            return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
-        } catch (Exception e) {
-            LOG.error("Cannot compile DOM Codec for {}", inputType, e);
-            val exception = new CodeGenerationException("Cannot compile Transformator for " + inputType);
-            exception.addSuppressed(e);
-            throw exception;
-        }
-    }
-
-    private def dispatch Class<? extends BindingCodec<Map<QName, Object>, Object>> generateValueTransformer(
-        Class<?> inputType, GeneratedTransferObject typeSpec, UnionTypeDefinition typeDef) {
-        try {
-            val SourceCodeGenerator sourceGenerator = sourceCodeGeneratorFactory.getInstance( null );
-
-            val ctCls = createClass(typeSpec.codecClassName) [
-                val properties = typeSpec.allProperties;
-                val getterToTypeDefinition = XtendHelper.getTypes(typeDef).toMap[type|type.QName.getterName];
-                //staticField(Map,"AUGMENTATION_SERIALIZERS");
-                if (inputType.isYangBindingAvailable) {
-                    implementsType(BINDING_CODEC)
-                    staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec, sourceGenerator)
-                    staticField(it, IDENTITYREF_CODEC, BindingCodec, sourceGenerator)
-                    implementsType(BindingDeserializer.asCtClass)
-                }
-                method(Object, "toDomValue", Object) [
-                    modifiers = PUBLIC + FINAL + STATIC
-                    val ctSpec = inputType.asCtClass;
-                    val body = '''
-                        {
-                            ////System.out.println("«inputType.simpleName»#toDomValue: "+$1);
-
-                            if($1 == null) {
-                            return null;
-                            }
-                            Â«typeSpec.resolvedName» _value = («typeSpec.resolvedName») $1;
-                            Â«FOR property : properties.entrySet»
-                            Â«IF property.key != "getValue"»
-                                Â«property.value.resolvedName» Â«property.key» = («property.value.resolvedName») _value.«property.
-                            key»();
-                                if(«property.key» != null) {
-                                    return Â«serializeValue(property.value, property.key,
-                            getterToTypeDefinition.get(property.key))»;
-                                }
-                            Â«ENDIF»
-                            Â«ENDFOR»
-
-                            return null;
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-                method(Object, "serialize", Object) [
-                    val body = '''
-                        {
-                            return toDomValue($1);
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-                method(Object, "fromDomValue", Object) [
-                    modifiers = PUBLIC + FINAL + STATIC
-                    val body = '''
-                        {
-                            ////System.out.println("«inputType.simpleName»#fromDomValue: "+$1);
-
-                            if($1 == null) {
-                            return null;
-                            }
-                            if($1 instanceof String) {
-                            String _simpleValue = (String) $1;
-                            return new Â«typeSpec.resolvedName»(_simpleValue.toCharArray());
-                            }
-                            return null;
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-                method(Object, "deserialize", Object) [
-                    val body = '''
-                        {
-                            return fromDomValue($1);
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-            ]
-
-            val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain)
-            sourceGenerator.outputGeneratedSource( ctCls )
-            LOG.debug("DOM Codec for {} was generated {}", inputType, ret)
-            return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
-        } catch (Exception e) {
-            LOG.error("Cannot compile DOM Codec for {}", inputType, e);
-            val exception = new CodeGenerationException("Cannot compile Transformator for " + inputType);
-            exception.addSuppressed(e);
-            throw exception;
-        }
-    }
-
-    private def dispatch Class<? extends BindingCodec<Map<QName, Object>, Object>> generateValueTransformer(
-        Class<?> inputType, GeneratedTransferObject typeSpec, BitsTypeDefinition typeDef) {
-        try {
-            val SourceCodeGenerator sourceGenerator = sourceCodeGeneratorFactory.getInstance( null );
-
-            val ctCls = createClass(typeSpec.codecClassName) [
-                //staticField(Map,"AUGMENTATION_SERIALIZERS");
-                if (inputType.isYangBindingAvailable) {
-                    implementsType(BINDING_CODEC)
-                    staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec, sourceGenerator)
-                    staticField(it, IDENTITYREF_CODEC, BindingCodec, sourceGenerator)
-                    implementsType(BindingDeserializer.asCtClass)
-                }
-                method(Object, "toDomValue", Object) [
-                    modifiers = PUBLIC + FINAL + STATIC
-                    val ctSpec = typeSpec.asCtClass;
-                    val body = '''
-                        {
-                            ////System.out.println("«inputType.simpleName»#toDomValue: "+$1);
-
-                            if($1 == null) {
-                            return null;
-                            }
-                            Â«typeSpec.resolvedName» _encapsulatedValue = («typeSpec.resolvedName») $1;
-                            Â«HashSet.resolvedName» _value = new Â«HashSet.resolvedName»();
-                            //System.out.println("«inputType.simpleName»#toDomValue:Enc: "+_encapsulatedValue);
-
-                            Â«FOR bit : typeDef.bits»
-                            Â«val getter = bit.getterName()»
-                            if(Boolean.TRUE.equals(_encapsulatedValue.«getter»())) {
-                                _value.add("«bit.name»");
-                            }
-                            Â«ENDFOR»
-                            Â«Set.resolvedName» _domValue =  Â«Collections.resolvedName».unmodifiableSet(_value);
-                            //System.out.println("«inputType.simpleName»#toDomValue:DeEnc: "+_domValue);
-
-                            return _domValue;
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-                method(Object, "serialize", Object) [
-                    val body = '''
-                        {
-                            return toDomValue($1);
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-                method(Object, "fromDomValue", Object) [
-                    modifiers = PUBLIC + FINAL + STATIC
-                    val sortedBits = IterableExtensions.sort(typeDef.bits, [o1, o2|o1.propertyName.compareTo(o2.propertyName)])
-                    val body = '''
-                        {
-                            //System.out.println("«inputType.simpleName»#fromDomValue: "+$1);
-
-                            if($1 == null) {
-                            return null;
-                            }
-                            Â«Set.resolvedName» _domValue = («Set.resolvedName») $1;
-                            Â«FOR bit : sortedBits»
-                            Boolean Â«bit.propertyName» = Boolean.valueOf(_domValue.contains("«bit.name»"));
-                            Â«ENDFOR»
-
-                            return new Â«inputType.resolvedName»(«FOR bit : sortedBits SEPARATOR ","»«bit.propertyName»«ENDFOR»);
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-                method(Object, "deserialize", Object) [
-                    val body = '''
-                        {
-                            return fromDomValue($1);
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-            ]
-
-            val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain)
-            sourceGenerator.outputGeneratedSource( ctCls )
-            LOG.debug("DOM Codec for {} was generated {}", inputType, ret)
-            return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
-        } catch (Exception e) {
-            LOG.error("Cannot compile DOM Codec for {}", inputType, e);
-            val exception = new CodeGenerationException("Cannot compile Transformator for " + inputType);
-            exception.addSuppressed(e);
-            throw exception;
-        }
-    }
-
-    def String getPropertyName(Bit bit) {
-        '''_«BindingMapping.getPropertyName(bit.name)»'''
-    }
-
-    def String getterName(Bit bit) {
-
-        val paramName = BindingMapping.getPropertyName(bit.name);
-        return '''is«paramName.toFirstUpper»''';
-    }
-
-    def boolean isYangBindingAvailable(Class<?> class1) {
-        try {
-            val bindingCodecClass = class1.classLoader.loadClass(BINDING_CODEC.name);
-            return bindingCodecClass !== null;
-        } catch (ClassNotFoundException e) {
-            return false;
-        }
-    }
-
-    private def createDummyImplementation(Class<?> object, GeneratedTransferObject typeSpec,
-                                          SourceCodeGenerator sourceGenerator ) {
-        LOG.trace("Generating Dummy DOM Codec for {} with {}", object, object.classLoader)
-        return createClass(typeSpec.codecClassName) [
-            if (object.isYangBindingAvailable) {
-                implementsType(BINDING_CODEC)
-                staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec, sourceGenerator)
-                staticField(it, IDENTITYREF_CODEC, BindingCodec, sourceGenerator)
-                implementsType(BindingDeserializer.asCtClass)
-            }
-            //implementsType(BindingDeserializer.asCtClass)
-            method(Object, "toDomValue", Object) [
-                modifiers = PUBLIC + FINAL + STATIC
-                val body = '''
-                    {
-                        if($1 == null) {
-                            return null;
-                        }
-                        return $1.toString();
-                    }'''
-                setBodyChecked( body, sourceGenerator )
-            ]
-            method(Object, "serialize", Object) [
-                val body = '''
-                    {
-                        return toDomValue($1);
-                    }
-                '''
-                setBodyChecked( body, sourceGenerator )
-            ]
-            method(Object, "fromDomValue", Object) [
-                modifiers = PUBLIC + FINAL + STATIC
-                val body = '''return null;'''
-                setBodyChecked( body, sourceGenerator )
-            ]
-            method(Object, "deserialize", Object) [
-                val body = '''
-                    {
-                        return fromDomValue($1);
-                    }
-                    '''
-                setBodyChecked( body, sourceGenerator )
-            ]
-        ]
-    }
-
-    private def Type getValueReturnType(GeneratedTransferObject object) {
-        for (prop : object.properties) {
-            if (prop.name == "value") {
-                return prop.returnType;
-            }
-        }
-        if (object.superType != null) {
-            return getValueReturnType(object.superType);
-        }
-        return null;
-    }
-
-    private def dispatch Class<?> generateValueTransformer(Class<?> inputType, Enumeration typeSpec, TypeDefinition<?> type) {
-        var EnumerationType enumSchemaType
-        if (type instanceof EnumerationType) {
-            enumSchemaType = type as EnumerationType
-        } else {
-            val typeRef = new ReferencedTypeImpl(typeSpec.packageName, typeSpec.name);
-            val schema = getSchemaNode(typeRef) as ExtendedType;
-            enumSchemaType = schema.baseType as EnumerationType;
-        }
-        val enumSchema = enumSchemaType;
-        try {
-            val SourceCodeGenerator sourceGenerator = sourceCodeGeneratorFactory.getInstance( null );
-
-            //log.info("Generating DOM Codec for {} with {}", inputType, inputType.classLoader)
-            val ctCls = createClass(typeSpec.codecClassName) [
-                //staticField(Map,"AUGMENTATION_SERIALIZERS");
-                //implementsType(BINDING_CODEC)
-                method(Object, "toDomValue", Object) [
-                    modifiers = PUBLIC + FINAL + STATIC
-                    val body = '''
-                        {
-                            if($1 == null) {
-                                return null;
-                            }
-                            Â«typeSpec.resolvedName» _value = («typeSpec.resolvedName») $1;
-                            Â«FOR en : enumSchema.values»
-                            if(«typeSpec.resolvedName».«BindingMapping.getClassName(en.name)».equals(_value)) {
-                                return "«en.name»";
-                            }
-                            Â«ENDFOR»
-                            return null;
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-                method(Object, "serialize", Object) [
-                    val body = '''
-                        {
-                            return toDomValue($1);
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-                method(Object, "fromDomValue", Object) [
-                    modifiers = PUBLIC + FINAL + STATIC
-                    val body = '''
-                        {
-                            if($1 == null) {
-                                return null;
-                            }
-                            String _value = (String) $1;
-                            Â«FOR en : enumSchema.values»
-                                if("«en.name»".equals(_value)) {
-                                    return Â«typeSpec.resolvedName».«BindingMapping.getClassName(en.name)»;
-                                }
-                            Â«ENDFOR»
-                            return null;
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-                method(Object, "deserialize", Object) [
-                    val body = '''
-                        {
-                            return fromDomValue($1);
-                        }
-                    '''
-                    setBodyChecked( body, sourceGenerator )
-                ]
-            ]
-
-            val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain)
-            sourceGenerator.outputGeneratedSource( ctCls )
-            LOG.debug("DOM Codec for {} was generated {}", inputType, ret)
-            return ret;
-        } catch (CodeGenerationException e) {
-            throw new CodeGenerationException("Cannot compile Transformator for " + inputType, e);
-        } catch (Exception e) {
-            LOG.error("Cannot compile DOM Codec for {}", inputType, e);
-            val exception = new CodeGenerationException("Cannot compile Transformator for " + inputType);
-            exception.addSuppressed(e);
-            throw exception;
-        }
-
-    }
-
-    def Class<?> toClassImpl(CtClass newClass, ClassLoader loader, ProtectionDomain domain) {
-        val cls = newClass.toClass(loader, domain);
-        if (classFileCapturePath !== null) {
-            newClass.writeFile(classFileCapturePath.absolutePath);
-        }
-        listener?.onCodecCreated(cls);
-        return cls;
-    }
-
-    def debugWriteClass(CtClass class1) {
-        val path = class1.name.replace(".", "/") + ".class"
-
-        val captureFile = new File(classFileCapturePath, path);
-        captureFile.createNewFile
-
-    }
-
-    /**
-     * Default catch all
-     *
-     **/
-    private def dispatch CharSequence deserializeProperty(DataSchemaNode container, Type type, String propertyName) '''
-        Â«type.resolvedName» Â«propertyName» = null;
-    '''
-
-    private def dispatch CharSequence deserializeProperty(DataSchemaNode container, GeneratedTypeBuilder type,
-        String propertyName) {
-        _deserializeProperty(container, type.toInstance, propertyName)
-    }
-
-    static def toSetter(String it) {
-
-        if (startsWith("is")) {
-            return "set" + substring(2);
-        } else if (startsWith("get")) {
-            return "set" + substring(3);
-        }
-        return "set" + it;
-    }
-
-    /*
-    private def dispatch CharSequence deserializeProperty(DataSchemaNode container,GeneratedType type, String propertyName) '''
-        Â«type.resolvedName» Â«propertyName» = value.«propertyName»();
-        if(«propertyName» != null) {
-            Object domValue = Â«type.serializer».toDomStatic(QNAME,«propertyName»);
-            _childNodes.add(domValue);
-        }
-    '''
-    */
-    private def getBuilderName(GeneratedType type) '''«type.resolvedName»Builder'''
-
-    private def staticQNameField(CtClass it, QName node, SourceCodeGenerator sourceGenerator) {
-        val field = new CtField(ctQName, "QNAME", it);
-        field.modifiers = PUBLIC + FINAL + STATIC;
-        val code = '''«QName.asCtClass.name».cachedReference(«QName.asCtClass.name».create("«node.namespace»","«node.formattedRevision»","«node.localName»"))'''
-        addField(field, code )
-
-        sourceGenerator.appendField( field, code );
-    }
-
-    private def String serializeBodyImpl(GeneratedType type, DataNodeContainer nodeContainer) '''
-        {
-            Â«QName.name» _resultName = Â«QName.name».create($1,QNAME.getLocalName());
-            java.util.List _childNodes = new java.util.ArrayList();
-            Â«type.resolvedName» value = («type.resolvedName») $2;
-            Â«transformDataContainerBody(type, type.allProperties, nodeContainer)»
-            Â«serializeAugmentations»
-            return ($r) java.util.Collections.singletonMap(_resultName,_childNodes);
-        }
-    '''
-
-    private def dispatch String serializeBody(GeneratedType type, ListSchemaNode node) {
-        return serializeBodyImpl(type, node);
-    }
-
-    private def dispatch String serializeBody(GeneratedType type, NotificationDefinition node) {
-        return serializeBodyImpl(type, node);
-    }
-
-    private def dispatch String serializeBody(GeneratedType type, ContainerSchemaNode node) {
-        return serializeBodyImpl(type, node);
-    }
-
-    private def dispatch String serializeBody(GeneratedType type, ChoiceCaseNode node) {
-        return serializeBodyImpl(type, node);
-    }
-
-    private def dispatch String serializeBody(GeneratedType type, SchemaNode node) '''
-        {
-        Â«QName.name» _resultName = Â«QName.name».create($1,QNAME.getLocalName());
-            java.util.List _childNodes = new java.util.ArrayList();
-            Â«type.resolvedName» value = («type.resolvedName») $2;
-            return ($r) java.util.Collections.singletonMap(_resultName,_childNodes);
-        }
-    '''
-
-    private def transformDataContainerBody(Type type, Map<String, Type> properties, DataNodeContainer node) {
-        val ret = '''
-            Â«FOR child : node.childNodes»
-                Â«val signature = properties.getFor(child)»
-                Â«IF signature !== null»
-                    ////System.out.println("«type.name»#«signature.key»" + value.«signature.key»());
-                    Â«serializeProperty(child, signature.value, signature.key)»
-                Â«ENDIF»
-            Â«ENDFOR»
-        '''
-        return ret;
-    }
-
-    private static def serializeAugmentations() '''
-        java.util.List _augmentations = (java.util.List) Â«AUGMENTATION_CODEC».serialize(value);
-        if(_augmentations != null) {
-            _childNodes.addAll(_augmentations);
-        }
-    '''
-
-    private static def Entry<String, Type> getFor(Map<String, Type> map, DataSchemaNode node) {
-        var sig = map.get(node.getterName);
-        if (sig != null) {
-            return new SimpleEntry(node.getterName, sig);
-        }
-        sig = map.get(node.booleanGetterName);
-        if (sig != null) {
-            return new SimpleEntry(node.booleanGetterName, map.get(node.booleanGetterName));
-        }
-        return null;
-    }
-
-    private static def String getBooleanGetterName(DataSchemaNode node) {
-        return "is" + BindingMapping.getPropertyName(node.QName.localName).toFirstUpper;
-    }
-
-    private static def String getGetterName(DataSchemaNode node) {
-        return "get" + BindingMapping.getPropertyName(node.QName.localName).toFirstUpper;
-    }
-
-    private static def String getGetterName(QName node) {
-        return "get" + BindingMapping.getPropertyName(node.localName).toFirstUpper;
-    }
-
-    private def dispatch CharSequence serializeProperty(ListSchemaNode schema, ParameterizedType type,
-        String propertyName) '''
-        Â«type.resolvedName» Â«propertyName» = value.«propertyName»();
-        ////System.out.println("«propertyName»:" + Â«propertyName»);
-        if(«propertyName» != null) {
-            java.util.Iterator _iterator = Â«propertyName».iterator();
-            boolean _hasNext = _iterator.hasNext();
-            while(_hasNext) {
-                Object _listItem = _iterator.next();
-                Object _domValue = Â«type.actualTypeArguments.get(0).serializer(schema).resolvedName».toDomStatic(_resultName,_listItem);
-                _childNodes.add(_domValue);
-                _hasNext = _iterator.hasNext();
-            }
-        }
-    '''
-
-    private def dispatch CharSequence serializeProperty(LeafSchemaNode schema, Type type, String propertyName) '''
-        Â«type.resolvedName» Â«propertyName» = value.«propertyName»();
-
-        if(«propertyName» != null) {
-            Â«QName.name» _qname = Â«QName.name».create(_resultName,"«schema.QName.localName»");
-            Object _propValue = Â«serializeValue(type, propertyName, schema.type)»;
-            if(_propValue != null) {
-                Object _domValue = java.util.Collections.singletonMap(_qname,_propValue);
-                _childNodes.add(_domValue);
-            }
-        }
-    '''
-
-    private def dispatch serializeValue(GeneratedTransferObject type, String parameter, TypeDefinition<?> typeDefinition) {
-        '''«type.valueSerializer(typeDefinition).resolvedName».toDomValue(«parameter»)'''
-    }
-
-    private def dispatch serializeValue(Enumeration type, String parameter, TypeDefinition<?> typeDefinition) {
-        '''«type.valueSerializer(typeDefinition).resolvedName».toDomValue(«parameter»)'''
-    }
-
-    private def dispatch serializeValue(Type type, String parameter, EmptyTypeDefinition typeDefinition) {
-        '''(«parameter».booleanValue() ? "" : null)'''
-    }
-
-    private def dispatch serializeValue(Type signature, String property, TypeDefinition<?> typeDefinition) {
-        serializeValue(signature,property)
-    }
-
-    private def dispatch serializeValue(Type signature, String property, Void typeDefinition) {
-        serializeValue(signature,property)
-    }
-
-    private def dispatch serializeValue(Type signature, String property) {
-        if (INSTANCE_IDENTIFIER == signature) {
-            return '''«INSTANCE_IDENTIFIER_CODEC».serialize(«property»)'''
-        } else if (CLASS_TYPE.equals(signature)) {
-            return '''(«QName.resolvedName») Â«IDENTITYREF_CODEC».serialize(«property»)'''
-        }
-        if ("char[]" == signature.name) {
-            return '''new String(«property»)''';
-        }
-        return '''«property»''';
-    }
-
-    private def dispatch CharSequence serializeProperty(LeafListSchemaNode schema, ParameterizedType type,
-        String propertyName) '''
-        Â«type.resolvedName» Â«propertyName» = value.«propertyName»();
-        if(«propertyName» != null) {
-            Â«QName.name» _qname = Â«QName.name».create(_resultName,"«schema.QName.localName»");
-            java.util.Iterator _iterator = Â«propertyName».iterator();
-            boolean _hasNext = _iterator.hasNext();
-            while(_hasNext) {
-                Object _listItem = _iterator.next();
-                Object _propValue = Â«serializeValue(type.actualTypeArguments.get(0), "_listItem", schema.type)»;
-                Object _domValue = java.util.Collections.singletonMap(_qname,_propValue);
-                _childNodes.add(_domValue);
-                _hasNext = _iterator.hasNext();
-            }
-        }
-    '''
-
-    private def dispatch CharSequence serializeProperty(ChoiceNode container, GeneratedType type,
-        String propertyName) '''
-        Â«type.resolvedName» Â«propertyName» = value.«propertyName»();
-        if(«propertyName» != null) {
-            java.util.List domValue = Â«type.serializer(container).resolvedName».toDomStatic(_resultName,«propertyName»);
-            _childNodes.addAll(domValue);
-        }
-    '''
-
-    /**
-     * Default catch all
-     *
-     **/
-    private def dispatch CharSequence serializeProperty(DataSchemaNode container, Type type, String propertyName) '''
-        Â«type.resolvedName» Â«propertyName» = value.«propertyName»();
-        if(«propertyName» != null) {
-            Object domValue = Â«propertyName»;
-            _childNodes.add(domValue);
-        }
-    '''
-
-    private def dispatch CharSequence serializeProperty(DataSchemaNode container, GeneratedTypeBuilder type,
-        String propertyName) {
-        serializeProperty(container, type.toInstance, propertyName)
-    }
-
-    private def dispatch CharSequence serializeProperty(DataSchemaNode container, GeneratedType type,
-        String propertyName) '''
-        Â«type.resolvedName» Â«propertyName» = value.«propertyName»();
-        if(«propertyName» != null) {
-            Object domValue = Â«type.serializer(container).resolvedName».toDomStatic(_resultName,«propertyName»);
-            _childNodes.add(domValue);
-        }
-    '''
-
-    private def codecClassName(GeneratedType typeSpec) {
-        return '''«typeSpec.resolvedName»$Broker$Codec$DOM'''
-    }
-
-    private def codecClassName(Class<?> typeSpec) {
-        return '''«typeSpec.name»$Broker$Codec$DOM'''
-    }
-
-    private def HashMap<String, Type> getAllProperties(GeneratedType type) {
-        val ret = new HashMap<String, Type>();
-        type.collectAllProperties(ret);
-        return ret;
-    }
-
-    private def dispatch void collectAllProperties(GeneratedType type, Map<String, Type> set) {
-        for (definition : type.methodDefinitions) {
-            set.put(definition.name, definition.returnType);
-        }
-        for (property : type.properties) {
-            set.put(property.getterName, property.returnType);
-        }
-        for (parent : type.implements) {
-            parent.collectAllProperties(set);
-        }
-    }
-
-    def String getGetterName(GeneratedProperty property) {
-        return "get" + property.name.toFirstUpper
-    }
-
-    private def dispatch void collectAllProperties(Type type, Map<String, Type> set) {
-        // NOOP for generic type.
-    }
-
-    def String getResolvedName(Type type) {
-        return type.asCtClass.name;
-    }
-
-    def String getResolvedName(Class<?> type) {
-        return type.asCtClass.name;
-    }
-
-    def CtClass asCtClass(Type type) {
-        val cls = loadClass(type.fullyQualifiedName)
-        return cls.asCtClass;
-    }
-
-    private def dispatch processException(Class<?> inputType, CodeGenerationException e) {
-        LOG.error("Cannot compile DOM Codec for {}. One of it's prerequisites was not generated.", inputType);
-        throw e;
-    }
-
-    private def dispatch processException(Class<?> inputType, Exception e) {
-        LOG.error("Cannot compile DOM Codec for {}", inputType, e);
-        val exception = new CodeGenerationException("Cannot compile Transformator for " + inputType, e);
-        throw exception;
-    }
-
-    private def setBodyChecked(CtMethod method, String body, SourceCodeGenerator sourceGenerator ) {
-        try {
-            method.setBody(body);
-
-            sourceGenerator.appendMethod( method, body );
-        } catch (CannotCompileException e) {
-            LOG.error("Cannot compile method: {}#{} {}, Reason: {} Body: {}", method.declaringClass, method.name,
-                method.signature, e.message, body)
-            throw e;
-        }
-    }
-}
-
diff --git a/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/TypeResolver.java b/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/TypeResolver.java
deleted file mode 100644 (file)
index ba9aa1b..0000000
+++ /dev/null
@@ -1,24 +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.yangtools.sal.binding.generator.impl;
-
-import org.opendaylight.yangtools.sal.binding.model.api.Type;
-import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.SchemaNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-
-/**
- * Internal interface exposed to TransformerGenerator
- */
-interface TypeResolver {
-    AugmentationSchema getAugmentation(Type type);
-    GeneratedTypeBuilder getDefinition(Type type);
-    SchemaNode getSchemaNode(Type type);
-    GeneratedTypeBuilder getTypeBuilder(SchemaPath path);
-}
index a9759d885fd73804172f86fb8000e1e98bbdac25..913d68542a79a8b4c7e63eac7cf4e0994648d626 100644 (file)
@@ -17,7 +17,7 @@ import org.opendaylight.yangtools.yang.common.QName
 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
 import org.opendaylight.yangtools.yang.model.api.Deviation
@@ -55,34 +55,34 @@ class YangTemplate {
 
         '''
             Â«IF schemaNode instanceof DataSchemaNode»
-            Â«writeDataSchemaNode(schemaNode as DataSchemaNode)»
+            Â«writeDataSchemaNode(schemaNode)»
             Â«ENDIF»
             Â«IF schemaNode instanceof EnumTypeDefinition.EnumPair»
-            Â«writeEnumPair(schemaNode as EnumTypeDefinition.EnumPair)»
+            Â«writeEnumPair(schemaNode)»
             Â«ENDIF»
             Â«IF schemaNode instanceof ExtensionDefinition»
-            Â«writeExtension(schemaNode as ExtensionDefinition)»
+            Â«writeExtension(schemaNode)»
             Â«ENDIF»
             Â«IF schemaNode instanceof FeatureDefinition»
-            Â«writeFeature(schemaNode as FeatureDefinition)»
+            Â«writeFeature(schemaNode)»
             Â«ENDIF»
             Â«IF schemaNode instanceof GroupingDefinition»
-            Â«writeGroupingDef(schemaNode as GroupingDefinition)»
+            Â«writeGroupingDef(schemaNode)»
             Â«ENDIF»
             Â«IF schemaNode instanceof IdentitySchemaNode»
-            Â«writeIdentity(schemaNode as IdentitySchemaNode)»
+            Â«writeIdentity(schemaNode)»
             Â«ENDIF»
             Â«IF schemaNode instanceof NotificationDefinition»
-            Â«writeNotification(schemaNode as NotificationDefinition)»
+            Â«writeNotification(schemaNode)»
             Â«ENDIF»
             Â«IF schemaNode instanceof RpcDefinition»
-            Â«writeRPC(schemaNode as RpcDefinition)»
+            Â«writeRPC(schemaNode)»
             Â«ENDIF»
             Â«IF schemaNode instanceof TypeDefinition<?>»
-            Â«writeTypeDefinition(schemaNode as TypeDefinition<?>)»
+            Â«writeTypeDefinition(schemaNode)»
             Â«ENDIF»
             Â«IF schemaNode instanceof UnknownSchemaNode»
-            Â«writeUnknownSchemaNode(schemaNode as UnknownSchemaNode)»
+            Â«writeUnknownSchemaNode(schemaNode)»
             Â«ENDIF»
         '''
     }
@@ -94,7 +94,7 @@ class YangTemplate {
         '''
             Â«FOR node : nodes»
                 Â«IF node instanceof NotificationDefinition»
-                Â«writeNotification(node as NotificationDefinition)»
+                Â«writeNotification(node)»
                 Â«ELSEIF node instanceof RpcDefinition»
                 Â«writeRPC(node as RpcDefinition)»
                 Â«ENDIF»
@@ -371,7 +371,7 @@ class YangTemplate {
         '''
             refine Â«path.pathFromRoot.last» {
                 Â«IF schemaNode instanceof DataSchemaNode»
-                Â«writeDataSchemaNode(schemaNode as DataSchemaNode)»
+                Â«writeDataSchemaNode(schemaNode)»
                 Â«ENDIF»
             }
         '''
@@ -645,7 +645,7 @@ class YangTemplate {
         '''
     }
 
-    def static writeChoiceNode(ChoiceNode choiceNode) {
+    def static writeChoiceNode(ChoiceSchemaNode choiceNode) {
         '''
             choice Â«choiceNode.getQName.localName» {
                 Â«FOR child : choiceNode.cases»
@@ -682,25 +682,25 @@ class YangTemplate {
     def static CharSequence writeDataSchemaNode(DataSchemaNode child) {
         '''
             Â«IF child instanceof ContainerSchemaNode»
-                Â«writeContSchemaNode(child as ContainerSchemaNode)»
+                Â«writeContSchemaNode(child)»
             Â«ENDIF»
             Â«IF child instanceof AnyXmlSchemaNode»
-                Â«writeAnyXmlSchemaNode(child as AnyXmlSchemaNode)»
+                Â«writeAnyXmlSchemaNode(child)»
             Â«ENDIF»
             Â«IF child instanceof LeafSchemaNode»
-                Â«writeLeafSchemaNode(child as LeafSchemaNode)»
+                Â«writeLeafSchemaNode(child)»
             Â«ENDIF»
             Â«IF child instanceof LeafListSchemaNode»
-                Â«writeLeafListSchemaNode(child as LeafListSchemaNode)»
+                Â«writeLeafListSchemaNode(child)»
             Â«ENDIF»
             Â«IF child instanceof ChoiceCaseNode»
-                Â«writeChoiceCaseNode(child as ChoiceCaseNode)»
+                Â«writeChoiceCaseNode(child)»
             Â«ENDIF»
-            Â«IF child instanceof ChoiceNode»
-                Â«writeChoiceNode(child as ChoiceNode)»
+            Â«IF child instanceof ChoiceSchemaNode»
+                Â«writeChoiceNode(child)»
             Â«ENDIF»
             Â«IF child instanceof ListSchemaNode»
-                Â«writeListSchemaNode(child as ListSchemaNode)»
+                Â«writeListSchemaNode(child)»
             Â«ENDIF»
         '''
     }
diff --git a/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/package-info.java b/code-generator/binding-generator-impl/src/main/java/org/opendaylight/yangtools/sal/binding/generator/impl/package-info.java
deleted file mode 100644 (file)
index 50cbec8..0000000
+++ /dev/null
@@ -1,8 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.sal.binding.generator.impl;
\ No newline at end of file
index caf22b85984df6407bfdeaabbf90a15715d61afe..d79df4ef19e90e26b0dea0bbaae656cbccf06421 100644 (file)
@@ -44,7 +44,7 @@ import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.Augmentat
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
@@ -229,7 +229,7 @@ public class BindingRuntimeContext implements Immutable {
      *         the given context.
      * @throws IllegalArgumentException If supplied class does not represent case.
      */
-    public Optional<ChoiceCaseNode> getCaseSchemaDefinition(final ChoiceNode schema, final Class<?> childClass) throws IllegalArgumentException {
+    public Optional<ChoiceCaseNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class<?> childClass) throws IllegalArgumentException {
         final DataSchemaNode origSchema = getSchemaDefinition(childClass);
         Preconditions.checkArgument(origSchema instanceof ChoiceCaseNode, "Supplied schema %s is not case.", origSchema);
 
@@ -274,8 +274,8 @@ public class BindingRuntimeContext implements Immutable {
 
     public ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
         final Map<Type,Entry<Type,Type>> childToCase = new HashMap<>();;
-        for (final ChoiceNode choice :  FluentIterable.from(schema.getChildNodes()).filter(ChoiceNode.class)) {
-            final ChoiceNode originalChoice = getOriginalSchema(choice);
+        for (final ChoiceSchemaNode choice :  FluentIterable.from(schema.getChildNodes()).filter(ChoiceSchemaNode.class)) {
+            final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
             final Type choiceType = referencedType(typeToDefiningSchema.inverse().get(originalChoice));
             final Collection<Type> cases = choiceToCases.get(choiceType);
 
index 1084a0bf0f7dc8139825d3cbef4f83cf3abbdff4..5c35454039931e8a45b16e2b77c69f8ab3e76552 100644 (file)
@@ -9,7 +9,6 @@ package org.opendaylight.yangtools.sal.binding.generator.util;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 import static com.google.common.base.Preconditions.checkState;
-
 import com.google.common.base.Preconditions;
 import java.net.URI;
 import java.util.Date;
@@ -17,7 +16,7 @@ import java.util.Iterator;
 import javax.annotation.Nullable;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
@@ -87,10 +86,10 @@ public final class YangSchemaUtils {
             final DataSchemaNode child = currentNode.getDataChildByName(currentArg);
             if(child instanceof DataNodeContainer) {
                 currentNode = (DataNodeContainer) child;
-            } else if (child instanceof ChoiceNode) {
+            } else if (child instanceof ChoiceSchemaNode) {
                 final QName caseQName = arguments.next();
                 Preconditions.checkArgument(arguments.hasNext(), "Path must not refer case only.");
-                currentNode = ((ChoiceNode) child).getCaseNodeByName(caseQName);
+                currentNode = ((ChoiceSchemaNode) child).getCaseNodeByName(caseQName);
             } else {
                 // Search in grouping
                 for( final GroupingDefinition grouping : currentNode.getGroupings()) {
index def0b2766a782fb9894d7324afbc10f37ee4e3a8..be9b3d7a49235b7b1ddedb74369b31b807323153 100644 (file)
@@ -7,13 +7,17 @@
  */
 package org.opendaylight.yangtools.binding.generator.util;
 
+import com.google.common.base.CharMatcher;
+import com.google.common.base.Splitter;
 import com.google.common.cache.CacheBuilder;
 import com.google.common.cache.CacheLoader;
 import com.google.common.cache.LoadingCache;
+import com.google.common.collect.Iterables;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.concurrent.Future;
+import javax.annotation.Nullable;
 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
 import org.opendaylight.yangtools.sal.binding.model.api.Restrictions;
@@ -43,6 +47,7 @@ public final class Types {
     public static final ConcreteType VOID = typeForClass(Void.class);
     public static final ConcreteType BYTE_ARRAY = primitiveType("byte[]", null);
     public static final ConcreteType CHAR_ARRAY = primitiveType("char[]", null);
+    private static final Splitter DOT_SPLITTER = Splitter.on('.');
 
     /**
      * It is not desirable to create instance of this class
@@ -203,6 +208,16 @@ public final class Types {
         return parameterizedTypeFor(augmentation, valueType);
     }
 
+
+    public static  @Nullable String getOuterClassName(final Type valueType) {
+        final String pkgName = valueType.getPackageName();
+        if(CharMatcher.JAVA_UPPER_CASE.indexIn(pkgName) >= 0) {
+            // It is inner class.
+            return Iterables.getLast(DOT_SPLITTER.split(pkgName));
+        }
+        return null;
+    }
+
     /**
      *
      * Represents concrete JAVA type.
index 9e33442de24059144a365aa7e2f4b8c24594976e..d98b52fc471bd2b6ac4f152cae09be14d1dc6a20 100644 (file)
@@ -63,10 +63,10 @@ abstract class BaseTemplate {
         '''.toString
     }
 
-    protected def imports() ''' 
+    protected def imports() '''
         Â«IF !importMap.empty»
             Â«FOR entry : importMap.entrySet»
-                Â«IF entry.value != fullyQualifiedName»
+                Â«IF !hasSamePackage(entry.value)»
                     import Â«entry.value».«entry.key»;
                 Â«ENDIF»
             Â«ENDFOR»
@@ -74,6 +74,17 @@ abstract class BaseTemplate {
 
     '''
 
+    /**
+     * Checks if packages of generated type and imported type is the same
+     *
+     * @param importedTypePackageNam
+     * the package name of imported type
+     * @return true if the packages are the same false otherwise
+     */
+    final private def boolean hasSamePackage(String importedTypePackageName) {
+        return type.packageName.equals(importedTypePackageName);
+    }
+
     protected abstract def CharSequence body();
 
     // Helper patterns
@@ -93,10 +104,10 @@ abstract class BaseTemplate {
 
     /**
      * Template method which generates the getter method for <code>field</code>
-     * 
-     * @param field 
+     *
+     * @param field
      * generated property with data about field which is generated as the getter method
-     * @return string with the getter method source code in JAVA format 
+     * @return string with the getter method source code in JAVA format
      */
     final protected def getterMethod(GeneratedProperty field) {
         '''
@@ -117,10 +128,10 @@ abstract class BaseTemplate {
 
     /**
      * Template method which generates the setter method for <code>field</code>
-     * 
-     * @param field 
+     *
+     * @param field
      * generated property with data about field which is generated as the setter method
-     * @return string with the setter method source code in JAVA format 
+     * @return string with the setter method source code in JAVA format
      */
     final protected def setterMethod(GeneratedProperty field) '''
         Â«val returnType = field.returnType.importedName»
@@ -141,7 +152,7 @@ abstract class BaseTemplate {
 
     /**
      * Template method which generates method parameters with their types from <code>parameters</code>.
-     * 
+     *
      * @param parameters
      * group of generated property instances which are transformed to the method parameters
      * @return string with the list of the method parameters with their types in JAVA format
@@ -151,17 +162,17 @@ abstract class BaseTemplate {
 
     /**
      * Template method which generates sequence of the names of the class attributes from <code>parameters</code>.
-     * 
-     * @param parameters 
+     *
+     * @param parameters
      * group of generated property instances which are transformed to the sequence of parameter names
-     * @return string with the list of the parameter names of the <code>parameters</code> 
+     * @return string with the list of the parameter names of the <code>parameters</code>
      */
     def final protected asArguments(Iterable<GeneratedProperty> parameters) '''«IF !parameters.empty»«FOR parameter : parameters SEPARATOR ", "»«parameter.
         fieldName»«ENDFOR»«ENDIF»'''
 
     /**
      * Template method which generates JAVA comments.
-     * 
+     *
      * @param comment string with the comment for whole JAVA class
      * @return string with comment in JAVA format
      */
@@ -185,8 +196,11 @@ abstract class BaseTemplate {
         sb.append(NEW_LINE)
 
         for (String t : NL_SPLITTER.split(text)) {
-            sb.append(" * ")
-            sb.append(t)
+            sb.append(" *")
+            if (!t.isEmpty()) {
+                sb.append(' ');
+                sb.append(t)
+            }
             sb.append(NEW_LINE)
         }
         sb.append(" */")
@@ -417,9 +431,9 @@ abstract class BaseTemplate {
     def getRestrictions(Type type) {
         var Restrictions restrictions = null
         if (type instanceof ConcreteType) {
-            restrictions = (type as ConcreteType).restrictions
+            restrictions = type.restrictions
         } else if (type instanceof GeneratedTransferObject) {
-            restrictions = (type as GeneratedTransferObject).restrictions
+            restrictions = type.restrictions
         }
         return restrictions
     }
@@ -439,7 +453,7 @@ abstract class BaseTemplate {
 
     /**
      * Template method which generates method parameters with their types from <code>parameters</code>.
-     * 
+     *
      * @param parameters
      * list of parameter instances which are transformed to the method parameters
      * @return string with the list of the method parameters with their types in JAVA format
index 3a53ad2a9396f602818caa90c049fa249230c43b..15e93756576ab94104cd4d33549e8b486937e6f9 100644 (file)
@@ -34,7 +34,7 @@ import org.opendaylight.yangtools.yang.binding.Identifiable
 import org.opendaylight.yangtools.concepts.Builder
 
 /**
- * Template for generating JAVA builder classes. 
+ * Template for generating JAVA builder classes.
  */
 
 class BuilderTemplate extends BaseTemplate {
@@ -84,7 +84,7 @@ class BuilderTemplate extends BaseTemplate {
     /**
      * Returns set of method signature instances which contains all the methods of the <code>genType</code>
      * and all the methods of the implemented interfaces.
-     * 
+     *
      * @returns set of method signature instances
      */
     def private Set<MethodSignature> createMethods() {
@@ -97,9 +97,9 @@ class BuilderTemplate extends BaseTemplate {
     }
 
     /**
-     * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code> 
+     * Adds to the <code>methods</code> set all the methods of the <code>implementedIfcs</code>
      * and recursively their implemented interfaces.
-     * 
+     *
      * @param methods set of method signatures
      * @param implementedIfcs list of implemented interfaces
      */
@@ -132,7 +132,7 @@ class BuilderTemplate extends BaseTemplate {
 
     /**
      * Returns the first element of the list <code>elements</code>.
-     * 
+     *
      * @param list of elements
      */
     def private <E> first(List<E> elements) {
@@ -141,7 +141,7 @@ class BuilderTemplate extends BaseTemplate {
 
     /**
      * Returns the name of the package from <code>fullyQualifiedName</code>.
-     * 
+     *
      * @param fullyQualifiedName string with fully qualified type name (package + type)
      * @return string with the package name
      */
@@ -163,8 +163,8 @@ class BuilderTemplate extends BaseTemplate {
 
     /**
      * Creates set of generated property instances from getter <code>methods</code>.
-     * 
-     * @param set of method signature instances which should be transformed to list of properties 
+     *
+     * @param set of method signature instances which should be transformed to list of properties
      * @return set of generated property instances which represents the getter <code>methods</code>
      */
     def private propertiesFromMethods(Collection<MethodSignature> methods) {
@@ -183,7 +183,7 @@ class BuilderTemplate extends BaseTemplate {
 
     /**
      * Creates generated property instance from the getter <code>method</code> name and return type.
-     * 
+     *
      * @param method method signature from which is the method name and return type obtained
      * @return generated property instance for the getter <code>method</code>
      * @throws IllegalArgumentException<ul>
@@ -200,7 +200,7 @@ class BuilderTemplate extends BaseTemplate {
         var prefix = "get";
         if(Types.BOOLEAN.equals(method.returnType)) {
             prefix = "is";
-        } 
+        }
         if (method.name.startsWith(prefix)) {
             val fieldName = method.getName().substring(prefix.length()).toFirstLower
             val tmpGenTO = new GeneratedTOBuilderImpl("foo", "foo")
@@ -210,8 +210,8 @@ class BuilderTemplate extends BaseTemplate {
     }
 
     /**
-     * Template method which generates JAVA class body for builder class and for IMPL class. 
-     * 
+     * Template method which generates JAVA class body for builder class and for IMPL class.
+     *
      * @return string with JAVA source code
      */
     override body() '''
@@ -251,7 +251,7 @@ class BuilderTemplate extends BaseTemplate {
                 Â«generateHashCode()»
 
                 Â«generateEquals()»
-                
+
                 Â«generateToString(properties)»
             }
 
@@ -263,7 +263,7 @@ class BuilderTemplate extends BaseTemplate {
      */
     def private generateConstructorsFromIfcs(Type type) '''
         public Â«type.name»«BUILDER»() {
-        } 
+        }
         Â«IF (type instanceof GeneratedType && !(type instanceof GeneratedTransferObject))»
             Â«val ifc = type as GeneratedType»
             Â«FOR impl : ifc.implements»
@@ -277,14 +277,12 @@ class BuilderTemplate extends BaseTemplate {
      */
     def private Object generateConstructorFromIfc(Type impl) '''
         Â«IF (impl instanceof GeneratedType)»
-            Â«val implType = impl as GeneratedType»
-
-            Â«IF !(implType.methodDefinitions.empty)»
-                public Â«type.name»«BUILDER»(«implType.fullyQualifiedName» arg) {
-                    Â«printConstructorPropertySetter(implType)»
+            Â«IF !(impl.methodDefinitions.empty)»
+                public Â«type.name»«BUILDER»(«impl.fullyQualifiedName» arg) {
+                    Â«printConstructorPropertySetter(impl)»
                 }
             Â«ENDIF»
-            Â«FOR implTypeImplement : implType.implements»
+            Â«FOR implTypeImplement : impl.implements»
                 Â«generateConstructorFromIfc(implTypeImplement)»
             Â«ENDFOR»
         Â«ENDIF»
@@ -380,7 +378,7 @@ class BuilderTemplate extends BaseTemplate {
                 baseIfcs.add(ifc)
             }
         }
-        return baseIfcs 
+        return baseIfcs
     }
 
     private def Set<Type> getAllIfcs(Type type) {
@@ -394,7 +392,7 @@ class BuilderTemplate extends BaseTemplate {
                 baseIfcs.addAll(impl.getAllIfcs)
             }
         }
-        return baseIfcs 
+        return baseIfcs
     }
 
     private def List<String> toListOfNames(Collection<Type> types) {
@@ -568,7 +566,7 @@ class BuilderTemplate extends BaseTemplate {
                             break;
                             case 1:
                                 final Â«Map.importedName».Entry<«Class.importedName»<? extends Â«augmentField.returnType.importedName»>, Â«augmentField.returnType.importedName»> e = Â«prop».«augmentField.name».entrySet().iterator().next();
-                                this.«augmentField.name» = Â«Collections.importedName».<«Class.importedName»<? extends Â«augmentField.returnType.importedName»>, Â«augmentField.returnType.importedName»>singletonMap(e.getKey(), e.getValue());       
+                                this.«augmentField.name» = Â«Collections.importedName».<«Class.importedName»<? extends Â«augmentField.returnType.importedName»>, Â«augmentField.returnType.importedName»>singletonMap(e.getKey(), e.getValue());
                             break;
                         default :
                             this.«augmentField.name» = new Â«HashMap.importedName»<>(«prop».«augmentField.name»);
@@ -613,7 +611,7 @@ class BuilderTemplate extends BaseTemplate {
 
     /**
      * Template method which generate getter methods for IMPL class.
-     * 
+     *
      * @return string with getter methods
      */
     def private generateGetters(boolean addOverride) '''
@@ -638,7 +636,7 @@ class BuilderTemplate extends BaseTemplate {
 
     /**
      * Template method which generates the method <code>hashCode()</code>.
-     * 
+     *
      * @return string with the <code>hashCode()</code> method definition in JAVA format
      */
     def protected generateHashCode() '''
@@ -664,8 +662,8 @@ class BuilderTemplate extends BaseTemplate {
 
     /**
      * Template method which generates the method <code>equals()</code>.
-     * 
-     * @return string with the <code>equals()</code> method definition in JAVA format     
+     *
+     * @return string with the <code>equals()</code> method definition in JAVA format
      */
     def protected generateEquals() '''
         Â«IF !properties.empty || augmentField != null»
@@ -770,15 +768,15 @@ class BuilderTemplate extends BaseTemplate {
         return Â«type.importedName».class;
     }
     '''
-    
+
     private def createDescription(GeneratedType type) {
         return '''
         Class that builds {@link Â«type.importedName»} instances.
-        
+
         @see Â«type.importedName»
     '''
     }
-    
+
     override def protected String formatDataForJavaDoc(GeneratedType type) {
         val typeDescription = createDescription(type)
 
index b79d871f886bbacb705050b6fc53ac88a565c359..28c2f0dcea03243fe32d9e1694c50d30fb9cbc70 100644 (file)
@@ -189,7 +189,7 @@ class ClassTemplate extends BaseTemplate {
         Â«IF !enclosedGeneratedTypes.empty»
             Â«FOR innerClass : enclosedGeneratedTypes SEPARATOR "\n"»
                 Â«IF (innerClass instanceof GeneratedTransferObject)»
-                    Â«val classTemplate = new ClassTemplate(innerClass as GeneratedTransferObject)»
+                    Â«val classTemplate = new ClassTemplate(innerClass)»
                     Â«classTemplate.generateAsInnerClass»
 
                 Â«ENDIF»
@@ -464,12 +464,11 @@ class ClassTemplate extends BaseTemplate {
                 Â«IF c.name == TypeConstants.PATTERN_CONSTANT_NAME»
                     Â«val cValue = c.value»
                     Â«IF cValue instanceof List<?>»
-                        Â«val cValues = cValue as List<?>»
                         private static final Â«List.importedName»<«Pattern.importedName»> Â«Constants.MEMBER_PATTERN_LIST»;
                         public static final Â«List.importedName»<String> Â«TypeConstants.PATTERN_CONSTANT_NAME» = Â«ImmutableList.importedName».of(«
-                        FOR v : cValues SEPARATOR ", "»«
+                        FOR v : cValue SEPARATOR ", "»«
                             IF v instanceof String»"«
-                                v as String»"«
+                                v»"«
                             ENDIF»«
                         ENDFOR»);
 
index 417451bc181eee82bc51d14c51909aeb56430d8c..92466b2bd2b2d7ad8e27360ddca0c982dc860cc6 100644 (file)
@@ -11,36 +11,36 @@ import org.opendaylight.yangtools.sal.binding.model.api.Enumeration
 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType
 
 /**
- * Template for generating JAVA enumeration type. 
+ * Template for generating JAVA enumeration type.
  */
 class EnumTemplate extends BaseTemplate {
 
-    
+
     /**
      * Enumeration which will be transformed to JAVA source code for enumeration
      */
     val Enumeration enums
-    
+
     /**
      * Constructs instance of this class with concrete <code>enums</code>.
-     * 
-     * @param enums enumeration which will be transformed to JAVA source code 
+     *
+     * @param enums enumeration which will be transformed to JAVA source code
      */
     new(Enumeration enums) {
         super(enums as GeneratedType )
         this.enums = enums
     }
-    
-    
+
+
     /**
      * Generates only JAVA enumeration source code.
-     * 
+     *
      * @return string with JAVA enumeration source code
      */
     def generateAsInnerClass() {
         return body
     }
-    
+
     def writeEnumItem(String name, int value, String description) '''
         Â«asJavadoc(formatToParagraph(description))»
         Â«name»(«value»)
@@ -48,8 +48,8 @@ class EnumTemplate extends BaseTemplate {
 
     /**
      * Template method which generates enumeration body (declaration + enumeration items).
-     * 
-     * @return string with the enumeration body 
+     *
+     * @return string with the enumeration body
      */
     override body() '''
         Â«wrapToDocumentation(formatDataForJavaDoc(enums))»
@@ -69,11 +69,11 @@ class EnumTemplate extends BaseTemplate {
 
                 VALUE_MAP = b.build();
             }
-        
+
             private Â«enums.name»(int value) {
                 this.value = value;
             }
-            
+
             /**
              * @return integer value
              */
index b9210287cf07fe2a3414b5ff4ff3ba303e9925cb..acca70de9020dd151f5f63351562bb740c740c49 100644 (file)
@@ -16,34 +16,34 @@ import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType
 import org.opendaylight.yangtools.sal.binding.model.api.MethodSignature\rimport org.opendaylight.yangtools.sal.binding.model.api.AnnotationType
 
 /**
- * Template for generating JAVA interfaces. 
+ * Template for generating JAVA interfaces.
  */
 class InterfaceTemplate extends BaseTemplate {
-    
+
     /**
      * List of constant instances which are generated as JAVA public static final attributes.
      */
     val List<Constant> consts
-    
+
     /**
      * List of method signatures which are generated as method declarations.
      */
     val List<MethodSignature> methods
-    
+
     /**
      * List of enumeration which are generated as JAVA enum type.
      */
     val List<Enumeration> enums
-    
+
     /**
      * List of generated types which are enclosed inside <code>genType</code>
      */
     val List<GeneratedType> enclosedGeneratedTypes
-    
+
     /**
-     * Creates the instance of this class which is used for generating the interface file source 
+     * Creates the instance of this class which is used for generating the interface file source
      * code from <code>genType</code>.
-     * 
+     *
      * @throws IllegalArgumentException if <code>genType</code> equals <code>null</code>
      */
     new(GeneratedType genType) {
@@ -51,16 +51,16 @@ class InterfaceTemplate extends BaseTemplate {
         if (genType == null) {
             throw new IllegalArgumentException("Generated type reference cannot be NULL!")
         }
-        
+
         consts = genType.constantDefinitions
         methods = genType.methodDefinitions
         enums = genType.enumerations
         enclosedGeneratedTypes = genType.enclosedTypes
     }
-    
+
     /**
      * Template method which generate the whole body of the interface.
-     * 
+     *
      * @return string with code for interface body in JAVA format
      */
     override body() '''
@@ -68,19 +68,19 @@ class InterfaceTemplate extends BaseTemplate {
         public interface Â«type.name»
             Â«superInterfaces»
         {
-        
+
             Â«generateInnerClasses»
-        
+
             Â«generateEnums»
-        
+
             Â«generateConstants»
-        
+
             Â«generateMethods»
-        
+
         }
-        
+
     '''
-   
+
 
     def private generateAnnotations(List<AnnotationType> annotations) '''
         Â«IF annotations != null && !annotations.empty»
@@ -99,10 +99,10 @@ class InterfaceTemplate extends BaseTemplate {
 
     /**
      * Template method which generates the interface name declaration.
-     * 
+     *
      * @return string with the code for the interface declaration in JAVA format
      */
-    def private superInterfaces() 
+    def private superInterfaces()
     '''
     Â«IF (!type.implements.empty)»
          extends
@@ -114,19 +114,19 @@ class InterfaceTemplate extends BaseTemplate {
 
     /**
      * Template method which generates inner classes inside this interface.
-     * 
+     *
      * @return string with the source code for inner classes in JAVA format
      */
     def private generateInnerClasses() '''
         Â«IF !enclosedGeneratedTypes.empty»
             Â«FOR innerClass : enclosedGeneratedTypes SEPARATOR "\n"»
                 Â«IF (innerClass instanceof GeneratedTransferObject)»
-                    Â«IF (innerClass as GeneratedTransferObject).unionType»
-                        Â«val unionTemplate = new UnionTemplate(innerClass as GeneratedTransferObject)»
+                    Â«IF innerClass.unionType»
+                        Â«val unionTemplate = new UnionTemplate(innerClass)»
                         Â«unionTemplate.generateAsInnerClass»
                         Â«this.importMap.putAll(unionTemplate.importMap)»
                     Â«ELSE»
-                        Â«val classTemplate = new ClassTemplate(innerClass as GeneratedTransferObject)»
+                        Â«val classTemplate = new ClassTemplate(innerClass)»
                         Â«classTemplate.generateAsInnerClass»
                         Â«this.importMap.putAll(classTemplate.importMap)»
                     Â«ENDIF»
@@ -138,9 +138,9 @@ class InterfaceTemplate extends BaseTemplate {
 
     /**
      * Template method which generates JAVA enum type.
-     * 
+     *
      * @return string with inner enum source code in JAVA format
-     */    
+     */
     def private generateEnums() '''
         Â«IF !enums.empty»
             Â«FOR e : enums SEPARATOR "\n"»
@@ -149,12 +149,12 @@ class InterfaceTemplate extends BaseTemplate {
             Â«ENDFOR»
         Â«ENDIF»
     '''
-    
+
     /**
      * Template method wich generates JAVA constants.
-     * 
-     * @return string with constants in JAVA format 
-     */    
+     *
+     * @return string with constants in JAVA format
+     */
     def private generateConstants() '''
         Â«IF !consts.empty»
             Â«FOR c : consts»
@@ -167,9 +167,9 @@ class InterfaceTemplate extends BaseTemplate {
 
     /**
      * Template method which generates the declaration of the methods.
-     * 
-     * @return string with the declaration of methods source code in JAVA format 
-     */    
+     *
+     * @return string with the declaration of methods source code in JAVA format
+     */
     def private generateMethods() '''
         Â«IF !methods.empty»
             Â«FOR m : methods SEPARATOR "\n"»
index 1d8a156e2492f5ef7aacc0ed8a3faab0ac523704..78c2cd05253179c4bd7b3cc5b7329ef87e2509b8 100644 (file)
@@ -13,13 +13,13 @@ import org.opendaylight.yangtools.sal.binding.model.api.Enumeration
 import static org.opendaylight.yangtools.binding.generator.util.Types.*
 
 /**
- * Template for generating JAVA class. 
+ * Template for generating JAVA class.
  */
 class UnionTemplate extends ClassTemplate {
 
     /**
      * Creates instance of this class with concrete <code>genType</code>.
-     * 
+     *
      * @param genType generated transfer object which will be transformed to JAVA class source code
      */
     new(GeneratedTransferObject genType) {
@@ -44,12 +44,12 @@ class UnionTemplate extends ClassTemplate {
             Â«IF isCharArray»
                 /**
                  * Constructor provided only for using in JMX. Don't use it for
-                 * construction new object of this union type. 
+                 * construction new object of this union type.
                  */
                 @«ConstructorProperties.importedName»("«property.name»")
                 public Â«type.name»(«propRet.importedName» Â«property.fieldName») {
                     Â«String.importedName» defVal = new Â«String.importedName»(«property.fieldName»);
-                    Â«type.name» defInst = Â«type.name»Builder.getDefaultInstance(defVal);
+                    Â«type.name» defInst = Â«typeBuilder()».getDefaultInstance(defVal);
                     Â«FOR other : finalProperties»
                         Â«IF other.name.equals("value")»
                             Â«IF other.returnType.importedName.contains("[]")»
@@ -84,10 +84,10 @@ class UnionTemplate extends ClassTemplate {
                                     this.«other.fieldName» = Â«property.fieldName».getValue();
                                 Â«ELSEIF propRet instanceof GeneratedTransferObject // Is it a GeneratedTransferObject
                                         && (propRet as GeneratedTransferObject).typedef  // Is it a typedef
-                                        && (propRet as GeneratedTransferObject).properties != null 
-                                        && !(propRet as GeneratedTransferObject).properties.empty 
-                                        && ((propRet as GeneratedTransferObject).properties.size == 1) 
-                                        && (propRet as GeneratedTransferObject).properties.get(0).name.equals("value") 
+                                        && (propRet as GeneratedTransferObject).properties != null
+                                        && !(propRet as GeneratedTransferObject).properties.empty
+                                        && ((propRet as GeneratedTransferObject).properties.size == 1)
+                                        && (propRet as GeneratedTransferObject).properties.get(0).name.equals("value")
                                         && BOOLEAN.equals((propRet as GeneratedTransferObject).properties.get(0).returnType)» // And the property value is of type boolean
                                     Â«Â«Â« generated boolean typedef
                                     this.«other.fieldName» = Â«property.fieldName».isValue().toString().toCharArray();
@@ -104,6 +104,14 @@ class UnionTemplate extends ClassTemplate {
             Â«ENDIF»
         Â«ENDFOR»
     '''
+    
+    def typeBuilder() {
+        val outerCls = getOuterClassName(type);
+        if(outerCls !== null) {
+            return outerCls + type.name + "Builder"
+        }
+        return type.name + "Builder"
+    }
 
     private def unionConstructorsParentProperties() '''
         Â«FOR property : parentProperties SEPARATOR "\n"»
index 08f19bdd70d45d42a1f30168437ec47fed887cf3..64693702ff05b90f4fcd6f92e0e822385ed09d96 100644 (file)
@@ -20,7 +20,6 @@ import java.util.Map
 import java.util.Set
 import java.util.TreeMap
 
-import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil
 import org.opendaylight.yangtools.binding.generator.util.Types
 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType
 import org.opendaylight.yangtools.sal.binding.model.api.Type
@@ -33,7 +32,6 @@ import com.google.common.collect.ImmutableSet
 import static org.opendaylight.yangtools.yang.binding.BindingMapping.*
 import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider
 import com.google.common.base.Preconditions
-import org.opendaylight.yangtools.yang.binding.BindingMapping
 
 class YangModuleInfoTemplate {
 
@@ -51,7 +49,7 @@ class YangModuleInfoTemplate {
         Preconditions.checkArgument(module != null, "Module must not be null.");
         this.module = module
         this.ctx = ctx
-        _packageName = BindingGeneratorUtil.moduleNamespaceToPackageName(module);
+        _packageName = getRootPackageName(module.getQNameModule());
         _modelBindingProviderName = '''«packageName».«MODEL_BINDING_PROVIDER_CLASS_NAME»''';
     }
 
@@ -66,7 +64,7 @@ class YangModuleInfoTemplate {
                 Â«val DateFormat df = new SimpleDateFormat("yyyy-MM-dd")»
                 private final Â«String.importedName» revision = "«df.format(module.revision)»";
                 private final Â«String.importedName» resourcePath = "«sourcePath»";
-                
+
                 private final Â«Set.importedName»<YangModuleInfo> importedModules;
 
                 public static Â«YangModuleInfo.importedName» getInstance() {
@@ -114,15 +112,15 @@ class YangModuleInfoTemplate {
                                 Â«sorted.put(module.revision, module)»
                             Â«ENDIF»
                         Â«ENDFOR»
-                        set.add(«BindingGeneratorUtil.moduleNamespaceToPackageName(sorted.lastEntry().value)».«MODULE_INFO_CLASS_NAME».getInstance());
+                        set.add(«getRootPackageName(sorted.lastEntry().value.QNameModule)».«MODULE_INFO_CLASS_NAME».getInstance());
                     Â«ELSE»
-                        set.add(«BindingGeneratorUtil.moduleNamespaceToPackageName(ctx.findModuleByName(name, rev))».«MODULE_INFO_CLASS_NAME».getInstance());
+                        set.add(«getRootPackageName((ctx.findModuleByName(name, rev).QNameModule))».«MODULE_INFO_CLASS_NAME».getInstance());
                     Â«ENDIF»
                 Â«ENDFOR»
             Â«ENDIF»
             Â«IF !m.submodules.empty»
                 Â«FOR submodule : m.submodules»
-                    set.add(«BindingMapping.getClassName(submodule.name)»Info.getInstance());
+                    set.add(«getClassName(submodule.name)»Info.getInstance());
                 Â«ENDFOR»
             Â«ENDIF»
             Â«IF m.imports.empty && m.submodules.empty»
@@ -192,10 +190,10 @@ class YangModuleInfoTemplate {
         return "/" + module.moduleSourcePath.replace(java.io.File.separatorChar, '/')
     }
 
-    private def imports() ''' 
+    private def imports() '''
         Â«IF !importMap.empty»
             Â«FOR entry : importMap.entrySet»
-                Â«IF entry.value != BindingGeneratorUtil.moduleNamespaceToPackageName(module)»
+                Â«IF entry.value != getRootPackageName(module.QNameModule)»
                     import Â«entry.value».«entry.key»;
                 Â«ENDIF»
             Â«ENDFOR»
@@ -218,8 +216,7 @@ class YangModuleInfoTemplate {
             importMap.put(typeName, typePackageName);
         }
         if (type instanceof ParameterizedType) {
-            val ParameterizedType paramType = (type as ParameterizedType)
-            val Type[] params = paramType.getActualTypeArguments()
+            val Type[] params = type.getActualTypeArguments()
             if (params != null) {
                 for (Type param : params) {
                     putTypeIntoImports(param);
@@ -260,11 +257,10 @@ class YangModuleInfoTemplate {
 
     final def StringBuilder addActualTypeParameters(StringBuilder builder, Type type) {
         if (type instanceof ParameterizedType) {
-            val ParameterizedType pType = (type as ParameterizedType)
-            val Type[] pTypes = pType.getActualTypeArguments();
-            builder.append("<");
+            val Type[] pTypes = type.getActualTypeArguments();
+            builder.append('<');
             builder.append(getParameters(pTypes));
-            builder.append(">");
+            builder.append('>');
         }
         return builder;
     }
@@ -302,9 +298,9 @@ class YangModuleInfoTemplate {
 
     private def generateSubInfo(Module module) '''
         Â«FOR submodule : module.submodules»
-            private static final class Â«BindingMapping.getClassName(submodule.name)»Info implements Â«YangModuleInfo.importedName» {
+            private static final class Â«getClassName(submodule.name)»Info implements Â«YangModuleInfo.importedName» {
 
-                private static final Â«YangModuleInfo.importedName» INSTANCE = new Â«BindingMapping.getClassName(submodule.name)»Info();
+                private static final Â«YangModuleInfo.importedName» INSTANCE = new Â«getClassName(submodule.name)»Info();
 
                 private final Â«String.importedName» name = "«submodule.name»";
                 private final Â«String.importedName» namespace = "«submodule.namespace.toString»";
@@ -318,7 +314,7 @@ class YangModuleInfoTemplate {
                     return INSTANCE;
                 }
 
-                Â«classBody(submodule, BindingMapping.getClassName(submodule.name + "Info"))»
+                Â«classBody(submodule, getClassName(submodule.name + "Info"))»
             }
         Â«ENDFOR»
     '''
index 073f6a9d775aacc8de7e05350fe5f6550777f0ed..517382fa6fcea61329a4e29d0bc8a3c3b642f7c5 100644 (file)
@@ -27,6 +27,7 @@ import static org.opendaylight.yangtools.sal.java.api.generator.test.Compilation
 import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.cleanUp;
 import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.getSourceFiles;
 import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.testCompilation;
+
 import com.google.common.base.Predicate;
 import com.google.common.collect.Collections2;
 import com.google.common.collect.ImmutableSet;
@@ -87,11 +88,11 @@ public class CompilationTest extends BaseCompilationTest {
 
         // Test if all sources are generated
         File parent = new File(sourcesOutputDir, NS_TEST);
-        File keyArgs = new File(parent, "KeyArgs.java");
-        File links = new File(parent, "Links.java");
-        File linksBuilder = new File(parent, "LinksBuilder.java");
-        File linksKey = new File(parent, "LinksKey.java");
-        File testData = new File(parent, "TestData.java");
+        final File keyArgs = new File(parent, "KeyArgs.java");
+        final File links = new File(parent, "Links.java");
+        final File linksBuilder = new File(parent, "LinksBuilder.java");
+        final File linksKey = new File(parent, "LinksKey.java");
+        final File testData = new File(parent, "TestData.java");
         assertTrue(keyArgs.exists());
         assertTrue(links.exists());
         assertTrue(linksBuilder.exists());
@@ -100,13 +101,13 @@ public class CompilationTest extends BaseCompilationTest {
         assertFilesCount(parent, 6);
 
         parent = new File(sourcesOutputDir, NS_TEST + FS + "links");
-        File level = new File(parent, "Level.java");
-        File linkGroup = new File(parent, "LinkGroup.java");
-        File node = new File(parent, "Node.java");
-        File nodeBuilder = new File(parent, "NodeBuilder.java");
-        File nodeList = new File(parent, "NodeList.java");
-        File nodeListBuilder = new File(parent, "NodeListBuilder.java");
-        File nodesType = new File(parent, "NodesType.java");
+        final File level = new File(parent, "Level.java");
+        final File linkGroup = new File(parent, "LinkGroup.java");
+        final File node = new File(parent, "Node.java");
+        final File nodeBuilder = new File(parent, "NodeBuilder.java");
+        final File nodeList = new File(parent, "NodeList.java");
+        final File nodeListBuilder = new File(parent, "NodeListBuilder.java");
+        final File nodesType = new File(parent, "NodesType.java");
         assertTrue(level.exists());
         assertTrue(linkGroup.exists());
         assertTrue(node.exists());
@@ -119,10 +120,10 @@ public class CompilationTest extends BaseCompilationTest {
         // Test if sources are compilable
         testCompilation(sourcesOutputDir, compiledOutputDir);
 
-        ClassLoader loader = new URLClassLoader(new URL[] { compiledOutputDir.toURI().toURL() });
-        Class<?> keyArgsClass = Class.forName(BASE_PKG + ".urn.opendaylight.test.rev131008.KeyArgs", true, loader);
-        Class<?> linksClass = Class.forName(BASE_PKG + ".urn.opendaylight.test.rev131008.Links", true, loader);
-        Class<?> linksKeyClass = Class.forName(BASE_PKG + ".urn.opendaylight.test.rev131008.LinksKey", true, loader);
+        final ClassLoader loader = new URLClassLoader(new URL[] { compiledOutputDir.toURI().toURL() });
+        final Class<?> keyArgsClass = Class.forName(BASE_PKG + ".urn.opendaylight.test.rev131008.KeyArgs", true, loader);
+        final Class<?> linksClass = Class.forName(BASE_PKG + ".urn.opendaylight.test.rev131008.Links", true, loader);
+        final Class<?> linksKeyClass = Class.forName(BASE_PKG + ".urn.opendaylight.test.rev131008.LinksKey", true, loader);
 
         // Test generated 'grouping key-args'
         assertTrue(keyArgsClass.isInterface());
@@ -139,7 +140,7 @@ public class CompilationTest extends BaseCompilationTest {
         // Test list key constructor arguments ordering
         assertContainsConstructor(linksKeyClass, Byte.class, String.class, Integer.class);
         // Test serialVersionUID generation
-        Field suid = assertContainsField(linksKeyClass, "serialVersionUID", Long.TYPE);
+        final Field suid = assertContainsField(linksKeyClass, "serialVersionUID", Long.TYPE);
         suid.setAccessible(true);
         assertEquals(-8829501012356283881L, suid.getLong(null));
 
@@ -262,10 +263,10 @@ public class CompilationTest extends BaseCompilationTest {
 
         // Test if all sources were generated from 'module foo'
         File parent = new File(sourcesOutputDir, NS_FOO);
-        File fooListener = new File(parent, "FooListener.java");
+        final File fooListener = new File(parent, "FooListener.java");
         File pathAttributes = new File(parent, "PathAttributes.java");
-        File update = new File(parent, "Update.java");
-        File updateBuilder = new File(parent, "UpdateBuilder.java");
+        final File update = new File(parent, "Update.java");
+        final File updateBuilder = new File(parent, "UpdateBuilder.java");
         assertTrue(fooListener.exists());
         assertTrue(pathAttributes.exists());
         assertTrue(update.exists());
@@ -276,23 +277,23 @@ public class CompilationTest extends BaseCompilationTest {
         assertFilesCount(parent, 1);
         parent = new File(parent, "attributes");
         assertFilesCount(parent, 2);
-        File origin = new File(parent, "Origin.java");
-        File originBuilder = new File(parent, "OriginBuilder.java");
+        final File origin = new File(parent, "Origin.java");
+        final File originBuilder = new File(parent, "OriginBuilder.java");
         assertTrue(origin.exists());
         assertTrue(originBuilder.exists());
 
         parent = new File(sourcesOutputDir, NS_FOO + FS + "update");
         assertFilesCount(parent, 2);
         pathAttributes = new File(parent, "PathAttributes.java");
-        File pathAttributesBuilder = new File(parent, "PathAttributesBuilder.java");
+        final File pathAttributesBuilder = new File(parent, "PathAttributesBuilder.java");
         assertTrue(pathAttributes.exists());
         assertTrue(pathAttributesBuilder.exists());
 
         // Test if all sources were generated from 'module bar'
         parent = new File(sourcesOutputDir, NS_BAR);
-        File destination = new File(parent, "Destination.java");
-        File pathAttributes1 = new File(parent, "PathAttributes1.java");
-        File pathAttributes1Builder = new File(parent, "PathAttributes1Builder.java");
+        final File destination = new File(parent, "Destination.java");
+        final File pathAttributes1 = new File(parent, "PathAttributes1.java");
+        final File pathAttributes1Builder = new File(parent, "PathAttributes1Builder.java");
         assertTrue(destination.exists());
         assertTrue(pathAttributes1.exists());
         assertTrue(pathAttributes1Builder.exists());
@@ -300,15 +301,15 @@ public class CompilationTest extends BaseCompilationTest {
 
         parent = new File(sourcesOutputDir, NS_BAR + FS + "destination");
         assertFilesCount(parent, 2);
-        File destinationType = new File(parent, "DestinationType.java");
+        final File destinationType = new File(parent, "DestinationType.java");
         assertTrue(destinationType.exists());
 
         parent = new File(parent, "destination");
         assertFilesCount(parent, 1);
         parent = new File(parent, "type");
         assertFilesCount(parent, 2);
-        File destinationIpv4 = new File(parent, "DestinationIp.java");
-        File destinationIpv4Builder = new File(parent, "DestinationIpBuilder.java");
+        final File destinationIpv4 = new File(parent, "DestinationIp.java");
+        final File destinationIpv4Builder = new File(parent, "DestinationIpBuilder.java");
         assertTrue(destinationIpv4.exists());
         assertTrue(destinationIpv4Builder.exists());
 
@@ -317,8 +318,8 @@ public class CompilationTest extends BaseCompilationTest {
         parent = new File(parent, "path");
         assertFilesCount(parent, 1);
         parent = new File(parent, "attributes");
-        File mpUnreachNlri = new File(parent, "MpUnreachNlri.java");
-        File mpUnreachNlriBuilder = new File(parent, "MpUnreachNlriBuilder.java");
+        final File mpUnreachNlri = new File(parent, "MpUnreachNlri.java");
+        final File mpUnreachNlriBuilder = new File(parent, "MpUnreachNlriBuilder.java");
         assertTrue(mpUnreachNlri.exists());
         assertTrue(mpUnreachNlriBuilder.exists());
         assertFilesCount(parent, 3);
@@ -328,8 +329,8 @@ public class CompilationTest extends BaseCompilationTest {
         parent = new File(parent, "unreach");
         assertFilesCount(parent, 1);
         parent = new File(parent, "nlri");
-        File withdrawnRoutes = new File(parent, "WithdrawnRoutes.java");
-        File withdrawnRoutesBuilder = new File(parent, "WithdrawnRoutesBuilder.java");
+        final File withdrawnRoutes = new File(parent, "WithdrawnRoutes.java");
+        final File withdrawnRoutesBuilder = new File(parent, "WithdrawnRoutesBuilder.java");
         assertTrue(withdrawnRoutes.exists());
         assertTrue(withdrawnRoutesBuilder.exists());
         assertFilesCount(parent, 2);
@@ -337,7 +338,7 @@ public class CompilationTest extends BaseCompilationTest {
         // Test if all sources were generated from 'module baz'
         parent = new File(sourcesOutputDir, NS_BAZ);
         assertFilesCount(parent, 2);
-        File linkstateDestination = new File(parent, "LinkstateDestination.java");
+        final File linkstateDestination = new File(parent, "LinkstateDestination.java");
         assertTrue(linkstateDestination.exists());
 
         parent = new File(sourcesOutputDir, NS_BAZ + FS + "update");
@@ -359,28 +360,28 @@ public class CompilationTest extends BaseCompilationTest {
         parent = new File(parent, "destination");
         assertFilesCount(parent, 1);
         parent = new File(parent, "type");
-        File destinationLinkstate = new File(parent, "DestinationLinkstate.java");
-        File destinationLinkstateBuilder = new File(parent, "DestinationLinkstateBuilder.java");
+        final File destinationLinkstate = new File(parent, "DestinationLinkstate.java");
+        final File destinationLinkstateBuilder = new File(parent, "DestinationLinkstateBuilder.java");
         assertTrue(destinationLinkstate.exists());
         assertTrue(destinationLinkstateBuilder.exists());
         assertFilesCount(parent, 3);
         parent = new File(parent, "destination");
         assertFilesCount(parent, 1);
         parent = new File(parent, "linkstate");
-        File links = new File(parent, "Links.java");
-        File linksBuilder = new File(parent, "LinksBuilder.java");
+        final File links = new File(parent, "Links.java");
+        final File linksBuilder = new File(parent, "LinksBuilder.java");
         assertTrue(links.exists());
         assertTrue(linksBuilder.exists());
         assertFilesCount(parent, 3);
         parent = new File(parent, "links");
-        File source = new File(parent, "Source.java");
-        File sourceBuilder = new File(parent, "SourceBuilder.java");
+        final File source = new File(parent, "Source.java");
+        final File sourceBuilder = new File(parent, "SourceBuilder.java");
         assertTrue(source.exists());
         assertTrue(sourceBuilder.exists());
         assertFilesCount(parent, 3);
         parent = new File(parent, "source");
-        File address = new File(parent, "Address.java");
-        File addressBuilder = new File(parent, "AddressBuilder.java");
+        final File address = new File(parent, "Address.java");
+        final File addressBuilder = new File(parent, "AddressBuilder.java");
         assertTrue(address.exists());
         assertTrue(addressBuilder.exists());
         assertFilesCount(parent, 2);
@@ -400,24 +401,24 @@ public class CompilationTest extends BaseCompilationTest {
 
         generateTestSources("/compilation/leaf-return-types", sourcesOutputDir);
 
-        File parent = new File(sourcesOutputDir, NS_TEST);
+        final File parent = new File(sourcesOutputDir, NS_TEST);
         assertTrue(new File(parent, "TestData.java").exists());
         assertTrue(new File(parent, "Nodes.java").exists());
         assertTrue(new File(parent, "NodesBuilder.java").exists());
         assertTrue(new File(parent, "Alg.java").exists());
-        assertTrue(new File(parent, "IdUnionBuilder.java").exists());
+        assertTrue(new File(parent, "NodesIdUnionBuilder.java").exists());
         assertFilesCount(parent, 5);
 
         // Test if sources are compilable
         testCompilation(sourcesOutputDir, compiledOutputDir);
 
-        String pkg = BASE_PKG + ".urn.opendaylight.test.rev131008";
-        ClassLoader loader = new URLClassLoader(new URL[] { compiledOutputDir.toURI().toURL() });
-        Class<?> nodesClass = Class.forName(pkg + ".Nodes", true, loader);
-        Class<?> builderClass = Class.forName(pkg + ".NodesBuilder", true, loader);
+        final String pkg = BASE_PKG + ".urn.opendaylight.test.rev131008";
+        final ClassLoader loader = new URLClassLoader(new URL[] { compiledOutputDir.toURI().toURL() });
+        final Class<?> nodesClass = Class.forName(pkg + ".Nodes", true, loader);
+        final Class<?> builderClass = Class.forName(pkg + ".NodesBuilder", true, loader);
 
         // Test methods return type
-        byte[] b = new byte[] {};
+        final byte[] b = new byte[] {};
         assertContainsMethod(nodesClass, b.getClass(), "getIdBinary");
         assertContainsMethod(nodesClass, pkg + ".Nodes$IdBits", "getIdBits", loader);
         assertContainsMethod(nodesClass, Boolean.class, "isIdBoolean");
@@ -438,17 +439,17 @@ public class CompilationTest extends BaseCompilationTest {
         assertContainsMethod(nodesClass, BigInteger.class, "getIdU64");
         assertContainsMethod(nodesClass, pkg + ".Nodes$IdUnion", "getIdUnion", loader);
 
-        Object builderObj = builderClass.newInstance();
+        final Object builderObj = builderClass.newInstance();
 
         Method m = assertContainsMethod(builderClass, builderClass, "setIdBinary", b.getClass());
-        List<Range<Integer>> lengthConstraints = new ArrayList<>();
+        final List<Range<Integer>> lengthConstraints = new ArrayList<>();
         lengthConstraints.add(Range.closed(1, 10));
         Object arg = new byte[] {};
         String expectedMsg = String.format("Invalid length: %s, expected: %s.", arg, lengthConstraints);
         assertContainsRestrictionCheck(builderObj, m, expectedMsg, arg);
 
         m = assertContainsMethod(builderClass, builderClass, "setIdDecimal64", BigDecimal.class);
-        List<Range<BigDecimal>> rangeConstraints = new ArrayList<>();
+        final List<Range<BigDecimal>> rangeConstraints = new ArrayList<>();
         rangeConstraints.add(Range.closed(new BigDecimal("1.5"), new BigDecimal("5.5")));
         arg = new BigDecimal("1.4");
         expectedMsg = String.format("Invalid range: %s, expected: %s.", arg, rangeConstraints);
@@ -467,41 +468,41 @@ public class CompilationTest extends BaseCompilationTest {
         generateTestSources("/compilation/context-reference", sourcesOutputDir);
 
         // Test if all sources are generated
-        File fooParent = new File(sourcesOutputDir, NS_FOO);
+        final File fooParent = new File(sourcesOutputDir, NS_FOO);
         assertFilesCount(fooParent, 3);
         assertTrue(new File(fooParent, "FooData.java").exists());
         assertTrue(new File(fooParent, "Nodes.java").exists());
         assertTrue(new File(fooParent, "NodesBuilder.java").exists());
 
-        File barParent = new File(sourcesOutputDir, NS_BAR);
+        final File barParent = new File(sourcesOutputDir, NS_BAR);
         assertFilesCount(barParent, 1);
         assertTrue(new File(barParent, "IdentityClass.java").exists());
 
         // Test if sources are compilable
         testCompilation(sourcesOutputDir, compiledOutputDir);
 
-        ClassLoader loader = new URLClassLoader(new URL[] { compiledOutputDir.toURI().toURL() });
-        Class<?> nodesClass = Class.forName(BASE_PKG + ".urn.opendaylight.foo.rev131008.Nodes", true, loader);
-        Class<?> identityClass = Class
+        final ClassLoader loader = new URLClassLoader(new URL[] { compiledOutputDir.toURI().toURL() });
+        final Class<?> nodesClass = Class.forName(BASE_PKG + ".urn.opendaylight.foo.rev131008.Nodes", true, loader);
+        final Class<?> identityClass = Class
                 .forName(BASE_PKG + ".urn.opendaylight.bar.rev131008.IdentityClass", true, loader);
 
         // test identity
         try {
             identityClass.getConstructor();
-            Class<?> baseIdentity = Class.forName("org.opendaylight.yangtools.yang.binding.BaseIdentity", true, loader);
+            final Class<?> baseIdentity = Class.forName("org.opendaylight.yangtools.yang.binding.BaseIdentity", true, loader);
             assertEquals(baseIdentity, identityClass.getSuperclass());
-        } catch (NoSuchMethodException e) {
+        } catch (final NoSuchMethodException e) {
             throw new AssertionError("IdentityClass must have no-arg constructor");
         }
 
         // Test annotation
         try {
-            Method getId = nodesClass.getMethod("getId");
-            Annotation[] annotations = getId.getAnnotations();
+            final Method getId = nodesClass.getMethod("getId");
+            final Annotation[] annotations = getId.getAnnotations();
             assertEquals(1, annotations.length);
-            Annotation routingContext = annotations[0];
+            final Annotation routingContext = annotations[0];
             assertEquals(RoutingContext.class, routingContext.annotationType());
-        } catch (NoSuchMethodException e) {
+        } catch (final NoSuchMethodException e) {
             throw new AssertionError("Method getId() not found");
         }
 
@@ -575,10 +576,10 @@ public class CompilationTest extends BaseCompilationTest {
         // Test if sources are compilable
         testCompilation(sourcesOutputDir, compiledOutputDir);
 
-        ClassLoader loader = new URLClassLoader(new URL[] { compiledOutputDir.toURI().toURL() });
-        Class<?> outputActionClass = Class.forName(BASE_PKG
+        final ClassLoader loader = new URLClassLoader(new URL[] { compiledOutputDir.toURI().toURL() });
+        final Class<?> outputActionClass = Class.forName(BASE_PKG
                 + ".urn.test.foo.rev140717.action.action.output.action._case.OutputAction", true, loader);
-        Class<?> actionClass = Class.forName(BASE_PKG + ".urn.test.foo.rev140717.Action", true, loader);
+        final Class<?> actionClass = Class.forName(BASE_PKG + ".urn.test.foo.rev140717.Action", true, loader);
 
         // Test generated 'container output-action'
         assertTrue(outputActionClass.isInterface());
@@ -621,14 +622,14 @@ public class CompilationTest extends BaseCompilationTest {
             assertEquals(java.lang.Class.class, method.getReturnType());
             returnType = method.getGenericReturnType();
             assertTrue(returnType instanceof ParameterizedType);
-            ParameterizedType pt = (ParameterizedType) returnType;
-            java.lang.reflect.Type[] parameters = pt.getActualTypeArguments();
+            final ParameterizedType pt = (ParameterizedType) returnType;
+            final java.lang.reflect.Type[] parameters = pt.getActualTypeArguments();
             assertEquals(1, parameters.length);
-            java.lang.reflect.Type parameter = parameters[0];
+            final java.lang.reflect.Type parameter = parameters[0];
             assertTrue(parameter instanceof WildcardType);
-            WildcardType wildcardType = (WildcardType) parameter;
+            final WildcardType wildcardType = (WildcardType) parameter;
             assertEquals("? extends " + returnTypeStr, wildcardType.toString());
-        } catch (NoSuchMethodException e) {
+        } catch (final NoSuchMethodException e) {
             throw new AssertionError("Method '" + methodName + "' not found");
         }
     }
@@ -644,14 +645,14 @@ public class CompilationTest extends BaseCompilationTest {
             assertEquals(rawReturnType, method.getReturnType());
             returnType = method.getGenericReturnType();
             assertTrue(returnType instanceof ParameterizedType);
-            ParameterizedType pt = (ParameterizedType) returnType;
-            java.lang.reflect.Type[] parameters = pt.getActualTypeArguments();
+            final ParameterizedType pt = (ParameterizedType) returnType;
+            final java.lang.reflect.Type[] parameters = pt.getActualTypeArguments();
             assertEquals(1, parameters.length);
-            java.lang.reflect.Type parameter = parameters[0];
+            final java.lang.reflect.Type parameter = parameters[0];
             assertTrue(parameter instanceof WildcardType);
-            WildcardType wildcardType = (WildcardType) parameter;
+            final WildcardType wildcardType = (WildcardType) parameter;
             assertEquals("?", wildcardType.toString());
-        } catch (NoSuchMethodException e) {
+        } catch (final NoSuchMethodException e) {
             throw new AssertionError("Method '" + methodName + "' not found");
         }
     }
diff --git a/code-generator/binding-java-api-generator/src/test/java/org/opendaylight/yangtools/sal/java/api/generator/test/UnionTypedefUnusedImportTest.java b/code-generator/binding-java-api-generator/src/test/java/org/opendaylight/yangtools/sal/java/api/generator/test/UnionTypedefUnusedImportTest.java
new file mode 100644 (file)
index 0000000..39f3607
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.sal.java.api.generator.test;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.COMPILER_OUTPUT_PATH;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.FS;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.GENERATOR_OUTPUT_PATH;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.cleanUp;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.getSourceFiles;
+import static org.opendaylight.yangtools.sal.java.api.generator.test.CompilationTestUtils.testCompilation;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.nio.charset.Charset;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.HashSet;
+import java.util.List;
+import org.junit.Test;
+import org.opendaylight.yangtools.sal.binding.model.api.Type;
+import org.opendaylight.yangtools.sal.java.api.generator.GeneratorJavaFile;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+public class UnionTypedefUnusedImportTest extends BaseCompilationTest {
+
+    @Test
+    public void testUnionTypedefUnusedImport() throws Exception {
+        final File sourcesOutputDir = new File(GENERATOR_OUTPUT_PATH + FS + "union-typedef");
+        assertTrue("Failed to create test file '" + sourcesOutputDir + "'", sourcesOutputDir.mkdir());
+        final File compiledOutputDir = new File(COMPILER_OUTPUT_PATH + FS + "union-typedef");
+        assertTrue("Failed to create test file '" + compiledOutputDir + "'", compiledOutputDir.mkdir());
+
+        final List<File> sourceFiles = getSourceFiles("/compilation/union-typedef");
+        final SchemaContext context = parser.parseFiles(sourceFiles);
+        final List<Type> types = bindingGenerator.generateTypes(context);
+        final GeneratorJavaFile generator = new GeneratorJavaFile(new HashSet<>(types));
+        generator.generateToFile(sourcesOutputDir);
+        final boolean isUsedImport = containsImport("org.opendaylight.yang.gen.v1.org.opendaylight.yangtools.union.typedef.rev130208.TypedefUnion");
+        assertFalse(String.format("Class shouldn't contain import for this type '%s'", types.get(1).getName()),
+                isUsedImport);
+
+        testCompilation(sourcesOutputDir, compiledOutputDir);
+        cleanUp(sourcesOutputDir, compiledOutputDir);
+    }
+
+    private String readFile(String path, Charset encoding) throws IOException {
+        byte[] encoded = Files.readAllBytes(Paths.get(path));
+        return new String(encoded, encoding);
+    }
+
+    private boolean containsImport(final String fullImport) throws URISyntaxException, IOException {
+        final String filePath = GENERATOR_OUTPUT_PATH + FS + "union-typedef" + FS + "org" + FS + "opendaylight" + FS + "yang" + FS + "gen" + FS + "v1" + FS + "org" + FS + "opendaylight" + FS + "yangtools" + FS + "union" + FS + "typedef" + FS + "rev141124" + FS + "TypedefUnionBuilder.java";
+        final String fileContent = readFile(filePath, StandardCharsets.UTF_8);
+
+        if (fileContent.contains(fullImport)) {
+            return true;
+        }
+        return false;
+    }
+}
diff --git a/code-generator/binding-java-api-generator/src/test/resources/compilation/union-typedef/union-typedef-test.yang b/code-generator/binding-java-api-generator/src/test/resources/compilation/union-typedef/union-typedef-test.yang
new file mode 100644 (file)
index 0000000..b271f07
--- /dev/null
@@ -0,0 +1,19 @@
+module union-typedef-test {
+    yang-version 1;
+    namespace "org:opendaylight:yangtools:union:typedef";
+    prefix "tp";
+
+    description
+        "Test unused import";
+
+    revision "2014-11-24" {
+        reference "WILL BE DEFINED LATER";
+    }
+
+    typedef typedef-union {
+        type union {
+            type int32;
+            type string;
+        }
+    }
+}
\ No newline at end of file
index 2657fcbaba44475fbf96a0d3bed196656384ba2e..ece776fbcf1031470f52350e7d9efff7b2606cad 100644 (file)
@@ -9,17 +9,15 @@ package org.opendaylight.yangtools.sal.binding.yang.types;
 
 import com.google.common.collect.Maps;
 import com.google.common.collect.Sets;
-
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
@@ -149,8 +147,8 @@ public class GroupingDefinitionDependencySort {
         for (DataSchemaNode childNode : container.getChildNodes()) {
             if (childNode instanceof DataNodeContainer) {
                 ret.addAll(getAllUsesNodes((DataNodeContainer) childNode));
-            } else if (childNode instanceof ChoiceNode) {
-                Set<ChoiceCaseNode> cases = ((ChoiceNode) childNode).getCases();
+            } else if (childNode instanceof ChoiceSchemaNode) {
+                Set<ChoiceCaseNode> cases = ((ChoiceSchemaNode) childNode).getCases();
                 for (ChoiceCaseNode choiceCaseNode : cases) {
                     ret.addAll(getAllUsesNodes(choiceCaseNode));
                 }
index b393c13367806ea9fb7211e698906e569ebe421f..bd81da916adfac7030a676661ad17d8be34ba83e 100644 (file)
@@ -7,12 +7,10 @@
  */
 package org.opendaylight.yangtools.sal.binding.yang.types;
 
-import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.moduleNamespaceToPackageName;
 import static org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil.packageNameForGeneratedType;
 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNode;
 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findDataSchemaNodeForRelativeXPath;
 import static org.opendaylight.yangtools.yang.model.util.SchemaContextUtil.findParentModule;
-
 import com.google.common.base.Preconditions;
 import com.google.common.collect.Sets;
 import com.google.common.io.BaseEncoding;
@@ -201,7 +199,7 @@ public final class TypeProviderImpl implements TypeProvider {
             if (r != null && returnType instanceof GeneratedTransferObject) {
                 GeneratedTransferObject gto = (GeneratedTransferObject) returnType;
                 Module module = findParentModule(schemaContext, parentNode);
-                String basePackageName = moduleNamespaceToPackageName(module);
+                String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
                 String packageName = packageNameForGeneratedType(basePackageName, typeDefinition.getPath());
                 String genTOName = BindingMapping.getClassName(typedefName);
                 String name = packageName + "." + genTOName;
@@ -321,7 +319,7 @@ public final class TypeProviderImpl implements TypeProvider {
         }
         Preconditions.checkArgument(identity != null, "Target identity '" + baseIdQName + "' do not exists");
 
-        final String basePackageName = moduleNamespaceToPackageName(module);
+        final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
         final String packageName = packageNameForGeneratedType(basePackageName, identity.getPath());
         final String genTypeName = BindingMapping.getClassName(identity.getQName());
 
@@ -532,7 +530,7 @@ public final class TypeProviderImpl implements TypeProvider {
         final String enumerationName = BindingMapping.getClassName(enumName);
 
         Module module = findParentModule(schemaContext, parentNode);
-        final String basePackageName = moduleNamespaceToPackageName(module);
+        final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
 
         final EnumerationBuilderImpl enumBuilder = new EnumerationBuilderImpl(basePackageName, enumerationName);
         enumBuilder.setDescription(enumTypeDef.getDescription());
@@ -621,7 +619,7 @@ public final class TypeProviderImpl implements TypeProvider {
      */
     private void resolveTypeDefsFromContext() {
         final Set<Module> modules = schemaContext.getModules();
-        Preconditions.checkArgument(modules != null, "Sef of Modules cannot be NULL!");
+        Preconditions.checkArgument(modules != null, "Set of Modules cannot be NULL!");
         final Module[] modulesArray = new Module[modules.size()];
         int i = 0;
         for (Module modul : modules) {
@@ -635,8 +633,7 @@ public final class TypeProviderImpl implements TypeProvider {
             if (dateTypeMap == null) {
                 dateTypeMap = new HashMap<>();
             }
-            final Map<String, Type> typeMap = new HashMap<>();
-            dateTypeMap.put(module.getRevision(), typeMap);
+            dateTypeMap.put(module.getRevision(), Collections.<String, Type>emptyMap());
             genTypeDefsContextMap.put(module.getName(), dateTypeMap);
         }
 
@@ -644,7 +641,7 @@ public final class TypeProviderImpl implements TypeProvider {
             if (module == null) {
                 continue;
             }
-            final String basePackageName = moduleNamespaceToPackageName(module);
+            final String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
 
             final DataNodeIterator it = new DataNodeIterator(module);
             final List<TypeDefinition<?>> typeDefinitions = it.allTypedefs();
@@ -731,8 +728,12 @@ public final class TypeProviderImpl implements TypeProvider {
                 }
                 if (returnType != null) {
                     final Map<Date, Map<String, Type>> modulesByDate = genTypeDefsContextMap.get(moduleName);
-                    final Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
+                    Map<String, Type> typeMap = modulesByDate.get(moduleRevision);
                     if (typeMap != null) {
+                        if (typeMap.isEmpty()) {
+                            typeMap = new HashMap<>(4);
+                            modulesByDate.put(moduleRevision, typeMap);
+                        }
                         typeMap.put(typedefName, returnType);
                     }
                     return returnType;
@@ -1384,10 +1385,10 @@ public final class TypeProviderImpl implements TypeProvider {
             path.next();
             if (!(path.hasNext())) {
                 parentName = BindingMapping.getClassName(parent.getName()) + "Data";
-                String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
+                String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
                 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
             } else {
-                String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
+                String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
                 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
                 parentName = BindingMapping.getClassName(parent.getName());
                 className = packageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
@@ -1407,12 +1408,12 @@ public final class TypeProviderImpl implements TypeProvider {
             String className;
             if (type instanceof ExtendedType) {
                 Module m = getParentModule(type);
-                String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(m);
+                String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
                 String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
                 className = packageName + "." + BindingMapping.getClassName(typeQName);
             } else {
                 Module parentModule = getParentModule(node);
-                String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parentModule);
+                String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
                 String packageName = packageNameForGeneratedType(basePackageName, node.getPath());
                 className = packageName + "." + BindingMapping.getClassName(node.getQName());
             }
@@ -1451,7 +1452,7 @@ public final class TypeProviderImpl implements TypeProvider {
         if (type instanceof ExtendedType && !(base instanceof LeafrefTypeDefinition)
                 && !(base instanceof EnumerationType) && !(base instanceof UnionTypeDefinition)) {
             Module m = getParentModule(type);
-            String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(m);
+            String basePackageName = BindingMapping.getRootPackageName(m.getQNameModule());
             String packageName = packageNameForGeneratedType(basePackageName, type.getPath());
             String className = packageName + "." + BindingMapping.getClassName(typeQName);
             sb.insert(0, "new " + className + "(");
@@ -1577,7 +1578,7 @@ public final class TypeProviderImpl implements TypeProvider {
                 module = modules.iterator().next();
             }
 
-            String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(module);
+            String basePackageName = BindingMapping.getRootPackageName(module.getQNameModule());
             className = basePackageName + "." + BindingMapping.getClassName(typeQName);
         } else {
             Iterator<QName> path = node.getPath().getPathFromRoot().iterator();
@@ -1587,13 +1588,13 @@ public final class TypeProviderImpl implements TypeProvider {
                 Date revision = first.getRevision();
                 Module parent = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
                 parentName = BindingMapping.getClassName((parent).getName()) + "Data";
-                String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parent);
+                String basePackageName = BindingMapping.getRootPackageName(parent.getQNameModule());
                 className = basePackageName + "." + parentName + "." + BindingMapping.getClassName(node.getQName());
             } else {
                 URI namespace = first.getNamespace();
                 Date revision = first.getRevision();
                 Module parentModule = schemaContext.findModuleByNamespaceAndRevision(namespace, revision);
-                String basePackageName = BindingGeneratorUtil.moduleNamespaceToPackageName(parentModule);
+                String basePackageName = BindingMapping.getRootPackageName(parentModule.getQNameModule());
                 String packageName = packageNameForGeneratedType(basePackageName, node.getType().getPath());
                 className = packageName + "." + BindingMapping.getClassName(node.getQName());
             }
index 67a9e6f05ea0e2d4285dae55d976d6929fa6cb90..d7d20c1489e13b118f711b34815436f2cff7ae96 100644 (file)
             <artifactId>yang-data-api</artifactId>
         </dependency>
 
+        <dependency>
+            <groupId>org.apache.maven</groupId>
+            <artifactId>maven-core</artifactId>
+            <scope>provided</scope>
+        </dependency>
         <dependency>
             <groupId>org.sonatype.plexus</groupId>
             <artifactId>plexus-build-api</artifactId>
+            <scope>provided</scope>
         </dependency>
 
         <dependency>
index 62f628c50f5f23593d3672d948de69ad94d5a9f6..6cd4960c66203c16820024a5a2b707e3014d1bbb 100644 (file)
@@ -27,7 +27,7 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdent
 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode
 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
@@ -373,14 +373,12 @@ class GeneratorImpl {
         // find recursively
         for(child : childNodes) {
             if(child instanceof ContainerSchemaNode) {
-                val contChild = child as ContainerSchemaNode
-                val foundChild = findNodeInChildNodes(findingNode, contChild.childNodes)
+                val foundChild = findNodeInChildNodes(findingNode, child.childNodes)
                 if (foundChild != null)
                     return foundChild;
             }
             else if(child instanceof ListSchemaNode) {
-                val listChild = child as ListSchemaNode
-                val foundChild = findNodeInChildNodes(findingNode, listChild.childNodes)
+                val foundChild = findNodeInChildNodes(findingNode, child.childNodes)
                 if (foundChild != null)
                     return foundChild;
             }
@@ -408,27 +406,27 @@ class GeneratorImpl {
         return
         '''
         Â«IF child instanceof ContainerSchemaNode»
-            Â«printContainerNode(child as ContainerSchemaNode)»
+            Â«printContainerNode(child)»
         Â«ENDIF»
         Â«IF child instanceof AnyXmlSchemaNode»
-            Â«printAnyXmlNode(child as AnyXmlSchemaNode)»
+            Â«printAnyXmlNode(child)»
         Â«ENDIF»
         Â«IF child instanceof LeafSchemaNode»
-            Â«printLeafNode(child as LeafSchemaNode)»
+            Â«printLeafNode(child)»
         Â«ENDIF»
         Â«IF child instanceof LeafListSchemaNode»
-            Â«printLeafListNode(child as LeafListSchemaNode)»
+            Â«printLeafListNode(child)»
         Â«ENDIF»
         Â«IF child instanceof ListSchemaNode»
-            Â«printListNode(child as ListSchemaNode)»
+            Â«printListNode(child)»
         Â«ENDIF»
-        Â«IF child instanceof ChoiceNode»
-            Â«printChoiceNode(child as ChoiceNode)»
+        Â«IF child instanceof ChoiceSchemaNode»
+            Â«printChoiceNode(child)»
         Â«ENDIF»
         '''
     }
     
-    private def printChoiceNode(ChoiceNode child) {
+    private def printChoiceNode(ChoiceSchemaNode child) {
         val List<ChoiceCaseNode> cases = new ArrayList(child.cases);
         if(!cases.empty) {
             val ChoiceCaseNode aCase = cases.get(0)
@@ -757,7 +755,7 @@ class GeneratorImpl {
         Â«module.childNodes.treeSet(YangInstanceIdentifier.builder.build())»
     '''
 
-    private def dispatch CharSequence tree(ChoiceNode node,YangInstanceIdentifier path) '''
+    private def dispatch CharSequence tree(ChoiceSchemaNode node,YangInstanceIdentifier path) '''
         Â«node.nodeName» (choice)
         Â«casesTree(node.cases,path)»
     '''
@@ -846,36 +844,32 @@ class GeneratorImpl {
 
     def CharSequence printBaseInfo(SchemaNode node) {
         if(node instanceof LeafSchemaNode) {
-            val LeafSchemaNode leafNode = (node as LeafSchemaNode)
             return '''
                 Â«printInfo(node, "leaf")»
-                Â«listItem("type", typeAnchorLink(leafNode.type?.path, leafNode.type.QName.localName))»
-                Â«listItem("units", leafNode.units)»
-                Â«listItem("default", leafNode.^default)»
+                Â«listItem("type", typeAnchorLink(node.type?.path, node.type.QName.localName))»
+                Â«listItem("units", node.units)»
+                Â«listItem("default", node.^default)»
                 </ul>
             '''
         } else if(node instanceof LeafListSchemaNode) {
-            val LeafListSchemaNode leafListNode = (node as LeafListSchemaNode)
             return '''
                 Â«printInfo(node, "leaf-list")»
-                Â«listItem("type", leafListNode.type?.QName.localName)»
+                Â«listItem("type", node.type?.QName.localName)»
                 </ul>
             '''
         } else if(node instanceof ListSchemaNode) {
-            val ListSchemaNode listNode = (node as ListSchemaNode)
             return '''
                 Â«printInfo(node, "list")»
-                Â«FOR keyDef : listNode.keyDefinition»
+                Â«FOR keyDef : node.keyDefinition»
                     Â«listItem("key definition", keyDef.localName)»
                 Â«ENDFOR»
                 </ul>
             '''
-        } else if(node instanceof ChoiceNode) {
-            val ChoiceNode choiceNode = (node as ChoiceNode)
+        } else if(node instanceof ChoiceSchemaNode) {
             return '''
                 Â«printInfo(node, "choice")»
-                Â«listItem("default case", choiceNode.defaultCase)»
-                Â«FOR caseNode : choiceNode.cases»
+                Â«listItem("default case", node.defaultCase)»
+                Â«FOR caseNode : node.cases»
                     Â«caseNode.printSchemaNodeInfo»
                 Â«ENDFOR»
                 </ul>
@@ -915,9 +909,9 @@ class GeneratorImpl {
             Â«listItem("description", node.description)»
             Â«listItem("reference", node.reference)»
             Â«IF node instanceof DataSchemaNode»
-                Â«listItem("when condition", (node as DataSchemaNode).constraints.whenCondition?.toString)»
-                Â«listItem("min elements", (node as DataSchemaNode).constraints.minElements?.toString)»
-                Â«listItem("max elements", (node as DataSchemaNode).constraints.maxElements?.toString)»
+                Â«listItem("when condition", node.constraints.whenCondition?.toString)»
+                Â«listItem("min elements", node.constraints.minElements?.toString)»
+                Â«listItem("max elements", node.constraints.maxElements?.toString)»
             Â«ENDIF»
         '''
     }
@@ -950,7 +944,7 @@ class GeneratorImpl {
         val anyxmlNodes = nodes.filter(AnyXmlSchemaNode)
         val leafNodes = nodes.filter(LeafSchemaNode)
         val leafListNodes = nodes.filter(LeafListSchemaNode)
-        val choices = nodes.filter(ChoiceNode)
+        val choices = nodes.filter(ChoiceSchemaNode)
         val cases = nodes.filter(ChoiceCaseNode)
         val containers = nodes.filter(ContainerSchemaNode)
         val lists = nodes.filter(ListSchemaNode)
@@ -1081,7 +1075,7 @@ class GeneratorImpl {
         Â«node.childNodes.printChildren(level,newPath)»
     '''
 
-    private def dispatch CharSequence printInfo(ChoiceNode node, int level, YangInstanceIdentifier path) '''
+    private def dispatch CharSequence printInfo(ChoiceSchemaNode node, int level, YangInstanceIdentifier path) '''
         Â«val Set<DataSchemaNode> choiceCases = new HashSet(node.cases)»
         Â«choiceCases.printChildren(level,path)»
     '''
@@ -1180,18 +1174,17 @@ class GeneratorImpl {
     def asRestconfPath(YangInstanceIdentifier identifier) {
         val it = new StringBuilder();
         append(currentModule.name)
-        append(":")
+        append(':')
         var previous = false;
         for(arg : identifier.pathArguments) {
-            if(previous) append("/")
+            if(previous) append('/')
             append(arg.nodeType.localName);
             previous = true;
             if(arg instanceof NodeIdentifierWithPredicates) {
-                val nodeIdentifier = arg as NodeIdentifierWithPredicates;
-                for(qname : nodeIdentifier.getKeyValues.keySet) {
+                for(qname : arg.getKeyValues.keySet) {
                     append("/{");
                     append(qname.localName)
-                    append("}")
+                    append('}')
                 }
             }
         }
@@ -1211,7 +1204,7 @@ class GeneratorImpl {
 
         for (name : path) {
             if (parent instanceof DataNodeContainer) {
-                var SchemaNode node = (parent as DataNodeContainer).getDataChildByName(name)
+                var SchemaNode node = parent.getDataChildByName(name)
                 if (node == null && (parent instanceof Module)) {
                     val notifications = (parent as Module).notifications;
                     for (notification : notifications) {
@@ -1235,7 +1228,7 @@ class GeneratorImpl {
                 pathString.append(':')
                 pathString.append(name.localName)
                 pathString.append('/')
-                if(node instanceof ChoiceNode && dataNode !== null) {
+                if(node instanceof ChoiceSchemaNode && dataNode !== null) {
                     val DataSchemaNode caseNode = dataNode.childNodes.findFirst[DataSchemaNode e | e instanceof ChoiceCaseNode];
                     if(caseNode !== null) {
                         pathString.append("(case)");
@@ -1413,7 +1406,7 @@ class GeneratorImpl {
     '''
 
     private def String nodeSchemaPathToPath(DataSchemaNode node, Map<SchemaPath, DataSchemaNode> childNodes) {
-        if (node instanceof ChoiceNode || node instanceof ChoiceCaseNode) {
+        if (node instanceof ChoiceSchemaNode || node instanceof ChoiceCaseNode) {
             return null
         }
 
@@ -1429,7 +1422,7 @@ class GeneratorImpl {
             for (pathElement : path) {
                 actual.add(pathElement)
                 val DataSchemaNode nodeByPath = childNodes.get(SchemaPath.create(actual, absolute))
-                if (!(nodeByPath instanceof ChoiceNode) && !(nodeByPath instanceof ChoiceCaseNode)) {
+                if (!(nodeByPath instanceof ChoiceSchemaNode) && !(nodeByPath instanceof ChoiceCaseNode)) {
                     result.append(pathElement.localName)
                     if (i != path.size - 1) {
                         result.append("/")
@@ -1447,9 +1440,9 @@ class GeneratorImpl {
             if (node instanceof DataNodeContainer) {
                 collectChildNodes((node as DataNodeContainer).childNodes, destination)
             }
-            if (node instanceof ChoiceNode) {
+            if (node instanceof ChoiceSchemaNode) {
                 val List<DataSchemaNode> choiceCases = new ArrayList()
-                for (caseNode : (node as ChoiceNode).cases) {
+                for (caseNode : node.cases) {
                     choiceCases.add(caseNode)
                 }
                 collectChildNodes(choiceCases, destination)
index e860fc12ccd3936c8ee968498f216d1389b905bb..2a02f379462176bee9676b27db4680e6446c4018 100644 (file)
@@ -29,12 +29,12 @@ class WadlRestconfGenerator {
        
        File path
        static val BuildContext CTX = new DefaultBuildContext();
+       static val PATH_DELIMETER = '/'
        var SchemaContext context;
        var List<DataSchemaNode> configData;
        var List<DataSchemaNode> operationalData;
        var Module module;
        var List<LeafSchemaNode> pathListParams;
-       val PATH_DELIMETER = "/"
 
        new(File targetPath) {
                if (!targetPath.exists) targetPath.mkdirs
@@ -156,8 +156,7 @@ class WadlRestconfGenerator {
                var StringBuilder path = new StringBuilder
                path.append(schemaNode.QName.localName)
                if (schemaNode instanceof ListSchemaNode) {
-                       val listKeys = (schemaNode as ListSchemaNode).keyDefinition
-                       for (listKey : listKeys) {
+                       for (listKey : schemaNode.keyDefinition) {
                                pathListParams.add((schemaNode as DataNodeContainer).getDataChildByName(listKey) as LeafSchemaNode)
                                path.append(PATH_DELIMETER)
                                path.append('{')
index 3d2643e75b906788376f91728dfec2b0071a6d90..6d862f667510322cf84809552947cbb1802b054a 100644 (file)
                 <artifactId>yang-maven-plugin-spi</artifactId>
                 <version>${project.version}</version>
             </dependency>
+            <dependency>
+                <groupId>org.opendaylight.yangtools.model</groupId>
+                <artifactId>iana-if-type-2014-05-08</artifactId>
+                <version>2014.05.08.7-SNAPSHOT</version>
+            </dependency>
             <dependency>
                 <groupId>org.opendaylight.yangtools.model</groupId>
                 <artifactId>ietf-inet-types</artifactId>
                 <artifactId>ietf-yang-types-20130715</artifactId>
                 <version>2013.07.15.7-SNAPSHOT</version>
             </dependency>
+            <dependency>
+                <groupId>org.opendaylight.yangtools.model</groupId>
+                <artifactId>ietf-interfaces</artifactId>
+                <version>2014.05.08.7-SNAPSHOT</version>
+            </dependency>
             <dependency>
                 <groupId>org.opendaylight.yangtools.model</groupId>
                 <artifactId>ietf-restconf</artifactId>
                 <artifactId>ietf-topology-l3-unicast</artifactId>
                 <version>${ietf.topology.version}</version>
             </dependency>
-            <dependency>
-                <groupId>org.opendaylight.yangtools</groupId>
-                <artifactId>yang-data-composite-node</artifactId>
-                <version>${project.version}</version>
-            </dependency>
             <dependency>
                 <groupId>org.opendaylight.yangtools</groupId>
                 <artifactId>restconf-client-api</artifactId>
index 3af9851fa23f660c6ba1417a6b43a2f378fd18af..d59c952d30cbdf611cdfcb4c808d7df5d4b12c87 100644 (file)
     <version>0.7.0-SNAPSHOT</version>
     <packaging>jar</packaging>
 
-    <build>
-        <plugins>
-            <!-- generate dependencies versions -->
-            <plugin>
-                <artifactId>maven-dependency-plugin</artifactId>
-            </plugin>
-            <plugin>
-                <groupId>com.alexecollins.maven.plugin</groupId>
-                <artifactId>script-maven-plugin</artifactId>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.karaf.tooling</groupId>
-                <artifactId>karaf-maven-plugin</artifactId>
-            </plugin>
-            <plugin>
-                <groupId>org.codehaus.mojo</groupId>
-                <artifactId>build-helper-maven-plugin</artifactId>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-resources-plugin</artifactId>
-            </plugin>
-            <plugin>
-                <groupId>org.apache.maven.plugins</groupId>
-                <artifactId>maven-surefire-plugin</artifactId>
-                <configuration>
-                    <dependenciesToScan>
-                        <dependency>org.opendaylight.yangtools:features-test</dependency>
-                    </dependenciesToScan>
-                </configuration>
-            </plugin>
-        </plugins>
-    </build>
-
     <dependencyManagement>
         <dependencies>
             <dependency>
     </dependencyManagement>
 
     <dependencies>
+        <dependency>
+            <groupId>org.opendaylight.yangtools.model</groupId>
+            <artifactId>iana-if-type-2014-05-08</artifactId>
+        </dependency>
         <dependency>
             <groupId>org.opendaylight.yangtools.model</groupId>
             <artifactId>ietf-inet-types</artifactId>
         </dependency>
+        <dependency>
+            <groupId>org.opendaylight.yangtools.model</groupId>
+            <artifactId>ietf-interfaces</artifactId>
+        </dependency>
         <dependency>
             <groupId>org.opendaylight.yangtools.model</groupId>
             <artifactId>ietf-restconf</artifactId>
             <groupId>org.opendaylight.yangtools</groupId>
             <artifactId>yang-data-api</artifactId>
         </dependency>
-        <dependency>
-            <groupId>org.opendaylight.yangtools</groupId>
-            <artifactId>yang-data-composite-node</artifactId>
-        </dependency>
         <dependency>
             <groupId>org.opendaylight.yangtools</groupId>
             <artifactId>yang-data-impl</artifactId>
index 673c7bced9c22e87bec86988dd0442ccb674f07f..d4c94bec9ffe2555f1c3e974bf6f78e5971e765d 100644 (file)
@@ -21,7 +21,9 @@
 
     <feature name='odl-yangtools-models' version='${project.version}' description='OpenDaylight :: Yangtools :: Models'>
         <feature version='${project.version}'>odl-yangtools-binding</feature>
+        <bundle>mvn:org.opendaylight.yangtools.model/iana-if-type-2014-05-08/{{VERSION}}</bundle>
         <bundle>mvn:org.opendaylight.yangtools.model/ietf-inet-types/{{VERSION}}</bundle>
+        <bundle>mvn:org.opendaylight.yangtools.model/ietf-interfaces/{{VERSION}}</bundle>
         <bundle>mvn:org.opendaylight.yangtools.model/ietf-yang-types/{{VERSION}}</bundle>
         <bundle>mvn:org.opendaylight.yangtools.model/ietf-yang-types-20130715/{{VERSION}}</bundle>
         <bundle>mvn:org.opendaylight.yangtools.model/ietf-restconf/{{VERSION}}</bundle>
@@ -39,7 +41,6 @@
         <bundle>mvn:org.opendaylight.yangtools.thirdparty/antlr4-runtime-osgi-nohead/{{VERSION}}</bundle>
         <bundle>mvn:commons-io/commons-io/{{VERSION}}</bundle>
         <bundle>mvn:org.opendaylight.yangtools/yang-data-api/{{VERSION}}</bundle>
-        <bundle>mvn:org.opendaylight.yangtools/yang-data-composite-node/{{VERSION}}</bundle>
         <bundle>mvn:org.opendaylight.yangtools/yang-data-impl/{{VERSION}}</bundle>
         <bundle>mvn:org.opendaylight.yangtools/yang-data-operations/{{VERSION}}</bundle>
         <bundle>mvn:org.opendaylight.yangtools/yang-data-util/{{VERSION}}</bundle>
index d0e43ef25f2e4acf51af270696092dba4c700079..6341f11cfb30960cbbed594077692c14c13642d3 100644 (file)
                                         </goals>
                                      </pluginExecutionFilter>
                                      <action>
-                                         <ignore />
+                                         <execute/>
                                      </action>
                                  </pluginExecution>
                                  <pluginExecution>
index e10977b6de01ecd0c2254a0fd1c263f4088e8aac..4ec7c5f917b46813dea363f314fa6af7078e2ded 100644 (file)
@@ -7,12 +7,10 @@
  */
 package org.opendaylight.yangtools.util;
 
+import com.google.common.collect.ImmutableSet;
 import java.math.BigDecimal;
 import java.math.BigInteger;
-import java.util.Collections;
-import java.util.HashSet;
 import java.util.Set;
-
 import org.opendaylight.yangtools.concepts.Immutable;
 import org.opendaylight.yangtools.concepts.Mutable;
 
@@ -22,10 +20,9 @@ public final class Immutables {
         throw new UnsupportedOperationException("Helper class");
     }
 
-    public static final Set<Class<?>> KNOWN_IMMUTABLES = Immutables.<Class<?>> asHashSet(
-            //
+    public static final Set<Class<?>> KNOWN_IMMUTABLES = ImmutableSet.<Class<?>>of(
             Integer.class, Short.class, BigDecimal.class, BigInteger.class, Byte.class, Character.class, Double.class,
-            Float.class, String.class);
+            Float.class, String.class, Boolean.class, Void.class);
 
     /**
      * Determines if object is known to be immutable
@@ -52,13 +49,4 @@ public final class Immutables {
         }
         return false;
     }
-
-    @SafeVarargs
-    private static <E> Set<E> asHashSet(final E... list) {
-        HashSet<E> ret = new HashSet<>();
-        for (E e : list) {
-            ret.add(e);
-        }
-        return Collections.unmodifiableSet(ret);
-    }
 }
index a9970deee5100cfd2408f7f6bdbd9af84fdae014..e5c21c41614ce8933d860c94d5a9ede90f27897a 100644 (file)
@@ -36,7 +36,7 @@ public final class LazyCollections {
         case 0:
             return Collections.singletonList(obj);
         case 1:
-            ret = new ArrayList<>();
+            ret = new ArrayList<>(2);
             ret.addAll(list);
             break;
         default:
diff --git a/common/util/src/main/java/org/opendaylight/yangtools/util/UnmodifiableCollection.java b/common/util/src/main/java/org/opendaylight/yangtools/util/UnmodifiableCollection.java
new file mode 100644 (file)
index 0000000..5b9d98a
--- /dev/null
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.util;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableCollection;
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.ImmutableSet.Builder;
+import com.google.common.collect.Iterators;
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Iterator;
+import javax.annotation.Nonnull;
+
+/**
+ * An unmodifiable view over a {@link Collection}. Unlike the view returned via
+ * {@link Collections#unmodifiableCollection(Collection)}, this class checks its
+ * argument to ensure multiple encapsulation does not occur.
+ *
+ * this class checks
+ * the argument so it prevents multiple encapsulation. Subclasses of
+ * {@link ImmutableCollection} are also recognized and not encapsulated.
+ * An attempt is also made to identi
+ *
+ * @param <E> the type of elements in this collection
+ */
+public final class UnmodifiableCollection<E> implements Collection<E>, Serializable {
+    private static final long serialVersionUID = 1L;
+    private static final Class<?> UNMODIFIABLE_COLLECTION_CLASS;
+    private static final Collection<Class<?>> SINGLETON_CLASSES;
+
+    static {
+        UNMODIFIABLE_COLLECTION_CLASS = Collections.unmodifiableCollection(new ArrayList<Object>()).getClass();
+
+        final Builder<Class<?>> b = ImmutableSet.builder();
+        b.add(Collections.singleton(null).getClass());
+        b.add(Collections.singletonList(null).getClass());
+        SINGLETON_CLASSES = b.build();
+    }
+
+    private final Collection<E> delegate;
+
+    private UnmodifiableCollection(final Collection<E> delegate) {
+        this.delegate = Preconditions.checkNotNull(delegate);
+    }
+
+    /**
+     * Create an unmodifiable view of the target collection. If the instance is known
+     * to be unmodifiable, that instance is returned.
+     *
+     * @param collection Target collection
+     * @return An unmodifiable view of the collection
+     */
+    public static <T> Collection<T> create(final @Nonnull Collection<T> collection) {
+        if (collection instanceof UnmodifiableCollection || collection instanceof ImmutableCollection ||
+                Collections.EMPTY_LIST == collection || Collections.EMPTY_SET == collection ||
+                UNMODIFIABLE_COLLECTION_CLASS.isInstance(collection) || SINGLETON_CLASSES.contains(collection.getClass())) {
+            return collection;
+        }
+
+        return new UnmodifiableCollection<>(collection);
+    }
+
+    @Override
+    public Iterator<E> iterator() {
+        return Iterators.unmodifiableIterator(delegate.iterator());
+    }
+
+    @Override
+    public int size() {
+        return delegate.size();
+    }
+
+    @Override
+    public boolean isEmpty() {
+        return delegate.isEmpty();
+    }
+
+    @Override
+    public boolean contains(final Object o) {
+        return delegate.contains(o);
+    }
+
+    @Override
+    public Object[] toArray() {
+        return delegate.toArray();
+    }
+
+    @Override
+    public <T> T[] toArray(final T[] a) {
+        return delegate.toArray(a);
+    }
+
+    @Override
+    public boolean containsAll(final Collection<?> c) {
+        return delegate.containsAll(c);
+    }
+
+    @Override
+    public boolean add(final E e) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public boolean addAll(final Collection<? extends E> c) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public boolean remove(final Object o) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public boolean removeAll(final Collection<?> c) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public boolean retainAll(final Collection<?> c) {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public void clear() {
+        throw new UnsupportedOperationException();
+    }
+
+    @Override
+    public String toString() {
+        final StringBuffer sb = new StringBuffer("UnmodifiableCollection{");
+        sb.append(delegate);
+        return sb.toString();
+    }
+}
index 932ed416bbf3bddf33528ba7290eb88b09d4e914..721d844fd660b44b019de88a405c8482e3e63aeb 100644 (file)
@@ -38,7 +38,6 @@ public class BundleStartTest {
         options.add(mavenBundle("ch.qos.logback", "logback-core").versionAsInProject());
         options.add(mavenBundle("ch.qos.logback", "logback-classic").versionAsInProject());
         options.add(mavenBundle("com.google.guava", "guava").versionAsInProject());
-        options.add(mavenBundle("commons-io", "commons-io").versionAsInProject());
         options.add(mavenBundle("org.apache.commons", "commons-lang3").versionAsInProject());
         options.add(mavenBundle("org.opendaylight.yangtools.thirdparty", "antlr4-runtime-osgi-nohead")
                 .versionAsInProject());
diff --git a/integration-test/yang-runtime-tests/src/test/java/org/opendaylight/yangtools/it/yang/runtime/tests/Bug466EmptyAugmentationCodecs.java b/integration-test/yang-runtime-tests/src/test/java/org/opendaylight/yangtools/it/yang/runtime/tests/Bug466EmptyAugmentationCodecs.java
deleted file mode 100644 (file)
index 3189025..0000000
+++ /dev/null
@@ -1,55 +0,0 @@
-package org.opendaylight.yangtools.it.yang.runtime.tests;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import javassist.ClassPool;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.test.regression.bug466.augmentation.empty.rev140226.Bug4661;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.test.regression.bug466.base.rev140226.Bug466;
-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.data.impl.codec.DataContainerCodec;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-
-import com.google.common.base.Optional;
-
-public class Bug466EmptyAugmentationCodecs {
-
-
-
-    private YangModuleInfo baseModuleInfo;
-    private YangModuleInfo augmentationModuleInfo;
-    private ModuleInfoBackedContext moduleInfoContext;
-    private RuntimeGeneratedMappingServiceImpl mappingService;
-    private Optional<SchemaContext> schemaContext;
-
-
-    @Before
-    public void setup()throws Exception {
-        baseModuleInfo = BindingReflections.getModuleInfo(Bug466.class);
-        augmentationModuleInfo = BindingReflections.getModuleInfo(Bug4661.class);
-
-        moduleInfoContext = ModuleInfoBackedContext.create();
-        moduleInfoContext.registerModuleInfo(baseModuleInfo);
-        moduleInfoContext.registerModuleInfo(augmentationModuleInfo);
-        schemaContext = moduleInfoContext.tryToCreateSchemaContext();
-        assertNotNull(schemaContext);
-        assertTrue(schemaContext.isPresent());
-
-        mappingService = new RuntimeGeneratedMappingServiceImpl(ClassPool.getDefault(), moduleInfoContext);
-        mappingService.onGlobalContextUpdated(schemaContext.get());
-
-    }
-
-
-    @Test
-    public void proactiveGenerationOfAugmentationCodecs() {
-        DataContainerCodec<Bug466> codec = mappingService.getCodecRegistry().getCodecForDataObject(Bug466.class);
-        assertNotNull(codec);
-    }
-
-}
index d75c5657bf1bceecc4be7925a286e9fbca481178..c36638463c07465f9ed6740ccb390806d9cbecfc 100644 (file)
@@ -26,7 +26,7 @@ import org.opendaylight.yangtools.sal.binding.generator.impl.BindingGeneratorImp
 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleContext;
 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
@@ -162,8 +162,8 @@ public class MultipleRevisionsSupportTest {
             for (DataSchemaNode child : ((DataNodeContainer) node).getChildNodes()) {
                 assertDeepRevision(revision, child);
             }
-        } else if (node instanceof ChoiceNode) {
-            for (DataSchemaNode child : ((ChoiceNode) node).getCases()) {
+        } else if (node instanceof ChoiceSchemaNode) {
+            for (DataSchemaNode child : ((ChoiceSchemaNode) node).getCases()) {
                 assertDeepRevision(revision, child);
             }
         }
diff --git a/integration-test/yang-runtime-tests/src/test/java/org/opendaylight/yangtools/it/yang/runtime/tests/RuntimeCodecAugmentationWithGroupingsAndCasesTest.java b/integration-test/yang-runtime-tests/src/test/java/org/opendaylight/yangtools/it/yang/runtime/tests/RuntimeCodecAugmentationWithGroupingsAndCasesTest.java
deleted file mode 100644 (file)
index a642b69..0000000
+++ /dev/null
@@ -1,77 +0,0 @@
-package org.opendaylight.yangtools.it.yang.runtime.tests;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import com.google.common.base.Optional;
-
-import java.util.AbstractMap.SimpleEntry;
-import java.util.Map.Entry;
-
-import javassist.ClassPool;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.extension.yang.ext.rev130709.RpcContextRef;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.test.regression.augmentation.base.rev140424.Choices;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.test.regression.augmentation.base.rev140424.grouping.GroupingDataBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.test.regression.augmentation.ext.rev140424.choices.augmentable.choice.ext.with.grouping.augmentations.ExtWithGroupingAugmentations;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.test.regression.augmentation.ext.rev140424.choices.augmentable.choice.ext.with.grouping.augmentations.ExtWithGroupingAugmentationsBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.test.regression.augmentation.ext.rev140424.choices.augmentable.choice.ext.with.grouping.augmentations.ext.with.grouping.augmentations.InUsesAugment;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.yang.test.regression.augmentation.ext.rev140424.choices.augmentable.choice.ext.with.grouping.augmentations.ext.with.grouping.augmentations.InUsesAugmentBuilder;
-import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
-import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
-import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-
-public class RuntimeCodecAugmentationWithGroupingsAndCasesTest {
-
-    private static final InstanceIdentifier<ExtWithGroupingAugmentations> GROUPING_AUGMENTATIONS_PATH = InstanceIdentifier
-            .builder(Choices.class).child(ExtWithGroupingAugmentations.class).build();
-
-    private ModuleInfoBackedContext moduleInfoContext;
-
-    private Optional<SchemaContext> schemaContext;
-
-    private RuntimeGeneratedMappingServiceImpl mappingService;
-
-
-    @Before
-    public void setUp() throws Exception {
-        YangModuleInfo yangExtInfo = BindingReflections.getModuleInfo(RpcContextRef.class);
-        YangModuleInfo baseModuleInfo = BindingReflections.getModuleInfo(Choices.class);
-        YangModuleInfo augmentationModuleInfo = BindingReflections.getModuleInfo(org.opendaylight.yang.gen.v1.urn.opendaylight.yang.test.regression.augmentation.ext.rev140424.choices.augmentable.choice.ext.with.grouping.augmentations.ExtWithGroupingAugmentations.class);
-
-        moduleInfoContext = ModuleInfoBackedContext.create();
-        moduleInfoContext.registerModuleInfo(yangExtInfo);
-        moduleInfoContext.registerModuleInfo(baseModuleInfo);
-        moduleInfoContext.registerModuleInfo(augmentationModuleInfo);
-
-        schemaContext = moduleInfoContext.tryToCreateSchemaContext();
-        assertNotNull(schemaContext);
-        assertTrue(schemaContext.isPresent());
-
-        mappingService = new RuntimeGeneratedMappingServiceImpl(ClassPool.getDefault(), moduleInfoContext);
-        mappingService.onGlobalContextUpdated(schemaContext.get());
-
-    }
-
-    @Test
-    public void testSerialization() {
-
-        ExtWithGroupingAugmentations caseData = new ExtWithGroupingAugmentationsBuilder() //
-        .setGroupingData(new GroupingDataBuilder() //
-        .addAugmentation(InUsesAugment.class, new InUsesAugmentBuilder() //
-        .setExtAumentation("InUses") //
-        .build()) //
-        .build()) //
-        .build();
-
-        Entry<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, CompositeNode> result = mappingService
-                .toDataDom(new SimpleEntry(GROUPING_AUGMENTATIONS_PATH, caseData));
-        assertNotNull(result);
-    }
-}
diff --git a/model/iana/iana-if-type-2014-05-08/pom.xml b/model/iana/iana-if-type-2014-05-08/pom.xml
new file mode 100644 (file)
index 0000000..979dfdf
--- /dev/null
@@ -0,0 +1,50 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- vi: set et smarttab sw=4 tabstop=4: -->
+<!--
+ Copyright (c) 2015 Ericsson India Global Services Pvt Ltd. and others.  All rights reserved.
+
+ This program and the accompanying materials are made available under the
+ terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ and is available at http://www.eclipse.org/legal/epl-v10.html
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+    <parent>
+        <artifactId>model-iana</artifactId>
+        <groupId>org.opendaylight.yangtools.model</groupId>
+        <version>0.7.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>iana-if-type-2014-05-08</artifactId>
+    <version>2014.05.08.7-SNAPSHOT</version>
+    <name>${project.artifactId}</name>
+    <description>${project.artifactId}</description>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.opendaylight.yangtools.model</groupId>
+            <artifactId>ietf-interfaces</artifactId>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <artifactId>maven-jar-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-Name>${project.groupId}.${project.artifactId}</Bundle-Name>
+                    </instructions>
+                </configuration>
+            </plugin>
+
+        </plugins>
+    </build>
+
+</project>
diff --git a/model/iana/iana-if-type-2014-05-08/src/main/yang/iana-if-type@2014-05-08.yang b/model/iana/iana-if-type-2014-05-08/src/main/yang/iana-if-type@2014-05-08.yang
new file mode 100644 (file)
index 0000000..5dd8219
--- /dev/null
@@ -0,0 +1,1547 @@
+module iana-if-type {
+  namespace "urn:ietf:params:xml:ns:yang:iana-if-type";
+  prefix ianaift;
+
+  import ietf-interfaces {
+    prefix if;
+  }
+
+  organization "IANA";
+  contact
+    "        Internet Assigned Numbers Authority
+
+     Postal: ICANN
+             4676 Admiralty Way, Suite 330
+             Marina del Rey, CA 90292
+
+     Tel:    +1 310 823 9358
+     <mailto:iana@iana.org>";
+  description
+    "This YANG module defines YANG identities for IANA-registered
+     interface types.
+
+     This YANG module is maintained by IANA and reflects the
+     'ifType definitions' registry.
+
+     The latest revision of this YANG module can be obtained from
+     the IANA web site.
+
+     Requests for new values should be made to IANA via
+     email (iana@iana.org).
+
+     Copyright (c) 2014 IETF Trust and the persons identified as
+     authors of the code.  All rights reserved.
+
+     Redistribution and use in source and binary forms, with or
+     without modification, is permitted pursuant to, and subject
+     to the license terms contained in, the Simplified BSD License
+     set forth in Section 4.c of the IETF Trust's Legal Provisions
+     Relating to IETF Documents
+     (http://trustee.ietf.org/license-info).
+
+     The initial version of this YANG module is part of RFC 7224;
+     see the RFC itself for full legal notices.";
+    reference
+      "IANA 'ifType definitions' registry.
+       <http://www.iana.org/assignments/smi-numbers>";
+
+  revision 2014-05-08 {
+    description
+      "Initial revision.";
+    reference
+      "RFC 7224: IANA Interface Type YANG Module";
+  }
+
+  identity iana-interface-type {
+    base if:interface-type;
+    description
+      "This identity is used as a base for all interface types
+       defined in the 'ifType definitions' registry.";
+  }
+
+
+
+
+
+
+  identity other {
+    base iana-interface-type;
+  }
+  identity regular1822 {
+    base iana-interface-type;
+  }
+  identity hdh1822 {
+    base iana-interface-type;
+  }
+  identity ddnX25 {
+    base iana-interface-type;
+  }
+  identity rfc877x25 {
+    base iana-interface-type;
+    reference
+      "RFC 1382 - SNMP MIB Extension for the X.25 Packet Layer";
+  }
+  identity ethernetCsmacd {
+    base iana-interface-type;
+    description
+      "For all Ethernet-like interfaces, regardless of speed,
+       as per RFC 3635.";
+    reference
+      "RFC 3635 - Definitions of Managed Objects for the
+                  Ethernet-like Interface Types";
+  }
+  identity iso88023Csmacd {
+    base iana-interface-type;
+    status deprecated;
+    description
+      "Deprecated via RFC 3635.
+       Use ethernetCsmacd(6) instead.";
+    reference
+      "RFC 3635 - Definitions of Managed Objects for the
+                  Ethernet-like Interface Types";
+  }
+  identity iso88024TokenBus {
+    base iana-interface-type;
+  }
+  identity iso88025TokenRing {
+    base iana-interface-type;
+  }
+  identity iso88026Man {
+    base iana-interface-type;
+  }
+  identity starLan {
+    base iana-interface-type;
+    status deprecated;
+    description
+      "Deprecated via RFC 3635.
+       Use ethernetCsmacd(6) instead.";
+    reference
+      "RFC 3635 - Definitions of Managed Objects for the
+                  Ethernet-like Interface Types";
+  }
+  identity proteon10Mbit {
+    base iana-interface-type;
+  }
+  identity proteon80Mbit {
+    base iana-interface-type;
+  }
+  identity hyperchannel {
+    base iana-interface-type;
+  }
+  identity fddi {
+    base iana-interface-type;
+    reference
+      "RFC 1512 - FDDI Management Information Base";
+  }
+  identity lapb {
+    base iana-interface-type;
+    reference
+      "RFC 1381 - SNMP MIB Extension for X.25 LAPB";
+  }
+  identity sdlc {
+    base iana-interface-type;
+  }
+  identity ds1 {
+    base iana-interface-type;
+    description
+      "DS1-MIB.";
+    reference
+      "RFC 4805 - Definitions of Managed Objects for the
+                  DS1, J1, E1, DS2, and E2 Interface Types";
+  }
+  identity e1 {
+    base iana-interface-type;
+    status obsolete;
+    description
+      "Obsolete; see DS1-MIB.";
+    reference
+      "RFC 4805 - Definitions of Managed Objects for the
+                  DS1, J1, E1, DS2, and E2 Interface Types";
+  }
+
+
+  identity basicISDN {
+    base iana-interface-type;
+    description
+      "No longer used.  See also RFC 2127.";
+  }
+  identity primaryISDN {
+    base iana-interface-type;
+    description
+      "No longer used.  See also RFC 2127.";
+  }
+  identity propPointToPointSerial {
+    base iana-interface-type;
+    description
+      "Proprietary serial.";
+  }
+  identity ppp {
+    base iana-interface-type;
+  }
+  identity softwareLoopback {
+    base iana-interface-type;
+  }
+  identity eon {
+    base iana-interface-type;
+    description
+      "CLNP over IP.";
+  }
+  identity ethernet3Mbit {
+    base iana-interface-type;
+  }
+  identity nsip {
+    base iana-interface-type;
+    description
+      "XNS over IP.";
+  }
+  identity slip {
+    base iana-interface-type;
+    description
+      "Generic SLIP.";
+  }
+  identity ultra {
+    base iana-interface-type;
+    description
+      "Ultra Technologies.";
+  }
+  identity ds3 {
+    base iana-interface-type;
+    description
+      "DS3-MIB.";
+    reference
+      "RFC 3896 - Definitions of Managed Objects for the
+                  DS3/E3 Interface Type";
+  }
+  identity sip {
+    base iana-interface-type;
+    description
+      "SMDS, coffee.";
+    reference
+      "RFC 1694 - Definitions of Managed Objects for SMDS
+                  Interfaces using SMIv2";
+  }
+  identity frameRelay {
+    base iana-interface-type;
+    description
+      "DTE only.";
+    reference
+      "RFC 2115 - Management Information Base for Frame Relay
+                  DTEs Using SMIv2";
+  }
+  identity rs232 {
+    base iana-interface-type;
+    reference
+      "RFC 1659 - Definitions of Managed Objects for RS-232-like
+                  Hardware Devices using SMIv2";
+  }
+  identity para {
+    base iana-interface-type;
+    description
+      "Parallel-port.";
+    reference
+      "RFC 1660 - Definitions of Managed Objects for
+                  Parallel-printer-like Hardware Devices using
+                  SMIv2";
+  }
+  identity arcnet {
+    base iana-interface-type;
+    description
+      "ARCnet.";
+  }
+  identity arcnetPlus {
+    base iana-interface-type;
+    description
+      "ARCnet Plus.";
+  }
+
+
+
+  identity atm {
+    base iana-interface-type;
+    description
+      "ATM cells.";
+  }
+  identity miox25 {
+    base iana-interface-type;
+    reference
+      "RFC 1461 - SNMP MIB extension for Multiprotocol
+                  Interconnect over X.25";
+  }
+  identity sonet {
+    base iana-interface-type;
+    description
+      "SONET or SDH.";
+  }
+  identity x25ple {
+    base iana-interface-type;
+    reference
+      "RFC 2127 - ISDN Management Information Base using SMIv2";
+  }
+  identity iso88022llc {
+    base iana-interface-type;
+  }
+  identity localTalk {
+    base iana-interface-type;
+  }
+  identity smdsDxi {
+    base iana-interface-type;
+  }
+  identity frameRelayService {
+    base iana-interface-type;
+    description
+      "FRNETSERV-MIB.";
+    reference
+      "RFC 2954 - Definitions of Managed Objects for Frame
+                  Relay Service";
+  }
+  identity v35 {
+    base iana-interface-type;
+  }
+  identity hssi {
+    base iana-interface-type;
+  }
+  identity hippi {
+    base iana-interface-type;
+  }
+
+  identity modem {
+    base iana-interface-type;
+    description
+      "Generic modem.";
+  }
+  identity aal5 {
+    base iana-interface-type;
+    description
+      "AAL5 over ATM.";
+  }
+  identity sonetPath {
+    base iana-interface-type;
+  }
+  identity sonetVT {
+    base iana-interface-type;
+  }
+  identity smdsIcip {
+    base iana-interface-type;
+    description
+      "SMDS InterCarrier Interface.";
+  }
+  identity propVirtual {
+    base iana-interface-type;
+    description
+      "Proprietary virtual/internal.";
+    reference
+      "RFC 2863 - The Interfaces Group MIB";
+  }
+  identity propMultiplexor {
+    base iana-interface-type;
+    description
+      "Proprietary multiplexing.";
+    reference
+      "RFC 2863 - The Interfaces Group MIB";
+  }
+  identity ieee80212 {
+    base iana-interface-type;
+    description
+      "100BaseVG.";
+  }
+  identity fibreChannel {
+    base iana-interface-type;
+    description
+      "Fibre Channel.";
+  }
+
+
+
+  identity hippiInterface {
+    base iana-interface-type;
+    description
+      "HIPPI interfaces.";
+  }
+  identity frameRelayInterconnect {
+    base iana-interface-type;
+    status obsolete;
+    description
+      "Obsolete; use either
+       frameRelay(32) or frameRelayService(44).";
+  }
+  identity aflane8023 {
+    base iana-interface-type;
+    description
+      "ATM Emulated LAN for 802.3.";
+  }
+  identity aflane8025 {
+    base iana-interface-type;
+    description
+      "ATM Emulated LAN for 802.5.";
+  }
+  identity cctEmul {
+    base iana-interface-type;
+    description
+      "ATM Emulated circuit.";
+  }
+  identity fastEther {
+    base iana-interface-type;
+    status deprecated;
+    description
+      "Obsoleted via RFC 3635.
+       ethernetCsmacd(6) should be used instead.";
+    reference
+      "RFC 3635 - Definitions of Managed Objects for the
+                  Ethernet-like Interface Types";
+  }
+  identity isdn {
+    base iana-interface-type;
+    description
+      "ISDN and X.25.";
+    reference
+      "RFC 1356 - Multiprotocol Interconnect on X.25 and ISDN
+                  in the Packet Mode";
+  }
+
+
+
+  identity v11 {
+    base iana-interface-type;
+    description
+      "CCITT V.11/X.21.";
+  }
+  identity v36 {
+    base iana-interface-type;
+    description
+      "CCITT V.36.";
+  }
+  identity g703at64k {
+    base iana-interface-type;
+    description
+      "CCITT G703 at 64Kbps.";
+  }
+  identity g703at2mb {
+    base iana-interface-type;
+    status obsolete;
+    description
+      "Obsolete; see DS1-MIB.";
+  }
+  identity qllc {
+    base iana-interface-type;
+    description
+      "SNA QLLC.";
+  }
+  identity fastEtherFX {
+    base iana-interface-type;
+    status deprecated;
+    description
+      "Obsoleted via RFC 3635.
+       ethernetCsmacd(6) should be used instead.";
+    reference
+      "RFC 3635 - Definitions of Managed Objects for the
+                  Ethernet-like Interface Types";
+  }
+  identity channel {
+    base iana-interface-type;
+    description
+      "Channel.";
+  }
+  identity ieee80211 {
+    base iana-interface-type;
+    description
+      "Radio spread spectrum.";
+  }
+  identity ibm370parChan {
+    base iana-interface-type;
+    description
+      "IBM System 360/370 OEMI Channel.";
+  }
+  identity escon {
+    base iana-interface-type;
+    description
+      "IBM Enterprise Systems Connection.";
+  }
+  identity dlsw {
+    base iana-interface-type;
+    description
+      "Data Link Switching.";
+  }
+  identity isdns {
+    base iana-interface-type;
+    description
+      "ISDN S/T interface.";
+  }
+  identity isdnu {
+    base iana-interface-type;
+    description
+      "ISDN U interface.";
+  }
+  identity lapd {
+    base iana-interface-type;
+    description
+      "Link Access Protocol D.";
+  }
+  identity ipSwitch {
+    base iana-interface-type;
+    description
+      "IP Switching Objects.";
+  }
+  identity rsrb {
+    base iana-interface-type;
+    description
+      "Remote Source Route Bridging.";
+  }
+  identity atmLogical {
+    base iana-interface-type;
+    description
+      "ATM Logical Port.";
+    reference
+      "RFC 3606 - Definitions of Supplemental Managed Objects
+                  for ATM Interface";
+  }
+  identity ds0 {
+    base iana-interface-type;
+    description
+      "Digital Signal Level 0.";
+    reference
+      "RFC 2494 - Definitions of Managed Objects for the DS0
+                  and DS0 Bundle Interface Type";
+  }
+  identity ds0Bundle {
+    base iana-interface-type;
+    description
+      "Group of ds0s on the same ds1.";
+    reference
+      "RFC 2494 - Definitions of Managed Objects for the DS0
+                  and DS0 Bundle Interface Type";
+  }
+  identity bsc {
+    base iana-interface-type;
+    description
+      "Bisynchronous Protocol.";
+  }
+  identity async {
+    base iana-interface-type;
+    description
+      "Asynchronous Protocol.";
+  }
+  identity cnr {
+    base iana-interface-type;
+    description
+      "Combat Net Radio.";
+  }
+  identity iso88025Dtr {
+    base iana-interface-type;
+    description
+      "ISO 802.5r DTR.";
+  }
+  identity eplrs {
+    base iana-interface-type;
+    description
+      "Ext Pos Loc Report Sys.";
+  }
+  identity arap {
+    base iana-interface-type;
+    description
+      "Appletalk Remote Access Protocol.";
+  }
+  identity propCnls {
+    base iana-interface-type;
+    description
+      "Proprietary Connectionless Protocol.";
+  }
+  identity hostPad {
+    base iana-interface-type;
+    description
+      "CCITT-ITU X.29 PAD Protocol.";
+  }
+  identity termPad {
+    base iana-interface-type;
+    description
+      "CCITT-ITU X.3 PAD Facility.";
+  }
+  identity frameRelayMPI {
+    base iana-interface-type;
+    description
+      "Multiproto Interconnect over FR.";
+  }
+  identity x213 {
+    base iana-interface-type;
+    description
+      "CCITT-ITU X213.";
+  }
+  identity adsl {
+    base iana-interface-type;
+    description
+      "Asymmetric Digital Subscriber Loop.";
+  }
+  identity radsl {
+    base iana-interface-type;
+    description
+      "Rate-Adapt. Digital Subscriber Loop.";
+  }
+  identity sdsl {
+    base iana-interface-type;
+    description
+      "Symmetric Digital Subscriber Loop.";
+  }
+  identity vdsl {
+    base iana-interface-type;
+    description
+      "Very H-Speed Digital Subscrib. Loop.";
+  }
+  identity iso88025CRFPInt {
+    base iana-interface-type;
+    description
+      "ISO 802.5 CRFP.";
+  }
+  identity myrinet {
+    base iana-interface-type;
+    description
+      "Myricom Myrinet.";
+  }
+  identity voiceEM {
+    base iana-interface-type;
+    description
+      "Voice recEive and transMit.";
+  }
+  identity voiceFXO {
+    base iana-interface-type;
+    description
+      "Voice Foreign Exchange Office.";
+  }
+  identity voiceFXS {
+    base iana-interface-type;
+    description
+      "Voice Foreign Exchange Station.";
+  }
+  identity voiceEncap {
+    base iana-interface-type;
+    description
+      "Voice encapsulation.";
+  }
+  identity voiceOverIp {
+    base iana-interface-type;
+    description
+      "Voice over IP encapsulation.";
+  }
+  identity atmDxi {
+    base iana-interface-type;
+    description
+      "ATM DXI.";
+  }
+  identity atmFuni {
+    base iana-interface-type;
+    description
+      "ATM FUNI.";
+  }
+  identity atmIma {
+    base iana-interface-type;
+    description
+      "ATM IMA.";
+  }
+  identity pppMultilinkBundle {
+    base iana-interface-type;
+    description
+      "PPP Multilink Bundle.";
+  }
+  identity ipOverCdlc {
+    base iana-interface-type;
+    description
+      "IBM ipOverCdlc.";
+  }
+  identity ipOverClaw {
+    base iana-interface-type;
+    description
+      "IBM Common Link Access to Workstn.";
+  }
+  identity stackToStack {
+    base iana-interface-type;
+    description
+      "IBM stackToStack.";
+  }
+  identity virtualIpAddress {
+    base iana-interface-type;
+    description
+      "IBM VIPA.";
+  }
+  identity mpc {
+    base iana-interface-type;
+    description
+      "IBM multi-protocol channel support.";
+  }
+  identity ipOverAtm {
+    base iana-interface-type;
+    description
+      "IBM ipOverAtm.";
+    reference
+      "RFC 2320 - Definitions of Managed Objects for Classical IP
+                  and ARP Over ATM Using SMIv2 (IPOA-MIB)";
+  }
+  identity iso88025Fiber {
+    base iana-interface-type;
+    description
+      "ISO 802.5j Fiber Token Ring.";
+  }
+  identity tdlc {
+    base iana-interface-type;
+    description
+      "IBM twinaxial data link control.";
+  }
+  identity gigabitEthernet {
+    base iana-interface-type;
+    status deprecated;
+
+
+    description
+      "Obsoleted via RFC 3635.
+       ethernetCsmacd(6) should be used instead.";
+    reference
+      "RFC 3635 - Definitions of Managed Objects for the
+                  Ethernet-like Interface Types";
+  }
+  identity hdlc {
+    base iana-interface-type;
+    description
+      "HDLC.";
+  }
+  identity lapf {
+    base iana-interface-type;
+    description
+      "LAP F.";
+  }
+  identity v37 {
+    base iana-interface-type;
+    description
+      "V.37.";
+  }
+  identity x25mlp {
+    base iana-interface-type;
+    description
+      "Multi-Link Protocol.";
+  }
+  identity x25huntGroup {
+    base iana-interface-type;
+    description
+      "X25 Hunt Group.";
+  }
+  identity transpHdlc {
+    base iana-interface-type;
+    description
+      "Transp HDLC.";
+  }
+  identity interleave {
+    base iana-interface-type;
+    description
+      "Interleave channel.";
+  }
+  identity fast {
+    base iana-interface-type;
+    description
+      "Fast channel.";
+  }
+
+  identity ip {
+    base iana-interface-type;
+    description
+      "IP (for APPN HPR in IP networks).";
+  }
+  identity docsCableMaclayer {
+    base iana-interface-type;
+    description
+      "CATV Mac Layer.";
+  }
+  identity docsCableDownstream {
+    base iana-interface-type;
+    description
+      "CATV Downstream interface.";
+  }
+  identity docsCableUpstream {
+    base iana-interface-type;
+    description
+      "CATV Upstream interface.";
+  }
+  identity a12MppSwitch {
+    base iana-interface-type;
+    description
+      "Avalon Parallel Processor.";
+  }
+  identity tunnel {
+    base iana-interface-type;
+    description
+      "Encapsulation interface.";
+  }
+  identity coffee {
+    base iana-interface-type;
+    description
+      "Coffee pot.";
+    reference
+      "RFC 2325 - Coffee MIB";
+  }
+  identity ces {
+    base iana-interface-type;
+    description
+      "Circuit Emulation Service.";
+  }
+  identity atmSubInterface {
+    base iana-interface-type;
+    description
+      "ATM Sub Interface.";
+  }
+
+  identity l2vlan {
+    base iana-interface-type;
+    description
+      "Layer 2 Virtual LAN using 802.1Q.";
+  }
+  identity l3ipvlan {
+    base iana-interface-type;
+    description
+      "Layer 3 Virtual LAN using IP.";
+  }
+  identity l3ipxvlan {
+    base iana-interface-type;
+    description
+      "Layer 3 Virtual LAN using IPX.";
+  }
+  identity digitalPowerline {
+    base iana-interface-type;
+    description
+      "IP over Power Lines.";
+  }
+  identity mediaMailOverIp {
+    base iana-interface-type;
+    description
+      "Multimedia Mail over IP.";
+  }
+  identity dtm {
+    base iana-interface-type;
+    description
+      "Dynamic synchronous Transfer Mode.";
+  }
+  identity dcn {
+    base iana-interface-type;
+    description
+      "Data Communications Network.";
+  }
+  identity ipForward {
+    base iana-interface-type;
+    description
+      "IP Forwarding Interface.";
+  }
+  identity msdsl {
+    base iana-interface-type;
+    description
+      "Multi-rate Symmetric DSL.";
+  }
+  identity ieee1394 {
+    base iana-interface-type;
+
+    description
+      "IEEE1394 High Performance Serial Bus.";
+  }
+  identity if-gsn {
+    base iana-interface-type;
+    description
+      "HIPPI-6400.";
+  }
+  identity dvbRccMacLayer {
+    base iana-interface-type;
+    description
+      "DVB-RCC MAC Layer.";
+  }
+  identity dvbRccDownstream {
+    base iana-interface-type;
+    description
+      "DVB-RCC Downstream Channel.";
+  }
+  identity dvbRccUpstream {
+    base iana-interface-type;
+    description
+      "DVB-RCC Upstream Channel.";
+  }
+  identity atmVirtual {
+    base iana-interface-type;
+    description
+      "ATM Virtual Interface.";
+  }
+  identity mplsTunnel {
+    base iana-interface-type;
+    description
+      "MPLS Tunnel Virtual Interface.";
+  }
+  identity srp {
+    base iana-interface-type;
+    description
+      "Spatial Reuse Protocol.";
+  }
+  identity voiceOverAtm {
+    base iana-interface-type;
+    description
+      "Voice over ATM.";
+  }
+  identity voiceOverFrameRelay {
+    base iana-interface-type;
+    description
+      "Voice Over Frame Relay.";
+  }
+  identity idsl {
+    base iana-interface-type;
+    description
+      "Digital Subscriber Loop over ISDN.";
+  }
+  identity compositeLink {
+    base iana-interface-type;
+    description
+      "Avici Composite Link Interface.";
+  }
+  identity ss7SigLink {
+    base iana-interface-type;
+    description
+      "SS7 Signaling Link.";
+  }
+  identity propWirelessP2P {
+    base iana-interface-type;
+    description
+      "Prop. P2P wireless interface.";
+  }
+  identity frForward {
+    base iana-interface-type;
+    description
+      "Frame Forward Interface.";
+  }
+  identity rfc1483 {
+    base iana-interface-type;
+    description
+      "Multiprotocol over ATM AAL5.";
+    reference
+      "RFC 1483 - Multiprotocol Encapsulation over ATM
+                  Adaptation Layer 5";
+  }
+  identity usb {
+    base iana-interface-type;
+    description
+      "USB Interface.";
+  }
+  identity ieee8023adLag {
+    base iana-interface-type;
+    description
+      "IEEE 802.3ad Link Aggregate.";
+  }
+  identity bgppolicyaccounting {
+    base iana-interface-type;
+    description
+      "BGP Policy Accounting.";
+  }
+  identity frf16MfrBundle {
+    base iana-interface-type;
+    description
+      "FRF.16 Multilink Frame Relay.";
+  }
+  identity h323Gatekeeper {
+    base iana-interface-type;
+    description
+      "H323 Gatekeeper.";
+  }
+  identity h323Proxy {
+    base iana-interface-type;
+    description
+      "H323 Voice and Video Proxy.";
+  }
+  identity mpls {
+    base iana-interface-type;
+    description
+      "MPLS.";
+  }
+  identity mfSigLink {
+    base iana-interface-type;
+    description
+      "Multi-frequency signaling link.";
+  }
+  identity hdsl2 {
+    base iana-interface-type;
+    description
+      "High Bit-Rate DSL - 2nd generation.";
+  }
+  identity shdsl {
+    base iana-interface-type;
+    description
+      "Multirate HDSL2.";
+  }
+  identity ds1FDL {
+    base iana-interface-type;
+    description
+      "Facility Data Link (4Kbps) on a DS1.";
+  }
+  identity pos {
+    base iana-interface-type;
+    description
+      "Packet over SONET/SDH Interface.";
+  }
+
+
+
+  identity dvbAsiIn {
+    base iana-interface-type;
+    description
+      "DVB-ASI Input.";
+  }
+  identity dvbAsiOut {
+    base iana-interface-type;
+    description
+      "DVB-ASI Output.";
+  }
+  identity plc {
+    base iana-interface-type;
+    description
+      "Power Line Communications.";
+  }
+  identity nfas {
+    base iana-interface-type;
+    description
+      "Non-Facility Associated Signaling.";
+  }
+  identity tr008 {
+    base iana-interface-type;
+    description
+      "TR008.";
+  }
+  identity gr303RDT {
+    base iana-interface-type;
+    description
+      "Remote Digital Terminal.";
+  }
+  identity gr303IDT {
+    base iana-interface-type;
+    description
+      "Integrated Digital Terminal.";
+  }
+  identity isup {
+    base iana-interface-type;
+    description
+      "ISUP.";
+  }
+  identity propDocsWirelessMaclayer {
+    base iana-interface-type;
+    description
+      "Cisco proprietary Maclayer.";
+  }
+
+
+
+  identity propDocsWirelessDownstream {
+    base iana-interface-type;
+    description
+      "Cisco proprietary Downstream.";
+  }
+  identity propDocsWirelessUpstream {
+    base iana-interface-type;
+    description
+      "Cisco proprietary Upstream.";
+  }
+  identity hiperlan2 {
+    base iana-interface-type;
+    description
+      "HIPERLAN Type 2 Radio Interface.";
+  }
+  identity propBWAp2Mp {
+    base iana-interface-type;
+    description
+      "PropBroadbandWirelessAccesspt2Multipt (use of this value
+       for IEEE 802.16 WMAN interfaces as per IEEE Std 802.16f
+       is deprecated, and ieee80216WMAN(237) should be used
+       instead).";
+  }
+  identity sonetOverheadChannel {
+    base iana-interface-type;
+    description
+      "SONET Overhead Channel.";
+  }
+  identity digitalWrapperOverheadChannel {
+    base iana-interface-type;
+    description
+      "Digital Wrapper.";
+  }
+  identity aal2 {
+    base iana-interface-type;
+    description
+      "ATM adaptation layer 2.";
+  }
+  identity radioMAC {
+    base iana-interface-type;
+    description
+      "MAC layer over radio links.";
+  }
+  identity atmRadio {
+    base iana-interface-type;
+    description
+      "ATM over radio links.";
+  }
+  identity imt {
+    base iana-interface-type;
+    description
+      "Inter-Machine Trunks.";
+  }
+  identity mvl {
+    base iana-interface-type;
+    description
+      "Multiple Virtual Lines DSL.";
+  }
+  identity reachDSL {
+    base iana-interface-type;
+    description
+      "Long Reach DSL.";
+  }
+  identity frDlciEndPt {
+    base iana-interface-type;
+    description
+      "Frame Relay DLCI End Point.";
+  }
+  identity atmVciEndPt {
+    base iana-interface-type;
+    description
+      "ATM VCI End Point.";
+  }
+  identity opticalChannel {
+    base iana-interface-type;
+    description
+      "Optical Channel.";
+  }
+  identity opticalTransport {
+    base iana-interface-type;
+    description
+      "Optical Transport.";
+  }
+  identity propAtm {
+    base iana-interface-type;
+    description
+      "Proprietary ATM.";
+  }
+  identity voiceOverCable {
+    base iana-interface-type;
+    description
+      "Voice Over Cable Interface.";
+  }
+
+
+
+  identity infiniband {
+    base iana-interface-type;
+    description
+      "Infiniband.";
+  }
+  identity teLink {
+    base iana-interface-type;
+    description
+      "TE Link.";
+  }
+  identity q2931 {
+    base iana-interface-type;
+    description
+      "Q.2931.";
+  }
+  identity virtualTg {
+    base iana-interface-type;
+    description
+      "Virtual Trunk Group.";
+  }
+  identity sipTg {
+    base iana-interface-type;
+    description
+      "SIP Trunk Group.";
+  }
+  identity sipSig {
+    base iana-interface-type;
+    description
+      "SIP Signaling.";
+  }
+  identity docsCableUpstreamChannel {
+    base iana-interface-type;
+    description
+      "CATV Upstream Channel.";
+  }
+  identity econet {
+    base iana-interface-type;
+    description
+      "Acorn Econet.";
+  }
+  identity pon155 {
+    base iana-interface-type;
+    description
+      "FSAN 155Mb Symetrical PON interface.";
+  }
+
+
+
+  identity pon622 {
+    base iana-interface-type;
+    description
+      "FSAN 622Mb Symetrical PON interface.";
+  }
+  identity bridge {
+    base iana-interface-type;
+    description
+      "Transparent bridge interface.";
+  }
+  identity linegroup {
+    base iana-interface-type;
+    description
+      "Interface common to multiple lines.";
+  }
+  identity voiceEMFGD {
+    base iana-interface-type;
+    description
+      "Voice E&M Feature Group D.";
+  }
+  identity voiceFGDEANA {
+    base iana-interface-type;
+    description
+      "Voice FGD Exchange Access North American.";
+  }
+  identity voiceDID {
+    base iana-interface-type;
+    description
+      "Voice Direct Inward Dialing.";
+  }
+  identity mpegTransport {
+    base iana-interface-type;
+    description
+      "MPEG transport interface.";
+  }
+  identity sixToFour {
+    base iana-interface-type;
+    status deprecated;
+    description
+      "6to4 interface (DEPRECATED).";
+    reference
+      "RFC 4087 - IP Tunnel MIB";
+  }
+  identity gtp {
+    base iana-interface-type;
+    description
+      "GTP (GPRS Tunneling Protocol).";
+  }
+  identity pdnEtherLoop1 {
+    base iana-interface-type;
+    description
+      "Paradyne EtherLoop 1.";
+  }
+  identity pdnEtherLoop2 {
+    base iana-interface-type;
+    description
+      "Paradyne EtherLoop 2.";
+  }
+  identity opticalChannelGroup {
+    base iana-interface-type;
+    description
+      "Optical Channel Group.";
+  }
+  identity homepna {
+    base iana-interface-type;
+    description
+      "HomePNA ITU-T G.989.";
+  }
+  identity gfp {
+    base iana-interface-type;
+    description
+      "Generic Framing Procedure (GFP).";
+  }
+  identity ciscoISLvlan {
+    base iana-interface-type;
+    description
+      "Layer 2 Virtual LAN using Cisco ISL.";
+  }
+  identity actelisMetaLOOP {
+    base iana-interface-type;
+    description
+      "Acteleis proprietary MetaLOOP High Speed Link.";
+  }
+  identity fcipLink {
+    base iana-interface-type;
+    description
+      "FCIP Link.";
+  }
+  identity rpr {
+    base iana-interface-type;
+    description
+      "Resilient Packet Ring Interface Type.";
+  }
+
+
+
+  identity qam {
+    base iana-interface-type;
+    description
+      "RF Qam Interface.";
+  }
+  identity lmp {
+    base iana-interface-type;
+    description
+      "Link Management Protocol.";
+    reference
+      "RFC 4327 - Link Management Protocol (LMP) Management
+                  Information Base (MIB)";
+  }
+  identity cblVectaStar {
+    base iana-interface-type;
+    description
+      "Cambridge Broadband Networks Limited VectaStar.";
+  }
+  identity docsCableMCmtsDownstream {
+    base iana-interface-type;
+    description
+      "CATV Modular CMTS Downstream Interface.";
+  }
+  identity adsl2 {
+    base iana-interface-type;
+    status deprecated;
+    description
+      "Asymmetric Digital Subscriber Loop Version 2
+       (DEPRECATED/OBSOLETED - please use adsl2plus(238)
+       instead).";
+    reference
+      "RFC 4706 - Definitions of Managed Objects for Asymmetric
+                  Digital Subscriber Line 2 (ADSL2)";
+  }
+  identity macSecControlledIF {
+    base iana-interface-type;
+    description
+      "MACSecControlled.";
+  }
+  identity macSecUncontrolledIF {
+    base iana-interface-type;
+    description
+      "MACSecUncontrolled.";
+  }
+  identity aviciOpticalEther {
+    base iana-interface-type;
+    description
+      "Avici Optical Ethernet Aggregate.";
+  }
+  identity atmbond {
+    base iana-interface-type;
+    description
+      "atmbond.";
+  }
+  identity voiceFGDOS {
+    base iana-interface-type;
+    description
+      "Voice FGD Operator Services.";
+  }
+  identity mocaVersion1 {
+    base iana-interface-type;
+    description
+      "MultiMedia over Coax Alliance (MoCA) Interface
+       as documented in information provided privately to IANA.";
+  }
+  identity ieee80216WMAN {
+    base iana-interface-type;
+    description
+      "IEEE 802.16 WMAN interface.";
+  }
+  identity adsl2plus {
+    base iana-interface-type;
+    description
+      "Asymmetric Digital Subscriber Loop Version 2 -
+       Version 2 Plus and all variants.";
+  }
+  identity dvbRcsMacLayer {
+    base iana-interface-type;
+    description
+      "DVB-RCS MAC Layer.";
+    reference
+      "RFC 5728 - The SatLabs Group DVB-RCS MIB";
+  }
+  identity dvbTdm {
+    base iana-interface-type;
+    description
+      "DVB Satellite TDM.";
+    reference
+      "RFC 5728 - The SatLabs Group DVB-RCS MIB";
+  }
+  identity dvbRcsTdma {
+    base iana-interface-type;
+    description
+      "DVB-RCS TDMA.";
+    reference
+      "RFC 5728 - The SatLabs Group DVB-RCS MIB";
+  }
+  identity x86Laps {
+    base iana-interface-type;
+    description
+      "LAPS based on ITU-T X.86/Y.1323.";
+  }
+  identity wwanPP {
+    base iana-interface-type;
+    description
+      "3GPP WWAN.";
+  }
+  identity wwanPP2 {
+    base iana-interface-type;
+    description
+      "3GPP2 WWAN.";
+  }
+  identity voiceEBS {
+    base iana-interface-type;
+    description
+      "Voice P-phone EBS physical interface.";
+  }
+  identity ifPwType {
+    base iana-interface-type;
+    description
+      "Pseudowire interface type.";
+    reference
+      "RFC 5601 - Pseudowire (PW) Management Information Base (MIB)";
+  }
+  identity ilan {
+    base iana-interface-type;
+    description
+      "Internal LAN on a bridge per IEEE 802.1ap.";
+  }
+  identity pip {
+    base iana-interface-type;
+    description
+      "Provider Instance Port on a bridge per IEEE 802.1ah PBB.";
+  }
+  identity aluELP {
+    base iana-interface-type;
+    description
+      "Alcatel-Lucent Ethernet Link Protection.";
+  }
+  identity gpon {
+    base iana-interface-type;
+    description
+      "Gigabit-capable passive optical networks (G-PON) as per
+       ITU-T G.948.";
+  }
+  identity vdsl2 {
+    base iana-interface-type;
+    description
+      "Very high speed digital subscriber line Version 2
+       (as per ITU-T Recommendation G.993.2).";
+    reference
+      "RFC 5650 - Definitions of Managed Objects for Very High
+                  Speed Digital Subscriber Line 2 (VDSL2)";
+  }
+  identity capwapDot11Profile {
+    base iana-interface-type;
+    description
+      "WLAN Profile Interface.";
+    reference
+      "RFC 5834 - Control and Provisioning of Wireless Access
+                  Points (CAPWAP) Protocol Binding MIB for
+                  IEEE 802.11";
+  }
+  identity capwapDot11Bss {
+    base iana-interface-type;
+    description
+      "WLAN BSS Interface.";
+    reference
+      "RFC 5834 - Control and Provisioning of Wireless Access
+                  Points (CAPWAP) Protocol Binding MIB for
+                  IEEE 802.11";
+  }
+  identity capwapWtpVirtualRadio {
+    base iana-interface-type;
+    description
+      "WTP Virtual Radio Interface.";
+    reference
+      "RFC 5833 - Control and Provisioning of Wireless Access
+                  Points (CAPWAP) Protocol Base MIB";
+  }
+  identity bits {
+    base iana-interface-type;
+    description
+      "bitsport.";
+  }
+  identity docsCableUpstreamRfPort {
+    base iana-interface-type;
+    description
+      "DOCSIS CATV Upstream RF Port.";
+  }
+
+
+  identity cableDownstreamRfPort {
+    base iana-interface-type;
+    description
+      "CATV downstream RF Port.";
+  }
+  identity vmwareVirtualNic {
+    base iana-interface-type;
+    description
+      "VMware Virtual Network Interface.";
+  }
+  identity ieee802154 {
+    base iana-interface-type;
+    description
+      "IEEE 802.15.4 WPAN interface.";
+    reference
+      "IEEE 802.15.4-2006";
+  }
+  identity otnOdu {
+    base iana-interface-type;
+    description
+      "OTN Optical Data Unit.";
+  }
+  identity otnOtu {
+    base iana-interface-type;
+    description
+      "OTN Optical channel Transport Unit.";
+  }
+  identity ifVfiType {
+    base iana-interface-type;
+    description
+      "VPLS Forwarding Instance Interface Type.";
+  }
+  identity g9981 {
+    base iana-interface-type;
+    description
+      "G.998.1 bonded interface.";
+  }
+  identity g9982 {
+    base iana-interface-type;
+    description
+      "G.998.2 bonded interface.";
+  }
+  identity g9983 {
+    base iana-interface-type;
+    description
+      "G.998.3 bonded interface.";
+  }
+
+  identity aluEpon {
+    base iana-interface-type;
+    description
+      "Ethernet Passive Optical Networks (E-PON).";
+  }
+  identity aluEponOnu {
+    base iana-interface-type;
+    description
+      "EPON Optical Network Unit.";
+  }
+  identity aluEponPhysicalUni {
+    base iana-interface-type;
+    description
+      "EPON physical User to Network interface.";
+  }
+  identity aluEponLogicalLink {
+    base iana-interface-type;
+    description
+      "The emulation of a point-to-point link over the EPON
+       layer.";
+  }
+  identity aluGponOnu {
+    base iana-interface-type;
+    description
+      "GPON Optical Network Unit.";
+    reference
+      "ITU-T G.984.2";
+  }
+  identity aluGponPhysicalUni {
+    base iana-interface-type;
+    description
+      "GPON physical User to Network interface.";
+    reference
+      "ITU-T G.984.2";
+  }
+  identity vmwareNicTeam {
+    base iana-interface-type;
+    description
+      "VMware NIC Team.";
+  }
+}
index 4894d42e722fb03e3d0bafeec52fbc8476011b7f..13eb5db290d5645de0684c1b0d80652b30e98234 100644 (file)
@@ -22,6 +22,7 @@
     <modules>
         <module>iana-afn-safi</module>
         <module>iana-if-type</module>
+        <module>iana-if-type-2014-05-08</module>
         <!-- 
         <module>ietf-topology-l3-unicast-igp</module>
         <module>ietf-topology-isis</module>
diff --git a/model/ietf/ietf-interfaces/pom.xml b/model/ietf/ietf-interfaces/pom.xml
new file mode 100644 (file)
index 0000000..4044cec
--- /dev/null
@@ -0,0 +1,54 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!-- vi: set et smarttab sw=4 tabstop=4: -->
+<!--
+ Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+
+ This program and the accompanying materials are made available under the
+ terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ and is available at http://www.eclipse.org/legal/epl-v10.html
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+
+    <parent>
+        <artifactId>model-ietf</artifactId>
+        <groupId>org.opendaylight.yangtools.model</groupId>
+        <version>0.7.0-SNAPSHOT</version>
+    </parent>
+
+    <modelVersion>4.0.0</modelVersion>
+    <artifactId>ietf-interfaces</artifactId>
+    <version>2014.05.08.7-SNAPSHOT</version>
+    <name>${project.artifactId}</name>
+    <description>${project.artifactId}</description>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.opendaylight.yangtools.model</groupId>
+            <artifactId>ietf-inet-types</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.opendaylight.yangtools.model</groupId>
+            <artifactId>ietf-yang-types</artifactId>
+        </dependency>
+    </dependencies>
+
+    <build>
+        <plugins>
+            <plugin>
+                <artifactId>maven-jar-plugin</artifactId>
+            </plugin>
+            <plugin>
+                <groupId>org.apache.felix</groupId>
+                <artifactId>maven-bundle-plugin</artifactId>
+                <extensions>true</extensions>
+                <configuration>
+                    <instructions>
+                        <Bundle-Name>${project.groupId}.${project.artifactId}</Bundle-Name>
+                    </instructions>
+                </configuration>
+            </plugin>
+
+        </plugins>
+    </build>
+
+</project>
diff --git a/model/ietf/ietf-interfaces/src/main/yang/ietf-interfaces.yang b/model/ietf/ietf-interfaces/src/main/yang/ietf-interfaces.yang
new file mode 100644 (file)
index 0000000..ad64425
--- /dev/null
@@ -0,0 +1,725 @@
+module ietf-interfaces {
+
+  namespace "urn:ietf:params:xml:ns:yang:ietf-interfaces";
+  prefix if;
+
+  import ietf-yang-types {
+    prefix yang;
+  }
+
+  organization
+    "IETF NETMOD (NETCONF Data Modeling Language) Working Group";
+
+  contact
+    "WG Web:   <http://tools.ietf.org/wg/netmod/>
+     WG List:  <mailto:netmod@ietf.org>
+
+     WG Chair: Thomas Nadeau
+               <mailto:tnadeau@lucidvision.com>
+
+     WG Chair: Juergen Schoenwaelder
+               <mailto:j.schoenwaelder@jacobs-university.de>
+
+     Editor:   Martin Bjorklund
+               <mailto:mbj@tail-f.com>";
+
+  description
+    "This module contains a collection of YANG definitions for
+     managing network interfaces.
+
+     Copyright (c) 2014 IETF Trust and the persons identified as
+     authors of the code.  All rights reserved.
+
+     Redistribution and use in source and binary forms, with or
+     without modification, is permitted pursuant to, and subject
+     to the license terms contained in, the Simplified BSD License
+     set forth in Section 4.c of the IETF Trust's Legal Provisions
+     Relating to IETF Documents
+     (http://trustee.ietf.org/license-info).
+
+     This version of this YANG module is part of RFC 7223; see
+     the RFC itself for full legal notices.";
+
+  revision 2014-05-08 {
+    description
+      "Initial revision.";
+    reference
+      "RFC 7223: A YANG Data Model for Interface Management";
+  }
+
+  /*
+   * Typedefs
+   */
+
+  typedef interface-ref {
+    type leafref {
+      path "/if:interfaces/if:interface/if:name";
+    }
+    description
+      "This type is used by data models that need to reference
+       configured interfaces.";
+  }
+
+  typedef interface-state-ref {
+    type leafref {
+      path "/if:interfaces-state/if:interface/if:name";
+    }
+    description
+      "This type is used by data models that need to reference
+       the operationally present interfaces.";
+  }
+
+  /*
+   * Identities
+   */
+
+  identity interface-type {
+    description
+      "Base identity from which specific interface types are
+       derived.";
+  }
+
+  /*
+   * Features
+   */
+
+  feature arbitrary-names {
+    description
+      "This feature indicates that the device allows user-controlled
+       interfaces to be named arbitrarily.";
+  }
+  feature pre-provisioning {
+    description
+      "This feature indicates that the device supports
+       pre-provisioning of interface configuration, i.e., it is
+       possible to configure an interface whose physical interface
+       hardware is not present on the device.";
+  }
+
+  feature if-mib {
+    description
+      "This feature indicates that the device implements
+       the IF-MIB.";
+    reference
+      "RFC 2863: The Interfaces Group MIB";
+  }
+
+  /*
+   * Configuration data nodes
+   */
+
+  container interfaces {
+    description
+      "Interface configuration parameters.";
+
+    list interface {
+      key "name";
+
+      description
+        "The list of configured interfaces on the device.
+
+         The operational state of an interface is available in the
+         /interfaces-state/interface list.  If the configuration of a
+         system-controlled interface cannot be used by the system
+         (e.g., the interface hardware present does not match the
+         interface type), then the configuration is not applied to
+         the system-controlled interface shown in the
+         /interfaces-state/interface list.  If the configuration
+         of a user-controlled interface cannot be used by the system,
+         the configured interface is not instantiated in the
+         /interfaces-state/interface list.";
+
+     leaf name {
+        type string;
+        description
+          "The name of the interface.
+
+           A device MAY restrict the allowed values for this leaf,
+           possibly depending on the type of the interface.
+           For system-controlled interfaces, this leaf is the
+           device-specific name of the interface.  The 'config false'
+           list /interfaces-state/interface contains the currently
+           existing interfaces on the device.
+
+           If a client tries to create configuration for a
+           system-controlled interface that is not present in the
+           /interfaces-state/interface list, the server MAY reject
+           the request if the implementation does not support
+           pre-provisioning of interfaces or if the name refers to
+           an interface that can never exist in the system.  A
+           NETCONF server MUST reply with an rpc-error with the
+           error-tag 'invalid-value' in this case.
+
+           If the device supports pre-provisioning of interface
+           configuration, the 'pre-provisioning' feature is
+           advertised.
+
+           If the device allows arbitrarily named user-controlled
+           interfaces, the 'arbitrary-names' feature is advertised.
+
+           When a configured user-controlled interface is created by
+           the system, it is instantiated with the same name in the
+           /interface-state/interface list.";
+      }
+
+      leaf description {
+        type string;
+        description
+          "A textual description of the interface.
+
+           A server implementation MAY map this leaf to the ifAlias
+           MIB object.  Such an implementation needs to use some
+           mechanism to handle the differences in size and characters
+           allowed between this leaf and ifAlias.  The definition of
+           such a mechanism is outside the scope of this document.
+
+           Since ifAlias is defined to be stored in non-volatile
+           storage, the MIB implementation MUST map ifAlias to the
+           value of 'description' in the persistently stored
+           datastore.
+
+           Specifically, if the device supports ':startup', when
+           ifAlias is read the device MUST return the value of
+           'description' in the 'startup' datastore, and when it is
+           written, it MUST be written to the 'running' and 'startup'
+           datastores.  Note that it is up to the implementation to
+
+           decide whether to modify this single leaf in 'startup' or
+           perform an implicit copy-config from 'running' to
+           'startup'.
+
+           If the device does not support ':startup', ifAlias MUST
+           be mapped to the 'description' leaf in the 'running'
+           datastore.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifAlias";
+      }
+
+      leaf type {
+        type identityref {
+          base interface-type;
+        }
+        mandatory true;
+        description
+          "The type of the interface.
+
+           When an interface entry is created, a server MAY
+           initialize the type leaf with a valid value, e.g., if it
+           is possible to derive the type from the name of the
+           interface.
+
+           If a client tries to set the type of an interface to a
+           value that can never be used by the system, e.g., if the
+           type is not supported or if the type does not match the
+           name of the interface, the server MUST reject the request.
+           A NETCONF server MUST reply with an rpc-error with the
+           error-tag 'invalid-value' in this case.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifType";
+      }
+
+      leaf enabled {
+        type boolean;
+        default "true";
+        description
+          "This leaf contains the configured, desired state of the
+           interface.
+
+           Systems that implement the IF-MIB use the value of this
+           leaf in the 'running' datastore to set
+           IF-MIB.ifAdminStatus to 'up' or 'down' after an ifEntry
+           has been initialized, as described in RFC 2863.
+
+
+
+           Changes in this leaf in the 'running' datastore are
+           reflected in ifAdminStatus, but if ifAdminStatus is
+           changed over SNMP, this leaf is not affected.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifAdminStatus";
+      }
+
+      leaf link-up-down-trap-enable {
+        if-feature if-mib;
+        type enumeration {
+          enum enabled {
+            value 1;
+          }
+          enum disabled {
+            value 2;
+          }
+        }
+        description
+          "Controls whether linkUp/linkDown SNMP notifications
+           should be generated for this interface.
+
+           If this node is not configured, the value 'enabled' is
+           operationally used by the server for interfaces that do
+           not operate on top of any other interface (i.e., there are
+           no 'lower-layer-if' entries), and 'disabled' otherwise.";
+        reference
+          "RFC 2863: The Interfaces Group MIB -
+                     ifLinkUpDownTrapEnable";
+      }
+    }
+  }
+
+  /*
+   * Operational state data nodes
+   */
+
+  container interfaces-state {
+    config false;
+    description
+      "Data nodes for the operational state of interfaces.";
+
+    list interface {
+      key "name";
+
+
+
+
+
+      description
+        "The list of interfaces on the device.
+
+         System-controlled interfaces created by the system are
+         always present in this list, whether they are configured or
+         not.";
+
+      leaf name {
+        type string;
+        description
+          "The name of the interface.
+
+           A server implementation MAY map this leaf to the ifName
+           MIB object.  Such an implementation needs to use some
+           mechanism to handle the differences in size and characters
+           allowed between this leaf and ifName.  The definition of
+           such a mechanism is outside the scope of this document.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifName";
+      }
+
+      leaf type {
+        type identityref {
+          base interface-type;
+        }
+        mandatory true;
+        description
+          "The type of the interface.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifType";
+      }
+
+      leaf admin-status {
+        if-feature if-mib;
+        type enumeration {
+          enum up {
+            value 1;
+            description
+              "Ready to pass packets.";
+          }
+          enum down {
+            value 2;
+            description
+              "Not ready to pass packets and not in some test mode.";
+          }
+
+
+
+          enum testing {
+            value 3;
+            description
+              "In some test mode.";
+          }
+        }
+        mandatory true;
+        description
+          "The desired state of the interface.
+
+           This leaf has the same read semantics as ifAdminStatus.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifAdminStatus";
+      }
+
+      leaf oper-status {
+        type enumeration {
+          enum up {
+            value 1;
+            description
+              "Ready to pass packets.";
+          }
+          enum down {
+            value 2;
+            description
+              "The interface does not pass any packets.";
+          }
+          enum testing {
+            value 3;
+            description
+              "In some test mode.  No operational packets can
+               be passed.";
+          }
+          enum unknown {
+            value 4;
+            description
+              "Status cannot be determined for some reason.";
+          }
+          enum dormant {
+            value 5;
+            description
+              "Waiting for some external event.";
+          }
+          enum not-present {
+            value 6;
+            description
+              "Some component (typically hardware) is missing.";
+          }
+          enum lower-layer-down {
+            value 7;
+            description
+              "Down due to state of lower-layer interface(s).";
+          }
+        }
+        mandatory true;
+        description
+          "The current operational state of the interface.
+
+           This leaf has the same semantics as ifOperStatus.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifOperStatus";
+      }
+
+      leaf last-change {
+        type yang:date-and-time;
+        description
+          "The time the interface entered its current operational
+           state.  If the current state was entered prior to the
+           last re-initialization of the local network management
+           subsystem, then this node is not present.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifLastChange";
+      }
+
+      leaf if-index {
+        if-feature if-mib;
+        type int32 {
+          range "1..2147483647";
+        }
+        mandatory true;
+        description
+          "The ifIndex value for the ifEntry represented by this
+           interface.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifIndex";
+      }
+
+      leaf phys-address {
+        type yang:phys-address;
+        description
+          "The interface's address at its protocol sub-layer.  For
+           example, for an 802.x interface, this object normally
+           contains a Media Access Control (MAC) address.  The
+           interface's media-specific modules must define the bit
+
+
+           and byte ordering and the format of the value of this
+           object.  For interfaces that do not have such an address
+           (e.g., a serial line), this node is not present.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifPhysAddress";
+      }
+
+      leaf-list higher-layer-if {
+        type interface-state-ref;
+        description
+          "A list of references to interfaces layered on top of this
+           interface.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifStackTable";
+      }
+
+      leaf-list lower-layer-if {
+        type interface-state-ref;
+        description
+          "A list of references to interfaces layered underneath this
+           interface.";
+        reference
+          "RFC 2863: The Interfaces Group MIB - ifStackTable";
+      }
+
+      leaf speed {
+        type yang:gauge64;
+        units "bits/second";
+        description
+            "An estimate of the interface's current bandwidth in bits
+             per second.  For interfaces that do not vary in
+             bandwidth or for those where no accurate estimation can
+             be made, this node should contain the nominal bandwidth.
+             For interfaces that have no concept of bandwidth, this
+             node is not present.";
+        reference
+          "RFC 2863: The Interfaces Group MIB -
+                     ifSpeed, ifHighSpeed";
+      }
+
+
+
+
+
+
+
+
+
+      container statistics {
+        description
+          "A collection of interface-related statistics objects.";
+
+        leaf discontinuity-time {
+          type yang:date-and-time;
+          mandatory true;
+          description
+            "The time on the most recent occasion at which any one or
+             more of this interface's counters suffered a
+             discontinuity.  If no such discontinuities have occurred
+             since the last re-initialization of the local management
+             subsystem, then this node contains the time the local
+             management subsystem re-initialized itself.";
+        }
+
+        leaf in-octets {
+          type yang:counter64;
+          description
+            "The total number of octets received on the interface,
+             including framing characters.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifHCInOctets";
+        }
+
+        leaf in-unicast-pkts {
+          type yang:counter64;
+          description
+            "The number of packets, delivered by this sub-layer to a
+             higher (sub-)layer, that were not addressed to a
+             multicast or broadcast address at this sub-layer.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifHCInUcastPkts";
+        }
+
+
+
+
+        leaf in-broadcast-pkts {
+          type yang:counter64;
+          description
+            "The number of packets, delivered by this sub-layer to a
+             higher (sub-)layer, that were addressed to a broadcast
+             address at this sub-layer.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB -
+                       ifHCInBroadcastPkts";
+        }
+
+        leaf in-multicast-pkts {
+          type yang:counter64;
+          description
+            "The number of packets, delivered by this sub-layer to a
+             higher (sub-)layer, that were addressed to a multicast
+             address at this sub-layer.  For a MAC-layer protocol,
+             this includes both Group and Functional addresses.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB -
+                       ifHCInMulticastPkts";
+        }
+
+        leaf in-discards {
+          type yang:counter32;
+          description
+            "The number of inbound packets that were chosen to be
+             discarded even though no errors had been detected to
+             prevent their being deliverable to a higher-layer
+             protocol.  One possible reason for discarding such a
+             packet could be to free up buffer space.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+
+
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifInDiscards";
+        }
+
+        leaf in-errors {
+          type yang:counter32;
+          description
+            "For packet-oriented interfaces, the number of inbound
+             packets that contained errors preventing them from being
+             deliverable to a higher-layer protocol.  For character-
+             oriented or fixed-length interfaces, the number of
+             inbound transmission units that contained errors
+             preventing them from being deliverable to a higher-layer
+             protocol.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifInErrors";
+        }
+
+        leaf in-unknown-protos {
+          type yang:counter32;
+          description
+            "For packet-oriented interfaces, the number of packets
+             received via the interface that were discarded because
+             of an unknown or unsupported protocol.  For
+             character-oriented or fixed-length interfaces that
+             support protocol multiplexing, the number of
+             transmission units received via the interface that were
+             discarded because of an unknown or unsupported protocol.
+             For any interface that does not support protocol
+             multiplexing, this counter is not present.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifInUnknownProtos";
+        }
+
+
+
+
+
+        leaf out-octets {
+          type yang:counter64;
+          description
+            "The total number of octets transmitted out of the
+             interface, including framing characters.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifHCOutOctets";
+        }
+
+        leaf out-unicast-pkts {
+          type yang:counter64;
+          description
+            "The total number of packets that higher-level protocols
+             requested be transmitted, and that were not addressed
+             to a multicast or broadcast address at this sub-layer,
+             including those that were discarded or not sent.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifHCOutUcastPkts";
+        }
+
+        leaf out-broadcast-pkts {
+          type yang:counter64;
+          description
+            "The total number of packets that higher-level protocols
+             requested be transmitted, and that were addressed to a
+             broadcast address at this sub-layer, including those
+             that were discarded or not sent.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB -
+                       ifHCOutBroadcastPkts";
+        }
+
+
+        leaf out-multicast-pkts {
+          type yang:counter64;
+          description
+            "The total number of packets that higher-level protocols
+             requested be transmitted, and that were addressed to a
+             multicast address at this sub-layer, including those
+             that were discarded or not sent.  For a MAC-layer
+             protocol, this includes both Group and Functional
+             addresses.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB -
+                       ifHCOutMulticastPkts";
+        }
+
+        leaf out-discards {
+          type yang:counter32;
+          description
+            "The number of outbound packets that were chosen to be
+             discarded even though no errors had been detected to
+             prevent their being transmitted.  One possible reason
+             for discarding such a packet could be to free up buffer
+             space.
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifOutDiscards";
+        }
+
+        leaf out-errors {
+          type yang:counter32;
+          description
+            "For packet-oriented interfaces, the number of outbound
+             packets that could not be transmitted because of errors.
+             For character-oriented or fixed-length interfaces, the
+             number of outbound transmission units that could not be
+             transmitted because of errors.
+
+
+
+
+             Discontinuities in the value of this counter can occur
+             at re-initialization of the management system, and at
+             other times as indicated by the value of
+             'discontinuity-time'.";
+          reference
+            "RFC 2863: The Interfaces Group MIB - ifOutErrors";
+        }
+      }
+    }
+  }
+}
index c11433446561f738641c037db4333cb0288c65be..a5103aa2a31efe6d05e04b39256aede8540688c6 100644 (file)
@@ -165,7 +165,12 @@ module network-topology  {
                 to provide room for augmentations, e.g. for
                 statistics or priorization information associated with
                 supporting nodes.";
-            key "node-ref";
+            // This is not what was published in the initial draft,
+            // added topology-ref leaf and added it to the key
+            key "topology-ref node-ref";
+            leaf topology-ref {
+                type topology-ref;
+            }
             leaf node-ref {
                 type node-ref;
             }
index fe4328cd0230a946799a825a4c19f9d3fab37894..5677b0c11bd687a46b0a487bc18a24d6f6242e6a 100644 (file)
@@ -23,6 +23,7 @@
 
     <modules>
         <module>ietf-inet-types</module>
+        <module>ietf-interfaces</module>
         <module>ietf-yang-types</module>
         <module>ietf-yang-types-20130715</module>
         <module>ietf-ted</module>
index d5b345336a4a3dbad7f66bfa128d47414dbf14e8..5002553f6cae8ee0edd919b9c3d6c00e9f627402 100644 (file)
@@ -9,20 +9,16 @@ package org.opendaylight.yangtools.restconf.client.api;
 
 import java.net.URL;
 import org.opendaylight.yangtools.restconf.client.api.auth.AuthenticationHolder;
-import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
 import org.opendaylight.yangtools.yang.model.api.SchemaContextHolder;
 
 /**
  * An interface for acquiring #{@link RestconfClientContext} instances.
  */
 public interface RestconfClientContextFactory {
-       /**
-        * Get a #{@link RestconfClientContext} attached to the server pointed to by an URL.
-        * @param baseUrl URL pointer to the backend server
-        * @return RestconfClientContext attached to the backend server.
-        * @throws UnsupportedProtocolException if the factory cannot handle the protocol specified in the URL.
-        */
-       RestconfClientContext getRestconfClientContext(URL baseUrl,BindingIndependentMappingService mappingService,SchemaContextHolder holder) throws UnsupportedProtocolException;
+
+    RestconfClientContext getRestconfClientContext(URL baseUrl, SchemaContextHolder schemaContextHolder)
+            throws UnsupportedProtocolException;
+
     void setAuthentication(AuthenticationHolder authenticationHolder);
 
 }
index ef5b56a5486cdc9d0dfac2da5ff9c0d007f5ccf8..fe46d36d92b218e7e7db529914e726635580ac11 100644 (file)
           <groupId>org.opendaylight.yangtools</groupId>
           <artifactId>yang-binding</artifactId>
       </dependency>
+      <dependency>
+          <groupId>org.opendaylight.yangtools</groupId>
+          <artifactId>binding-data-codec</artifactId>
+      </dependency>
       <dependency>
           <groupId>org.opendaylight.yangtools</groupId>
           <artifactId>restconf-util</artifactId>
index a3af69dcdad941d747ad6ba823c8d8269496c627..ce00e2c29585a2031d9624ed32e42f46499eb80f 100644 (file)
@@ -4,14 +4,16 @@ import com.google.common.base.Function;
 import com.google.common.base.Optional;
 import com.google.common.util.concurrent.ListenableFuture;
 import com.sun.jersey.api.client.ClientResponse;
+import java.io.InputStream;
 import java.util.Map.Entry;
+import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
 import org.opendaylight.yangtools.restconf.client.api.data.Datastore;
 import org.opendaylight.yangtools.restconf.client.api.data.DefaultRetrievalStrategy;
 import org.opendaylight.yangtools.restconf.client.api.data.RetrievalStrategy;
 import org.opendaylight.yangtools.restconf.utils.RestconfUtils;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
@@ -38,18 +40,19 @@ public abstract class AbstractDataStore implements Datastore {
             RetrievalStrategy strategy) {
 
         final SchemaContext schemaContext = client.getSchemaContext();
-        final BindingIndependentMappingService mappingService = client.getMappingService();
-        final Entry<String, DataSchemaNode> pathWithSchema = RestconfUtils.toRestconfIdentifier(path, mappingService, schemaContext);
+        final BindingNormalizedNodeCodecRegistry mappingService = client.getMappingService();
+        final YangInstanceIdentifier domPath = mappingService.toYangInstanceIdentifier(path);
+        final Entry<String, DataSchemaNode> pathWithSchema = RestconfUtils.toRestconfIdentifier(domPath,schemaContext);
         String restconfPath = getStorePrefix() + pathWithSchema.getKey();
 
         return client.get(restconfPath, "application/xml",new Function<ClientResponse, Optional<T>>() {
 
+            @SuppressWarnings("unchecked")
             @Override
             public com.google.common.base.Optional<T> apply(ClientResponse response) {
                 switch (response.getStatus()) {
                 case 200: // Status OK
-                    DataObject dataObject = RestconfUtils.dataObjectFromInputStream(path,
-                            response.getEntityInputStream(), schemaContext, mappingService,pathWithSchema.getValue());
+                    DataObject dataObject = deserialize(domPath,response.getEntityInputStream());
                     return (Optional<T>) Optional.of(dataObject);
                 case 404: // Status Not Found
                     return Optional.<T> absent();
@@ -57,9 +60,15 @@ public abstract class AbstractDataStore implements Datastore {
                     throw new IllegalStateException("Failed : HTTP error code : " + response.getStatus());
                 }
             }
+
+
         });
     }
 
+    protected final DataObject deserialize(YangInstanceIdentifier domPath, InputStream entityInputStream) {
+        throw new UnsupportedOperationException("Not implemented yet.");
+    }
+
     protected abstract String getStorePrefix();
 
 }
index 3d089625317497a4c212a1a707fc5ffa453c305d..aa5342c66b962ea83fd9f8bbf41f42a20844f9f1 100644 (file)
@@ -8,26 +8,23 @@
 package org.opendaylight.yangtools.restconf.client;
 
 import com.google.common.base.Function;
-import com.google.common.base.Optional;
 import com.sun.jersey.api.client.ClientResponse;
 import java.lang.reflect.InvocationHandler;
 import java.lang.reflect.Method;
 import java.lang.reflect.Proxy;
 import java.util.ArrayList;
 import java.util.List;
+import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
 import org.opendaylight.yangtools.restconf.client.to.RestRpcError;
 import org.opendaylight.yangtools.restconf.client.to.RestRpcResult;
 import org.opendaylight.yangtools.restconf.common.ResourceUri;
-import org.opendaylight.yangtools.restconf.utils.XmlTools;
 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.YangModuleInfo;
 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
 import org.opendaylight.yangtools.yang.common.RpcError;
-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.xml.XmlDocumentUtils;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
@@ -35,25 +32,24 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.w3c.dom.Document;
-import org.w3c.dom.ls.DOMImplementationLS;
-import org.w3c.dom.ls.LSSerializer;
 
 public class BindingToRestRpc implements InvocationHandler {
 
     private final RestconfClientImpl client;
     private static final Logger logger = LoggerFactory.getLogger(BindingToRestRpc.class);
-    private final BindingIndependentMappingService mappingService;
+    private final BindingNormalizedNodeCodecRegistry mappingService;
     private final SchemaContext schcemaContext;
     private final Module module;
 
-    public BindingToRestRpc(final Class<?> proxiedInterface,final BindingIndependentMappingService mappingService,final RestconfClientImpl client,final SchemaContext schemaContext) throws Exception {
-        this.mappingService = mappingService;
+    public BindingToRestRpc(final Class<?> proxiedInterface,final BindingNormalizedNodeCodecRegistry mappingService2,final RestconfClientImpl client,final SchemaContext schemaContext) throws Exception {
+        this.mappingService = mappingService2;
         this.client  = client;
         this.schcemaContext = schemaContext;
         YangModuleInfo moduleInfo = BindingReflections.getModuleInfo(proxiedInterface);
         this.module = schemaContext.findModuleByName(moduleInfo.getName(),org.opendaylight.yangtools.yang.common.QName.parseRevision(moduleInfo.getRevision()));
     }
 
+    @SuppressWarnings("unchecked")
     @Override
     public Object invoke(final Object o,final Method method, final Object[] objects) throws Exception {
         for (RpcDefinition rpcDef:module.getRpcs()){
@@ -63,15 +59,13 @@ public class BindingToRestRpc implements InvocationHandler {
                 String rpcMethodName = rpcDef.getQName().getLocalName();
                 Document rpcInputDoc = null;
                 for (Object component:objects){
-                    CompositeNode rpcInput = mappingService.toDataDom((DataObject) component);
-                    rpcInputDoc = XmlDocumentUtils.toDocument(rpcInput,rpcDef.getInput(),XmlDocumentUtils.defaultValueCodecProvider());
+                    ContainerNode rpcInput = mappingService.toNormalizedNodeRpcData((DataObject) component);
+
+                    // FIXME: NormalizedNodeXmlStreamWriter
+
                 }
-                DOMImplementationLS lsImpl = (DOMImplementationLS)rpcInputDoc.getImplementation().getFeature("LS", "3.0");
-                LSSerializer serializer = lsImpl.createLSSerializer();
-                serializer.getDomConfig().setParameter("xml-declaration", false);
 
-                String payloadString = serializer.writeToString(rpcInputDoc);
-                final Class<? extends DataContainer> desiredOutputClass = (Class<? extends DataContainer>)BindingReflections.resolveRpcOutputClass(method).get();
+                String payloadString = null;
                 final DataSchemaNode rpcOutputSchema = rpcDef.getOutput();
                 return client.post(ResourceUri.OPERATIONS.getPath() + "/" + moduleName + ":" + rpcMethodName,payloadString,new Function<ClientResponse, Object>() {
                     @Override
@@ -81,11 +75,8 @@ public class BindingToRestRpc implements InvocationHandler {
                         }
                         List<RpcError> errors =  new ArrayList<>();
                         try {
-                            Document rpcOutputDocument = XmlTools.fromXml(clientResponse.getEntityInputStream());
-                            CompositeNode cn = (CompositeNode) XmlDocumentUtils.toDomNode(rpcOutputDocument.getDocumentElement(),
-                                    Optional.of(rpcOutputSchema),
-                                    Optional.of(XmlDocumentUtils.defaultValueCodecProvider()));
-                            DataContainer rpcOutputDataObject = mappingService.dataObjectFromDataDom(desiredOutputClass, cn);
+                            ContainerNode output = null;
+                            DataContainer rpcOutputDataObject = mappingService.fromNormalizedNodeRpcData(rpcOutputSchema.getPath(), output);
                             return new RestRpcResult(true,rpcOutputDataObject);
                         } catch (Exception e) {
                             logger.trace("Error while extracting rpc output in proxy method {}",e);
@@ -100,15 +91,16 @@ public class BindingToRestRpc implements InvocationHandler {
         throw new IllegalStateException("Unexpected state of proxy method.");
     }
 
-    public static<T> T getProxy(final Class<T> proxiedInterface,
-                                final BindingIndependentMappingService mappingService,
+    @SuppressWarnings("unchecked")
+    public static<T> T getProxy(final Class<T> rpcService,
+                                final BindingNormalizedNodeCodecRegistry mappingService2,
                                 final RestconfClientImpl restconfClient,
                                 final SchemaContext schemaContext) {
         T proxiedType = null;
         try {
             proxiedType = (T) Proxy.newProxyInstance
                     (BindingToRestRpc.class.getClassLoader(),
-                            new Class[]{proxiedInterface}, new BindingToRestRpc(proxiedInterface, mappingService, restconfClient, schemaContext));
+                            new Class[]{rpcService}, new BindingToRestRpc(rpcService, mappingService2, restconfClient, schemaContext));
         } catch (Exception e) {
             throw new IllegalStateException(e.getMessage());
         }
index 4df049538b0dcc7e3fcb687d68e29d8cd133b7ae..309f3555651439c34345b6edb4902cff76ff7f46 100644 (file)
@@ -7,14 +7,15 @@
  */
 package org.opendaylight.yangtools.restconf.client;
 
+import com.google.common.base.Function;
+import com.google.common.base.Optional;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.sun.jersey.api.client.ClientResponse;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Map;
-import java.util.Map.Entry;
-import java.util.concurrent.Executors;
-
 import javax.ws.rs.core.MediaType;
-
+import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
 import org.opendaylight.yangtools.restconf.client.api.data.ConfigurationDatastore;
 import org.opendaylight.yangtools.restconf.client.to.RestRpcError;
 import org.opendaylight.yangtools.restconf.client.to.RestRpcResult;
@@ -24,21 +25,12 @@ 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.data.impl.codec.BindingIndependentMappingService;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
-import com.google.common.base.Function;
-import com.google.common.base.Optional;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
-import com.sun.jersey.api.client.ClientResponse;
-
 public class ConfigurationDataStoreImpl extends AbstractDataStore implements ConfigurationDatastore  {
 
-    private final ListeningExecutorService pool = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
-
     @Override
     protected String getStorePrefix() {
         return ResourceUri.CONFIG.getPath();
@@ -52,13 +44,14 @@ public class ConfigurationDataStoreImpl extends AbstractDataStore implements Con
     @Override
     public ListenableFuture<RpcResult<Boolean>> deleteData(final InstanceIdentifier<?> path) {
         final SchemaContext schemaContext = getClient().getSchemaContext();
-        final BindingIndependentMappingService mappingService = getClient().getMappingService();
-        final Map.Entry<String, DataSchemaNode> pathWithSchema = RestconfUtils.toRestconfIdentifier(path, mappingService, schemaContext);
+        final BindingNormalizedNodeCodecRegistry mappingService = getClient().getMappingService();
+        final YangInstanceIdentifier domPath = mappingService.toYangInstanceIdentifier(path);
+        final Map.Entry<String, DataSchemaNode> pathWithSchema = RestconfUtils.toRestconfIdentifier(domPath, schemaContext);
         final String restconfPath = getStorePrefix() + pathWithSchema.getKey();
         return getClient().delete(restconfPath,MediaType.APPLICATION_XML,new Function<ClientResponse, RpcResult<Boolean>>() {
+            @SuppressWarnings("unchecked")
             @Override
             public RpcResult<Boolean> apply(ClientResponse clientResponse) {
-                Entry<String, DataSchemaNode> restconfEntry = RestconfUtils.toRestconfIdentifier(mappingService.toDataDom(path), schemaContext);
                 if (clientResponse.getStatus() != 200) {
                     RpcError rpcError = new RestRpcError(RpcError.ErrorSeverity.ERROR,RpcError.ErrorType.RPC,null,null,"HTTP status "+clientResponse.getStatus(),null,null);
                     Collection<RpcError> errors = new ArrayList<RpcError>();
@@ -66,7 +59,7 @@ public class ConfigurationDataStoreImpl extends AbstractDataStore implements Con
                     RestRpcResult rpcResult = new RestRpcResult(false,null,errors);
                     return (RpcResult<Boolean>) Optional.of(rpcResult);
                 }
-                DataObject dataObject = RestconfUtils.dataObjectFromInputStream(path, clientResponse.getEntityInputStream(), schemaContext, mappingService,restconfEntry.getValue());
+                DataObject dataObject = deserialize(domPath, clientResponse.getEntityInputStream());
                 RestRpcResult rpcResult = new RestRpcResult(true,dataObject,null);
                 return (RpcResult<Boolean>) Optional.of(rpcResult);
             }
@@ -76,14 +69,15 @@ public class ConfigurationDataStoreImpl extends AbstractDataStore implements Con
     @Override
     public ListenableFuture<RpcResult<Boolean>> putData(final InstanceIdentifier<?> path) {
         final SchemaContext schemaContext = getClient().getSchemaContext();
-        final BindingIndependentMappingService mappingService = getClient().getMappingService();
-        final Map.Entry<String, DataSchemaNode> pathWithSchema = RestconfUtils.toRestconfIdentifier(path, mappingService, schemaContext);
+        final BindingNormalizedNodeCodecRegistry mappingService = getClient().getMappingService();
+        final YangInstanceIdentifier domPath = mappingService.toYangInstanceIdentifier(path);
+        final Map.Entry<String, DataSchemaNode> pathWithSchema = RestconfUtils.toRestconfIdentifier(domPath, schemaContext);
         final String restconfPath = getStorePrefix() + pathWithSchema.getKey();
 
         return getClient().put(restconfPath,MediaType.APPLICATION_XML,new Function<ClientResponse, RpcResult<Boolean>>() {
+            @SuppressWarnings("unchecked")
             @Override
             public RpcResult<Boolean> apply(ClientResponse clientResponse) {
-                Map.Entry<String, DataSchemaNode> restconfEntry = RestconfUtils.toRestconfIdentifier(mappingService.toDataDom(path), schemaContext);
                 if (clientResponse.getStatus() != 200) {
                     RpcError rpcError = new RestRpcError(RpcError.ErrorSeverity.ERROR,RpcError.ErrorType.RPC,null,null,"HTTP status "+clientResponse.getStatus(),null,null);
                     Collection<RpcError> errors = new ArrayList<RpcError>();
@@ -91,7 +85,7 @@ public class ConfigurationDataStoreImpl extends AbstractDataStore implements Con
                     RestRpcResult rpcResult = new RestRpcResult(false,null,errors);
                     return (RpcResult<Boolean>) Optional.of(rpcResult);
                 }
-                DataObject dataObject = RestconfUtils.dataObjectFromInputStream(path, clientResponse.getEntityInputStream(),schemaContext,mappingService,restconfEntry.getValue());
+                DataObject dataObject = deserialize(domPath, clientResponse.getEntityInputStream());
                 RestRpcResult rpcResult = new RestRpcResult(true,dataObject);
                 return (RpcResult<Boolean>) Optional.of(rpcResult);
             }
index c1fb969fc0cfc3196952b1f1b0be2f74b1b08dc7..5acd464a0b54da442015b6256da32f65cddaa1a8 100644 (file)
@@ -12,7 +12,6 @@ import org.opendaylight.yangtools.restconf.client.api.RestconfClientContext;
 import org.opendaylight.yangtools.restconf.client.api.RestconfClientContextFactory;
 import org.opendaylight.yangtools.restconf.client.api.UnsupportedProtocolException;
 import org.opendaylight.yangtools.restconf.client.api.auth.AuthenticationHolder;
-import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
 import org.opendaylight.yangtools.yang.model.api.SchemaContextHolder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -22,12 +21,14 @@ public class RestconfClientFactory implements RestconfClientContextFactory {
     private static final Logger logger = LoggerFactory.getLogger(RestconfClientFactory.class);
     private AuthenticationHolder authenticationHolder;
 
+
+
     @Override
-    public RestconfClientContext getRestconfClientContext(URL baseUrl, BindingIndependentMappingService mappingService, SchemaContextHolder schemaContextHolder) throws UnsupportedProtocolException {
+    public RestconfClientContext getRestconfClientContext(URL baseUrl, SchemaContextHolder schemaContextHolder) throws UnsupportedProtocolException {
         if (!baseUrl.getProtocol().equals("http")){
             throw new UnsupportedProtocolException("Unsupported protocol "+baseUrl.getProtocol());
         }
-        RestconfClientImpl restconfClient = new RestconfClientImpl(baseUrl,mappingService,schemaContextHolder);
+        RestconfClientImpl restconfClient = new RestconfClientImpl(baseUrl,schemaContextHolder);
         if (null!=authenticationHolder){
             restconfClient.setAuthenticationHolder(authenticationHolder);
         }
index bd4f262e8bd3148263e53b52611149c495b7d187..2672a5bc125af9f0b8d70d8b98f19f1eceb8d1f5 100644 (file)
@@ -1,21 +1,35 @@
 /*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
  *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
+ * This program and the accompanying materials are made available under the terms of the Eclipse
+ * Public License v1.0 which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
  */
 package org.opendaylight.yangtools.restconf.client;
 
+import com.google.common.base.Function;
+import com.google.common.base.Preconditions;
+import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
+import com.sun.jersey.api.client.Client;
+import com.sun.jersey.api.client.ClientResponse;
+import com.sun.jersey.api.client.WebResource;
+import com.sun.jersey.api.client.config.ClientConfig;
+import com.sun.jersey.api.client.config.DefaultClientConfig;
+import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
+import com.sun.jersey.api.client.filter.HTTPDigestAuthFilter;
 import java.net.URI;
 import java.net.URISyntaxException;
 import java.net.URL;
 import java.util.Set;
 import java.util.concurrent.Callable;
 import java.util.concurrent.Executors;
-
+import javassist.ClassPool;
 import javax.ws.rs.core.MediaType;
-
+import org.opendaylight.yangtools.binding.data.codec.gen.impl.DataObjectSerializerGenerator;
+import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator;
+import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
 import org.opendaylight.yangtools.restconf.client.api.RestconfClientContext;
 import org.opendaylight.yangtools.restconf.client.api.auth.AuthenticationHolder;
 import org.opendaylight.yangtools.restconf.client.api.data.ConfigurationDatastore;
@@ -27,27 +41,14 @@ import org.opendaylight.yangtools.restconf.client.to.RestRpcServiceContext;
 import org.opendaylight.yangtools.restconf.common.ResourceUri;
 import org.opendaylight.yangtools.restconf.utils.RestconfUtils;
 import org.opendaylight.yangtools.restconf.utils.XmlTools;
+import org.opendaylight.yangtools.sal.binding.generator.util.JavassistUtils;
 import org.opendaylight.yangtools.yang.binding.RpcService;
-import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaContextHolder;
 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.WebResource;
-import com.sun.jersey.api.client.config.ClientConfig;
-import com.sun.jersey.api.client.config.DefaultClientConfig;
-import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
-import com.sun.jersey.api.client.filter.HTTPDigestAuthFilter;
-
 public class RestconfClientImpl implements RestconfClientContext, SchemaContextListener {
 
     private final URI defaultUri;
@@ -60,26 +61,28 @@ public class RestconfClientImpl implements RestconfClientContext, SchemaContextL
 
     private final SchemaContextHolder schemaContextHolder;
 
-    private final BindingIndependentMappingService mappingService;
+    private final BindingNormalizedNodeCodecRegistry mappingService;
 
     private OperationalDataStoreImpl operationalDatastoreAccessor;
     private ConfigurationDataStoreImpl configurationDatastoreAccessor;
 
-    public RestconfClientImpl(final URL url,final BindingIndependentMappingService mappingService,
-                              final SchemaContextHolder schemaContextHolder){
-        Preconditions.checkArgument(url != null,"Restconf endpoint URL must be supplied.");
-        Preconditions.checkArgument(mappingService != null, "Mapping service must not be null.");
+    private DataObjectSerializerGenerator generator;
+
+    public RestconfClientImpl(final URL url, final SchemaContextHolder schemaContextHolder) {
+        Preconditions.checkArgument(url != null, "Restconf endpoint URL must be supplied.");
         Preconditions.checkNotNull(schemaContextHolder, "Schema Context Holder must not be null.");
         ClientConfig config = new DefaultClientConfig();
-        this.restClient  = Client.create(config);
+        this.restClient = Client.create(config);
         URI uri = null;
         try {
             uri = url.toURI();
         } catch (URISyntaxException e) {
-            logger.trace("Error in URI syntax {}",e.getMessage(),e);
+            logger.trace("Error in URI syntax {}", e.getMessage(), e);
         }
+
+        this.generator = StreamWriterGenerator.create(JavassistUtils.forClassPool(ClassPool.getDefault()));
         this.defaultUri = uri;
-        this.mappingService = mappingService;
+        this.mappingService = new BindingNormalizedNodeCodecRegistry(generator);
         this.schemaContextHolder = schemaContextHolder;
     }
 
@@ -95,46 +98,48 @@ public class RestconfClientImpl implements RestconfClientContext, SchemaContextL
         return schemaContextHolder;
     }
 
-    protected BindingIndependentMappingService getMappingService() {
+    protected BindingNormalizedNodeCodecRegistry getMappingService() {
         return mappingService;
     }
 
     @Override
     public ListenableFuture<Set<Class<? extends RpcService>>> getRpcServices() {
-        return get(ResourceUri.MODULES.getPath(), MediaType.APPLICATION_XML,new Function<ClientResponse, Set<Class<? extends RpcService>>>() {
-            @Override
-            public Set<Class<? extends RpcService>> apply(final ClientResponse clientResponse) {
-                if (clientResponse.getStatus() != 200) {
-                    throw new RuntimeException("Failed : HTTP error code : "
-                            + clientResponse.getStatus());
-                }
-                return RestconfUtils.rpcServicesFromInputStream(clientResponse.getEntityInputStream(),mappingService,schemaContextHolder.getSchemaContext());
-            }
-        });
+        return get(ResourceUri.MODULES.getPath(), MediaType.APPLICATION_XML,
+                new Function<ClientResponse, Set<Class<? extends RpcService>>>() {
+                    @Override
+                    public Set<Class<? extends RpcService>> apply(final ClientResponse clientResponse) {
+                        if (clientResponse.getStatus() != 200) {
+                            throw new RuntimeException("Failed : HTTP error code : " + clientResponse.getStatus());
+                        }
+                        return RestconfUtils.rpcServicesFromInputStream(clientResponse.getEntityInputStream(),
+                                mappingService, schemaContextHolder.getSchemaContext());
+                    }
+                });
     }
 
     @Override
     public <T extends RpcService> RpcServiceContext<T> getRpcServiceContext(final Class<T> rpcService) {
-        return new RestRpcServiceContext<T>(rpcService,this.mappingService,this,schemaContextHolder.getSchemaContext());
+        return new RestRpcServiceContext<T>(rpcService, this.mappingService, this,
+                schemaContextHolder.getSchemaContext());
     }
 
     @Override
     public ListenableFuture<Set<EventStreamInfo>> getAvailableEventStreams() {
-        return get(ResourceUri.STREAM.getPath(), MediaType.APPLICATION_XML, new Function<ClientResponse, Set<EventStreamInfo>>() {
-            @Override
-            public Set<EventStreamInfo> apply(final ClientResponse clientResponse) {
-                if (clientResponse.getStatus() != 200) {
-                    throw new RuntimeException("Failed : HTTP error code : "
-                            + clientResponse.getStatus());
-                }
-                try {
-                    return XmlTools.evenStreamsFromInputStream(clientResponse.getEntityInputStream());
-                } catch (Exception e) {
-                    logger.trace("Stream discovery failed due to {}",e);
-                    throw new IllegalStateException(e);
-                }
-            }
-        });
+        return get(ResourceUri.STREAM.getPath(), MediaType.APPLICATION_XML,
+                new Function<ClientResponse, Set<EventStreamInfo>>() {
+                    @Override
+                    public Set<EventStreamInfo> apply(final ClientResponse clientResponse) {
+                        if (clientResponse.getStatus() != 200) {
+                            throw new RuntimeException("Failed : HTTP error code : " + clientResponse.getStatus());
+                        }
+                        try {
+                            return XmlTools.evenStreamsFromInputStream(clientResponse.getEntityInputStream());
+                        } catch (Exception e) {
+                            logger.trace("Stream discovery failed due to {}", e);
+                            throw new IllegalStateException(e);
+                        }
+                    }
+                });
     }
 
     @Override
@@ -152,18 +157,22 @@ public class RestconfClientImpl implements RestconfClientContext, SchemaContextL
 
     @Override
     public OperationalDatastore getOperationalDatastore() {
-        if(operationalDatastoreAccessor == null) {
-            operationalDatastoreAccessor =  new OperationalDataStoreImpl(this);
+        if (operationalDatastoreAccessor == null) {
+            operationalDatastoreAccessor = new OperationalDataStoreImpl(this);
         }
         return operationalDatastoreAccessor;
     }
 
     public void setAuthenticationHolder(final AuthenticationHolder authenticationHolder) {
-        if(authenticationHolder.authenticationRequired()){
-            switch (authenticationHolder.getAuthType()){
-                case DIGEST: restClient.addFilter(new HTTPDigestAuthFilter(authenticationHolder.getUserName(), authenticationHolder.getPassword()));
+        if (authenticationHolder.authenticationRequired()) {
+            switch (authenticationHolder.getAuthType()) {
+                case DIGEST:
+                    restClient.addFilter(new HTTPDigestAuthFilter(authenticationHolder.getUserName(),
+                            authenticationHolder.getPassword()));
                     break;
-                default: restClient.addFilter(new HTTPBasicAuthFilter(authenticationHolder.getUserName(), authenticationHolder.getPassword()));
+                default:
+                    restClient.addFilter(new HTTPBasicAuthFilter(authenticationHolder.getUserName(),
+                            authenticationHolder.getPassword()));
                     break;
             }
         }
@@ -185,42 +194,57 @@ public class RestconfClientImpl implements RestconfClientContext, SchemaContextL
     }
 
     protected <T> ListenableFuture<T> get(final String path, final Function<ClientResponse, T> processingFunction) {
-        return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path), RestOperation.GET, processingFunction));
+        return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path), RestOperation.GET,
+                processingFunction));
     }
 
-    protected <T> ListenableFuture<T> get(final String path,final String mediaType, final Function<ClientResponse, T> processingFunction) {
-        return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path),mediaType,RestOperation.GET,processingFunction));
+    protected <T> ListenableFuture<T> get(final String path, final String mediaType,
+            final Function<ClientResponse, T> processingFunction) {
+        return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path), mediaType, RestOperation.GET,
+                processingFunction));
     }
 
-    protected <T> ListenableFuture<T> post(final String path, final String payload, final Function<ClientResponse, T> processingFunction) {
-        return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path),payload,RestOperation.POST,processingFunction));
+    protected <T> ListenableFuture<T> post(final String path, final String payload,
+            final Function<ClientResponse, T> processingFunction) {
+        return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path), payload, RestOperation.POST,
+                processingFunction));
     }
 
-    protected <T> ListenableFuture<T> post(final String path,final String payload,final String mediaType, final Function<ClientResponse, T> processingFunction) {
-        return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path),payload,RestOperation.POST,mediaType,processingFunction));
+    protected <T> ListenableFuture<T> post(final String path, final String payload, final String mediaType,
+            final Function<ClientResponse, T> processingFunction) {
+        return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path), payload, RestOperation.POST,
+                mediaType, processingFunction));
     }
 
-    protected <T> ListenableFuture<T> put(final String path, final String payload, final Function<ClientResponse, T> processingFunction) {
-        return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path),RestOperation.PUT,payload,processingFunction));
+    protected <T> ListenableFuture<T> put(final String path, final String payload,
+            final Function<ClientResponse, T> processingFunction) {
+        return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path), RestOperation.PUT, payload,
+                processingFunction));
     }
 
-    protected <T> ListenableFuture<T> put(final String path,final String payload,final String mediaType, final Function<ClientResponse, T> processingFunction) {
-        return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path),payload,RestOperation.PUT,mediaType,processingFunction));
+    protected <T> ListenableFuture<T> put(final String path, final String payload, final String mediaType,
+            final Function<ClientResponse, T> processingFunction) {
+        return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path), payload, RestOperation.PUT,
+                mediaType, processingFunction));
     }
+
     protected <T> ListenableFuture<T> delete(final String path, final Function<ClientResponse, T> processingFunction) {
-        return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path),RestOperation.DELETE,processingFunction));
+        return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path), RestOperation.DELETE,
+                processingFunction));
     }
 
-    protected <T> ListenableFuture<T> delete(final String path,final String mediaType, final Function<ClientResponse, T> processingFunction) {
-        return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path),RestOperation.DELETE,mediaType,processingFunction));
+    protected <T> ListenableFuture<T> delete(final String path, final String mediaType,
+            final Function<ClientResponse, T> processingFunction) {
+        return pool.submit(new ExecuteOperationAndTransformTask<T>(constructPath(path), RestOperation.DELETE,
+                mediaType, processingFunction));
     }
 
     protected String constructPath(final String path) {
         return getDefaultUri().toString() + path;
     }
 
-    private enum RestOperation{
-        PUT,POST,GET,DELETE;
+    private enum RestOperation {
+        PUT, POST, GET, DELETE;
     }
 
     private class ExecuteOperationAndTransformTask<T> implements Callable<T> {
@@ -230,32 +254,38 @@ public class RestconfClientImpl implements RestconfClientContext, SchemaContextL
         private final String payload;
         private final RestOperation restOperation;
 
-        public ExecuteOperationAndTransformTask(final String path, final String payload, final RestOperation operation, final Function<ClientResponse, T> processingFunction) {
+        public ExecuteOperationAndTransformTask(final String path, final String payload, final RestOperation operation,
+                final Function<ClientResponse, T> processingFunction) {
             this.path = path;
             this.transformation = processingFunction;
-            this.acceptType = MediaType.APPLICATION_XML; //ResourceMediaTypes.XML.getMediaType();
+            this.acceptType = MediaType.APPLICATION_XML; // ResourceMediaTypes.XML.getMediaType();
             this.payload = payload;
             this.restOperation = operation;
         }
 
-        public ExecuteOperationAndTransformTask(final String path,final String payload, final RestOperation operation,final String mediaType, final Function<ClientResponse, T> processingFunction) {
+        public ExecuteOperationAndTransformTask(final String path, final String payload, final RestOperation operation,
+                final String mediaType, final Function<ClientResponse, T> processingFunction) {
             this.path = path;
             this.transformation = processingFunction;
             this.acceptType = mediaType;
             this.payload = payload;
             this.restOperation = operation;
         }
-        public ExecuteOperationAndTransformTask(final String path, final RestOperation operation,final String mediaType, final Function<ClientResponse, T> processingFunction) {
+
+        public ExecuteOperationAndTransformTask(final String path, final RestOperation operation,
+                final String mediaType, final Function<ClientResponse, T> processingFunction) {
             this.path = path;
             this.transformation = processingFunction;
             this.acceptType = mediaType;
             this.payload = null;
             this.restOperation = operation;
         }
-        public ExecuteOperationAndTransformTask(final String path, final RestOperation operation, final Function<ClientResponse, T> processingFunction) {
+
+        public ExecuteOperationAndTransformTask(final String path, final RestOperation operation,
+                final Function<ClientResponse, T> processingFunction) {
             this.path = path;
             this.transformation = processingFunction;
-            this.acceptType =  MediaType.APPLICATION_XML;
+            this.acceptType = MediaType.APPLICATION_XML;
             this.payload = null;
             this.restOperation = operation;
         }
@@ -265,19 +295,30 @@ public class RestconfClientImpl implements RestconfClientContext, SchemaContextL
             ClientResponse response = null;
             try {
                 WebResource resource = restClient.resource(path);
-                switch (restOperation){
-                    case PUT: response = resource.type(MediaType.APPLICATION_XML).accept(acceptType).put(ClientResponse.class, payload);
+                switch (restOperation) {
+                    case PUT:
+                        response =
+                                resource.type(MediaType.APPLICATION_XML).accept(acceptType)
+                                        .put(ClientResponse.class, payload);
+                        break;
+                    case POST:
+                        response =
+                                resource.type(MediaType.APPLICATION_XML).accept(acceptType)
+                                        .post(ClientResponse.class, payload);
                         break;
-                    case POST : response = resource.type(MediaType.APPLICATION_XML).accept(acceptType).post(ClientResponse.class, payload);
-                         break;
-                    case GET: response = resource.type(MediaType.APPLICATION_XML).accept(acceptType).get(ClientResponse.class);
+                    case GET:
+                        response =
+                                resource.type(MediaType.APPLICATION_XML).accept(acceptType).get(ClientResponse.class);
                         break;
-                    case DELETE: response = resource.type(MediaType.APPLICATION_XML).accept(acceptType).delete(ClientResponse.class);
+                    case DELETE:
+                        response =
+                                resource.type(MediaType.APPLICATION_XML).accept(acceptType)
+                                        .delete(ClientResponse.class);
                         break;
                 }
 
-            } catch (Exception e){
-                logger.trace("Exception occured while posting data to client {}",e);
+            } catch (Exception e) {
+                logger.trace("Exception occured while posting data to client {}", e);
             }
 
 
index da285e3b041c61971e264199a308716cc7b0dc23..1d8cfa56dbc8e0d4978779f951bd03dad721cb39 100644 (file)
@@ -7,11 +7,11 @@
  */
 package org.opendaylight.yangtools.restconf.client.to;
 
+import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
 import org.opendaylight.yangtools.restconf.client.BindingToRestRpc;
 import org.opendaylight.yangtools.restconf.client.RestconfClientImpl;
 import org.opendaylight.yangtools.restconf.client.api.rpc.RpcServiceContext;
 import org.opendaylight.yangtools.yang.binding.RpcService;
-import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -21,7 +21,7 @@ public class RestRpcServiceContext <T extends RpcService> implements RpcServiceC
     private static final Logger logger = LoggerFactory.getLogger(RestRpcServiceContext.class);
     private T rpcServiceProxy;
 
-    public RestRpcServiceContext(Class<T> rpcService,BindingIndependentMappingService mappingService, RestconfClientImpl
+    public RestRpcServiceContext(Class<T> rpcService,BindingNormalizedNodeCodecRegistry mappingService, RestconfClientImpl
             restconfClient,SchemaContext schemaContext){
         this.rpcServiceProxy = BindingToRestRpc.getProxy(rpcService,mappingService,restconfClient,schemaContext);
     }
index 174c26ccb9ba1d58da4fb49dd0e7930bcd8dd4c0..45b8fa222fa56f56d6df94c2d45b01078dc07e28 100644 (file)
@@ -7,13 +7,15 @@
  */
 package org.opendaylight.yangtools.restconf.client;
 
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.fail;
+
 import com.google.common.util.concurrent.ListenableFuture;
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.util.Iterator;
 import java.util.Set;
 import java.util.concurrent.ExecutionException;
-import javassist.ClassPool;
 import org.junit.Before;
 import org.opendaylight.yangtools.restconf.client.api.RestconfClientContext;
 import org.opendaylight.yangtools.restconf.client.api.UnsupportedProtocolException;
@@ -22,13 +24,12 @@ import org.opendaylight.yangtools.restconf.client.api.data.OperationalDatastore;
 import org.opendaylight.yangtools.restconf.client.api.event.EventStreamInfo;
 import org.opendaylight.yangtools.restconf.client.api.event.ListenableEventStreamContext;
 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
-import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
 import org.opendaylight.yangtools.yang.binding.RpcService;
 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaContextHolder;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.fail;
 
 public class RestconfClientImplTest {
 
@@ -38,17 +39,19 @@ public class RestconfClientImplTest {
     public static final String JSON = "+json";
     public static final String XML = "+xml";
     private  RestconfClientContext restconfClientContext;
-    private RuntimeGeneratedMappingServiceImpl mappingService;
-
 
     @Before
     public void setupRestconfClientContext() throws MalformedURLException, UnsupportedProtocolException {
-        mappingService = new RuntimeGeneratedMappingServiceImpl(new ClassPool());
 
         final ModuleInfoBackedContext moduleInfo = ModuleInfoBackedContext.create();
         moduleInfo.addModuleInfos(BindingReflections.loadModuleInfos());
-        mappingService.onGlobalContextUpdated(moduleInfo.tryToCreateSchemaContext().get());
-        this.restconfClientContext = new RestconfClientFactory().getRestconfClientContext(new URL(restconfUrl),mappingService, mappingService);
+        this.restconfClientContext = new RestconfClientFactory().getRestconfClientContext(new URL(restconfUrl),new SchemaContextHolder() {
+
+            @Override
+            public SchemaContext getSchemaContext() {
+                return moduleInfo.tryToCreateSchemaContext().get();
+            }
+        });
         assertNotNull(this.restconfClientContext);
     }
 
@@ -60,7 +63,7 @@ public class RestconfClientImplTest {
         }
         if (streamsFuture.isDone()){
             try {
-                Set<EventStreamInfo> streams = (Set<EventStreamInfo>) streamsFuture.get();
+                Set<EventStreamInfo> streams = streamsFuture.get();
                 assertNotNull(streams);
             } catch (InterruptedException e) {
                 fail(e.getMessage());
@@ -77,7 +80,7 @@ public class RestconfClientImplTest {
         }
         if (servicesFuture.isDone()){
             try {
-                Set<Class<? extends RpcService>> streams = (Set<Class<? extends RpcService>>) servicesFuture.get();
+                Set<Class<? extends RpcService>> streams = servicesFuture.get();
                 assertNotNull(streams);
             } catch (InterruptedException e) {
                 fail(e.getMessage());
diff --git a/restconf/restconf-jaxrs-api/src/main/java/org/opendaylight/yangtools/RestRestconfService.java b/restconf/restconf-jaxrs-api/src/main/java/org/opendaylight/yangtools/RestRestconfService.java
deleted file mode 100644 (file)
index a3c7146..0000000
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import org.opendaylight.yangtools.draft.Draft01;
-import org.opendaylight.yangtools.draft.Draft02;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-
-@Path("restconf")
-public interface RestRestconfService {
-
-    public static final String IDENTIFIER = "identifier";
-    public static final String INPUT = "input";
-    public static final String XML = "+xml";
-    public static final String JSON = "+json";
-
-    @GET
-    public Object getRoot();
-
-    @GET
-    @Path("/modules")
-    @Produces({Draft01.MediaTypes.API+JSON,Draft01.MediaTypes.API+XML,
-            Draft02.MediaTypes.API+JSON,Draft02.MediaTypes.API+XML})
-    public String getModules();
-
-    @POST
-    @Path("/operations/{identifier}")
-    @Produces({Draft01.MediaTypes.DATA+JSON,Draft01.MediaTypes.DATA+XML,
-            Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
-            MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    @Consumes({Draft01.MediaTypes.DATA+JSON,Draft01.MediaTypes.DATA+XML,
-            Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
-            MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public String invokeRpc(@PathParam(IDENTIFIER) String identifier, @QueryParam(INPUT) CompositeNode payload);
-
-    @POST
-    @Path("/operations/{identifier}")
-    @Produces({Draft01.MediaTypes.DATA+JSON,Draft01.MediaTypes.DATA+XML,
-            Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
-            MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public String invokeRpc(@PathParam(IDENTIFIER) String identifier);
-
-    @GET
-    @Path("/config/{identifier:.+}")
-    @Produces({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
-            MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public String readConfigurationData(@PathParam(IDENTIFIER) String identifier);
-
-    @GET
-    @Path("/operational/{identifier:.+}")
-    @Produces({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
-            MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public String readOperationalData(@PathParam(IDENTIFIER) String identifier);
-
-    @PUT
-    @Path("/config/{identifier:.+}")
-    @Consumes({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
-            MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public Response updateConfigurationData(@PathParam(IDENTIFIER) String identifier,@QueryParam(INPUT) CompositeNode payload);
-
-    @POST
-    @Path("/config/{identifier:.+}")
-    @Consumes({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
-            MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public Response createConfigurationData(@PathParam(IDENTIFIER) String identifier, @QueryParam(INPUT) CompositeNode payload);
-
-    @POST
-    @Path("/config")
-    @Consumes({Draft02.MediaTypes.DATA+JSON,Draft02.MediaTypes.DATA+XML,
-            MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML, MediaType.TEXT_XML})
-    public Response createConfigurationData( @QueryParam(INPUT) CompositeNode payload);
-
-    @DELETE
-    @Path("/config/{identifier:.+}")
-    public Response deleteConfigurationData(@PathParam(IDENTIFIER) String identifier);
-
-
-}
index eba3e4380ea75d138bd32154908da54618fa2f45..9ebb9ba3a4e47ad18055bcf22a06a9ae16e7bc8b 100644 (file)
             <groupId>org.opendaylight.yangtools</groupId>
             <artifactId>yang-binding</artifactId>
         </dependency>
+        <dependency>
+            <groupId>org.opendaylight.yangtools</groupId>
+            <artifactId>binding-data-codec</artifactId>
+        </dependency>
         <dependency>
             <groupId>org.opendaylight.yangtools</groupId>
             <artifactId>yang-common</artifactId>
             <groupId>org.opendaylight.yangtools</groupId>
             <artifactId>yang-model-api</artifactId>
         </dependency>
-        <dependency>
-            <groupId>commons-io</groupId>
-            <artifactId>commons-io</artifactId>
-        </dependency>
         <dependency>
             <groupId>com.google.guava</groupId>
             <artifactId>guava</artifactId>
             <artifactId>binding-generator-impl</artifactId>
             <scope>test</scope>
         </dependency>
-        <dependency>
-            <groupId>org.opendaylight.yangtools</groupId>
-            <artifactId>binding-data-codec</artifactId>
-            <scope>test</scope>
-        </dependency>
         <dependency>
             <groupId>org.opendaylight.yangtools</groupId>
             <artifactId>bug527-test-model</artifactId>
diff --git a/restconf/restconf-util/src/main/java/org/opendaylight/yangtools/restconf/utils/RestMessageTools.java b/restconf/restconf-util/src/main/java/org/opendaylight/yangtools/restconf/utils/RestMessageTools.java
deleted file mode 100644 (file)
index c0d6af5..0000000
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.restconf.utils;
-
-import com.sun.jersey.api.client.ClientResponse;
-import java.io.IOException;
-import java.io.StringWriter;
-import org.apache.commons.io.IOUtils;
-import org.opendaylight.yangtools.draft.Draft01;
-import org.opendaylight.yangtools.draft.Draft02;
-import org.opendaylight.yangtools.restconf.client.api.RestMessage;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-
-public class RestMessageTools {
-
-    public static final String XML = "+xml";
-    public static final String JSON = "+json";
-    private static final Logger logger = LoggerFactory.getLogger(RestMessageTools.class.toString());
-
-    public RestMessage extractMessage(ClientResponse response){
-        RestMessage restMessage = null;
-        if (response.getType().equals(Draft01.MediaTypes.API+JSON) ||
-                response.getType().equals(Draft02.MediaTypes.API+JSON)){
-            //to be implemented
-        }
-        if (response.getType().equals(Draft01.MediaTypes.API+XML) ||
-                response.getType().equals(Draft02.MediaTypes.API+XML)){
-            StringWriter writer = new StringWriter();
-            try {
-                IOUtils.copy(response.getEntityInputStream(), writer, "UTF-8");
-            } catch (IOException e) {
-                logger.info("Error parsing XML file from response.");
-            }
-        }
-        return restMessage;
-    }
-}
index 6a772f4ae4f30326e1c2b3f7f35891621fcf7728..7aedde5dbeac405951dbc6bd938c03e2858d6b7e 100644 (file)
@@ -7,7 +7,6 @@
  */
 package org.opendaylight.yangtools.restconf.utils;
 
-import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.BiMap;
 import com.google.common.collect.HashBiMap;
@@ -27,19 +26,12 @@ import java.util.Set;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
-import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
 import org.opendaylight.yangtools.yang.binding.RpcService;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
-import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
-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.codec.xml.XmlCodecProvider;
-import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
@@ -50,6 +42,7 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
 import org.xml.sax.SAXException;
 
 public class RestconfUtils {
@@ -58,13 +51,6 @@ public class RestconfUtils {
 
     private static final BiMap<URI, String> uriToModuleName = HashBiMap.<URI, String> create();
 
-    public static Entry<String, DataSchemaNode> toRestconfIdentifier(
-            final org.opendaylight.yangtools.yang.binding.InstanceIdentifier<?> bindingIdentifier,
-            final BindingIndependentMappingService mappingService, final SchemaContext schemaContext) {
-        YangInstanceIdentifier domIdentifier = mappingService.toDataDom(bindingIdentifier);
-        return toRestconfIdentifier(domIdentifier, schemaContext);
-    }
-
     public static Entry<String, DataSchemaNode> toRestconfIdentifier(final YangInstanceIdentifier xmlInstanceIdentifier,
             final SchemaContext schemaContext) {
 
@@ -212,49 +198,23 @@ public class RestconfUtils {
      * @return Set of classes representing rpc services parsed from input stream
      */
     public static Set<Class<? extends RpcService>> rpcServicesFromInputStream(final InputStream inputStream,
-            final BindingIndependentMappingService mappingService, final SchemaContext schemaContext) {
+            final BindingNormalizedNodeCodecRegistry mappingService, final SchemaContext schemaContext) {
         try {
             DocumentBuilderFactory documentBuilder = DocumentBuilderFactory.newInstance();
             documentBuilder.setNamespaceAware(true);
             DocumentBuilder builder = documentBuilder.newDocumentBuilder();
             Document doc = builder.parse(inputStream);
             Element rootElement = doc.getDocumentElement();
-
-            List<Node<?>> domNodes = XmlDocumentUtils.toDomNodes(rootElement,
-                    Optional.of(schemaContext.getChildNodes()));
+            NodeList domNodes = rootElement.getChildNodes();
             Set<Class<? extends RpcService>> rpcServices = new HashSet<Class<? extends RpcService>>();
-            for (Node<?> node : domNodes) {
-                if (node instanceof ImmutableCompositeNode) {
-                    ImmutableCompositeNode icNode = (ImmutableCompositeNode) node;
-                    QName namespace = null;
-                    QName revision = null;
-                    QName name = null;
-                    for (QName q : icNode.keySet()) {
-                        if (q.getLocalName().equals("namespace")) {
-                            namespace = q;
-                        }
-                        if (q.getLocalName().equals("revision")) {
-                            revision = q;
-                        }
-                        if (q.getLocalName().equals("name")) {
-                            name = q;
-                        }
 
-                    }
+            for (int i = 0; i < domNodes.getLength(); i++) {
 
-                    // FIXME: Method getRpcServiceClassFor has been modified and
-                    // fixed to follow API contract. This call MUST be updated
-                    // to follow contract i.e. pass correct parameters:
-                    // "NAMESPACE" and "REVISION"
-                    Optional<Class<? extends RpcService>> rpcService = mappingService.getRpcServiceClassFor(
-                            icNode.get(name).get(0).getValue().toString(), icNode.get(revision).get(0).getValue()
-                                    .toString());
-                    if (rpcService.isPresent()) {
-                        rpcServices.add(rpcService.get());
-                    }
-                }
             }
-
+            /**
+             * FIXME: Parse modules section and find all related RPC services.
+             *
+             */
             return rpcServices;
         } catch (ParserConfigurationException e) {
             logger.trace("Parse configuration exception {}", e);
@@ -266,46 +226,4 @@ public class RestconfUtils {
         return null;
     }
 
-    /**
-     * Parse DataObject from input stream.
-     *
-     * @param path
-     *            identifier of expected result object
-     * @param inputStream
-     *            stream containing xml data to parse
-     * @param schemaContext
-     *            parsed yang data context
-     * @param mappingService
-     *            current mapping service
-     * @param dataSchema
-     *            yang data schema node representation of resulting data object
-     * @return DataObject instance parsed from input stream
-     */
-    public static DataObject dataObjectFromInputStream(
-            final org.opendaylight.yangtools.yang.binding.InstanceIdentifier<?> path, final InputStream inputStream,
-            final SchemaContext schemaContext, final BindingIndependentMappingService mappingService,
-            final DataSchemaNode dataSchema) {
-        // Parse stream into w3c Document
-        try {
-            DocumentBuilderFactory documentBuilder = DocumentBuilderFactory.newInstance();
-            documentBuilder.setNamespaceAware(true);
-            DocumentBuilder builder = documentBuilder.newDocumentBuilder();
-            Document doc = builder.parse(inputStream);
-            Element rootElement = doc.getDocumentElement();
-            Node<?> domNode = XmlDocumentUtils.toDomNode(rootElement, Optional.of(dataSchema),
-                    Optional.<XmlCodecProvider> absent(), Optional.of(schemaContext));
-            DataObject dataObject = mappingService.dataObjectFromDataDom(path, (CompositeNode) domNode); // getDataFromResponse
-            return dataObject;
-        } catch (DeserializationException e) {
-            logger.trace("Deserialization exception {}", e);
-        } catch (ParserConfigurationException e) {
-            logger.trace("Parse configuration exception {}", e);
-        } catch (SAXException e) {
-            logger.trace("SAX exception {}", e);
-        } catch (IOException e) {
-            logger.trace("IOException {}", e);
-        }
-        return null;
-    }
-
 }
index c5cf5cdf59511899d880346993dd9eb6947ecb8a..425e3e218e6308bf1458758ecfd885364f287f65 100644 (file)
@@ -47,7 +47,6 @@ import org.opendaylight.yangtools.binding.data.codec.gen.impl.DataObjectSerializ
 import org.opendaylight.yangtools.binding.data.codec.gen.impl.StreamWriterGenerator;
 import org.opendaylight.yangtools.binding.data.codec.impl.BindingNormalizedNodeCodecRegistry;
 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
-import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
 import org.opendaylight.yangtools.sal.binding.generator.util.BindingRuntimeContext;
 import org.opendaylight.yangtools.sal.binding.generator.util.JavassistUtils;
 import org.opendaylight.yangtools.yang.binding.DataObject;
@@ -71,7 +70,7 @@ public class BindingStreamWriterTest {
     private static final ReportedLspKey LSP1_KEY = new ReportedLspKey("one");
     private static final ReportedLspKey LSP2_KEY = new ReportedLspKey("two");
 
-    private RuntimeGeneratedMappingServiceImpl mappingService;
+
     private Optional<SchemaContext> schemaContext;
     private DataObjectSerializerGenerator generator;
     private BindingNormalizedNodeCodecRegistry registry;
@@ -79,12 +78,9 @@ public class BindingStreamWriterTest {
 
     @Before
     public void setup() {
-        this.mappingService = new RuntimeGeneratedMappingServiceImpl(ClassPool.getDefault());
-
         final ModuleInfoBackedContext moduleInfo = ModuleInfoBackedContext.create();
         moduleInfo.addModuleInfos(BindingReflections.loadModuleInfos());
         schemaContext = moduleInfo.tryToCreateSchemaContext();
-        this.mappingService.onGlobalContextUpdated(moduleInfo.tryToCreateSchemaContext().get());
         JavassistUtils utils = JavassistUtils.forClassPool(ClassPool.getDefault());
         generator = StreamWriterGenerator.create(utils);
         registry = new BindingNormalizedNodeCodecRegistry(generator);
diff --git a/restconf/restconf-util/src/test/java/org/opendaylight/yangtools/restconf/utils/Bug1196Test.java b/restconf/restconf-util/src/test/java/org/opendaylight/yangtools/restconf/utils/Bug1196Test.java
deleted file mode 100644 (file)
index 7b8be18..0000000
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.restconf.utils;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.io.InputStream;
-import java.util.AbstractMap.SimpleEntry;
-import java.util.Map.Entry;
-
-import javassist.ClassPool;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.network.topology.unix.rev131222.network.topology.topology.node.path.computation.client.reported.lsp.lsp.tlvs.vs.tlv.vendor.payload.unix.UnixSubTlvs;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.ReportedLsp1;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.Lsp;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.Tlvs;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.network.topology.topology.node.path.computation.client.reported.lsp.lsp.tlvs.vs.tlv.vendor.payload.linux.LinuxSubTlvs;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.vs.tlv.VsTlv;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.Node1;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.PathComputationClient;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.ReportedLsp;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
-import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-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.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-
-public class Bug1196Test {
-
-    private static final InstanceIdentifier<PathComputationClient> PATH_TO_CLIENT = InstanceIdentifier.builder(NetworkTopology.class)
-            .child(Topology.class)
-            .child(Node.class)
-            .augmentation(Node1.class)
-            .child(PathComputationClient.class)
-            .build();
-    private RuntimeGeneratedMappingServiceImpl mappingService;
-
-    @Before
-    public void setup() {
-        this.mappingService = new RuntimeGeneratedMappingServiceImpl(new ClassPool());
-
-        final ModuleInfoBackedContext moduleInfo = ModuleInfoBackedContext.create();
-        moduleInfo.addModuleInfos(BindingReflections.loadModuleInfos());
-        this.mappingService.onGlobalContextUpdated(moduleInfo.tryToCreateSchemaContext().get());
-    }
-
-    @Test
-    public void testXmlDataToDataObjectLinuxCase() {
-        final InstanceIdentifier<Topology> instanceIdentifier = InstanceIdentifier.builder(NetworkTopology.class)
-                .child(Topology.class, new TopologyKey(new TopologyId("example-pcep-topology"))).build();
-        final InputStream is = this.getClass().getClassLoader().getResourceAsStream("topology-bug1196-linux.xml");
-        final DataSchemaNode dataSchema = RestconfUtils.toRestconfIdentifier(instanceIdentifier, this.mappingService,
-                this.mappingService.getSchemaContext()).getValue();
-        Topology topology = (Topology) RestconfUtils.dataObjectFromInputStream(instanceIdentifier, is,
-                this.mappingService.getSchemaContext(), this.mappingService, dataSchema);
-        assertNotNull(topology);
-        assertNotNull(topology.getNode());
-        assertEquals(1, topology.getNode().size());
-        Node node = topology.getNode().get(0);
-        Node1 node1 = node.getAugmentation(Node1.class);
-        assertNotNull(node1);
-        final PathComputationClient pcc = node1.getPathComputationClient();
-        final Lsp lsp = pcc.getReportedLsp().get(0).getAugmentation(ReportedLsp1.class).getLsp();
-        org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.Tlvs tlvs = lsp.getTlvs();
-        assertNotNull(tlvs);
-        VsTlv vsTlv = tlvs.getVsTlv();
-        assertNotNull(vsTlv.getVendorPayload());
-
-        Entry<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, CompositeNode> domPcc = mappingService.toDataDom(new SimpleEntry<InstanceIdentifier<?>,DataObject>(PATH_TO_CLIENT,pcc));
-        CompositeNode domPccValue = domPcc.getValue();
-        assertNotNull(domPccValue);
-        CompositeNode domPccTlvs = getFirstReportedLspVsTlvs(domPccValue);
-        assertNotNull(domPccTlvs);
-        assertNotNull(domPccTlvs.getFirstCompositeByName(LinuxSubTlvs.QNAME));
-
-    }
-
-    private CompositeNode getFirstReportedLspVsTlvs(final CompositeNode domPccValue) {
-        return domPccValue.getFirstCompositeByName(ReportedLsp.QNAME).getFirstCompositeByName(Lsp.QNAME).getFirstCompositeByName(Tlvs.QNAME).getFirstCompositeByName(QName.create(Tlvs.QNAME,VsTlv.QNAME.getLocalName()));
-    }
-
-    @Test
-    public void testXmlDataToDataObjectUnixCase() {
-        final InstanceIdentifier<Topology> instanceIdentifier = InstanceIdentifier.builder(NetworkTopology.class)
-                .child(Topology.class, new TopologyKey(new TopologyId("example-pcep-topology"))).build();
-        final InputStream is = this.getClass().getClassLoader().getResourceAsStream("topology-bug1196-unix.xml");
-        final DataSchemaNode dataSchema = RestconfUtils.toRestconfIdentifier(instanceIdentifier, this.mappingService,
-                this.mappingService.getSchemaContext()).getValue();
-        Topology topology = (Topology) RestconfUtils.dataObjectFromInputStream(instanceIdentifier, is,
-                this.mappingService.getSchemaContext(), this.mappingService, dataSchema);
-        assertNotNull(topology);
-        assertNotNull(topology.getNode());
-        assertEquals(1, topology.getNode().size());
-        Node node = topology.getNode().get(0);
-        Node1 node1 = node.getAugmentation(Node1.class);
-        assertNotNull(node1);
-        final PathComputationClient pcc = node1.getPathComputationClient();
-        final Lsp lsp = pcc.getReportedLsp().get(0).getAugmentation(ReportedLsp1.class).getLsp();
-        org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.Tlvs tlvs = lsp.getTlvs();
-        assertNotNull(tlvs);
-        VsTlv vsTlv = tlvs.getVsTlv();
-        assertNotNull(vsTlv.getVendorPayload());
-
-        Entry<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, CompositeNode> domPcc = mappingService.toDataDom(new SimpleEntry<InstanceIdentifier<?>,DataObject>(PATH_TO_CLIENT,pcc));
-        CompositeNode domPccValue = domPcc.getValue();
-        assertNotNull(domPccValue);
-        CompositeNode domPccTlvs = getFirstReportedLspVsTlvs(domPccValue);
-        assertNotNull(domPccTlvs);
-        assertNotNull(domPccTlvs.getFirstCompositeByName(UnixSubTlvs.QNAME));
-    }
-
-}
diff --git a/restconf/restconf-util/src/test/java/org/opendaylight/yangtools/restconf/utils/Bug527Test.java b/restconf/restconf-util/src/test/java/org/opendaylight/yangtools/restconf/utils/Bug527Test.java
deleted file mode 100644 (file)
index 97a47cb..0000000
+++ /dev/null
@@ -1,100 +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.yangtools.restconf.utils;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-
-import java.io.InputStream;
-import java.util.AbstractMap.SimpleEntry;
-
-import javassist.ClassPool;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yang.gen.v1.urn.yang.bar.rev140321.CreateFactoryInput;
-import org.opendaylight.yang.gen.v1.urn.yang.bar.rev140321.Factory;
-import org.opendaylight.yang.gen.v1.urn.yang.bar.rev140321.factory.Alpha;
-import org.opendaylight.yang.gen.v1.urn.yang.bar.rev140321.factory.Beta;
-import org.opendaylight.yang.gen.v1.urn.yang.bar.rev140321.machine.ext.types.machine.type.TypeA;
-import org.opendaylight.yang.gen.v1.urn.yang.bar.rev140321.machine.types.Types;
-import org.opendaylight.yang.gen.v1.urn.yang.bar.rev140321.machine.types.types.MachineType;
-import org.opendaylight.yang.gen.v1.urn.yang.baz.rev140321.machine.def.Machine;
-import org.opendaylight.yang.gen.v1.urn.yang.baz.rev140321.machine.def.machine.Atts;
-import org.opendaylight.yang.gen.v1.urn.yang.foo.rev140321.AlphaExt;
-import org.opendaylight.yang.gen.v1.urn.yang.foo.rev140321.BetaExt;
-import org.opendaylight.yang.gen.v1.urn.yang.foo.rev140321.CreateExt;
-import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
-import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-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.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-
-public class Bug527Test {
-
-    private RuntimeGeneratedMappingServiceImpl mappingService;
-
-    @Before
-    public void setup() {
-        this.mappingService = new RuntimeGeneratedMappingServiceImpl(new ClassPool());
-
-        final ModuleInfoBackedContext moduleInfo = ModuleInfoBackedContext.create();
-        moduleInfo.addModuleInfos(BindingReflections.loadModuleInfos());
-        this.mappingService.onGlobalContextUpdated(moduleInfo.tryToCreateSchemaContext().get());
-    }
-
-    @Test
-    public void testToDataObjectMappingWithNestedAugmentations() {
-        InstanceIdentifier<Factory> factoryId = InstanceIdentifier.builder(Factory.class).build();
-        InputStream is = this.getClass().getClassLoader().getResourceAsStream("topology-bug527.xml");
-        DataSchemaNode dataSchema = RestconfUtils.toRestconfIdentifier(factoryId, mappingService,
-                mappingService.getSchemaContext()).getValue();
-
-        Factory factory = (Factory) RestconfUtils.dataObjectFromInputStream(factoryId, is,
-                mappingService.getSchemaContext(), mappingService, dataSchema);
-        assertNotNull(factory);
-
-        Alpha alpha = factory.getAlpha();
-        Machine alphaMachine = alpha.getMachine();
-        Atts alphaAtts = alphaMachine.getAtts();
-        AlphaExt alphaAttsAug = alphaAtts.getAugmentation(AlphaExt.class);
-        Types alphaMachineTypes = alphaAttsAug.getTypes();
-        MachineType alphaMachineType = alphaMachineTypes.getMachineType();
-        TypeA alphaTypeA = (TypeA) alphaMachineType;
-        assertEquals("id-alpha", alphaTypeA.getId());
-        assertNull(alphaAtts.getAugmentation(BetaExt.class));
-
-        Beta beta = factory.getBeta();
-        Machine betaMachine = beta.getMachine();
-        Atts betaAtts = betaMachine.getAtts();
-        BetaExt betaAttsAug = betaAtts.getAugmentation(BetaExt.class);
-        Types betaMachineTypes = betaAttsAug.getTypes();
-        MachineType betaMachineType = betaMachineTypes.getMachineType();
-        TypeA betaTypeA = (TypeA) betaMachineType;
-        assertEquals("id-beta", betaTypeA.getId());
-        assertNull(betaAtts.getAugmentation(AlphaExt.class));
-
-        InstanceIdentifier<? extends DataObject> alphaPath = InstanceIdentifier.builder(Factory.class).child(Alpha.class).build();
-        CompositeNode domAlpha = mappingService.toDataDom(new SimpleEntry<InstanceIdentifier<? extends DataObject>,DataObject>(alphaPath,alpha)).getValue();
-        assertNotNull(domAlpha);
-
-        CompositeNodeTOImpl domInput = new CompositeNodeTOImpl(QName.create(domAlpha.getNodeType(),"input"),null, domAlpha.getValue());
-
-        CreateFactoryInput nestedInput = (CreateFactoryInput) mappingService.dataObjectFromDataDom(CreateFactoryInput.class, domInput);
-        assertNotNull(nestedInput);
-        assertNotNull(nestedInput.getMachine().getAtts().getAugmentation(CreateExt.class));
-
-
-    }
-
-}
diff --git a/restconf/restconf-util/src/test/java/org/opendaylight/yangtools/restconf/utils/LazyGeneratedCodecRestartTest.java b/restconf/restconf-util/src/test/java/org/opendaylight/yangtools/restconf/utils/LazyGeneratedCodecRestartTest.java
deleted file mode 100644 (file)
index 80c5d6e..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-package org.opendaylight.yangtools.restconf.utils;
-
-import org.junit.Before;
-import org.junit.Test;
-
-public class LazyGeneratedCodecRestartTest {
-
-    Bug527Test bug527;
-    Bug1196Test bug1196;
-    RestconfUtilsTest reUtils;
-
-
-    @Before
-    public void setup() {
-        bug527 = new Bug527Test();
-        bug1196 = new Bug1196Test();
-        reUtils = new RestconfUtilsTest();
-
-    }
-
-    @Test
-    public void test() {
-       bug1196.setup();
-       bug1196.testXmlDataToDataObjectUnixCase();
-
-       reUtils.setup();
-       reUtils.testToDataObjectMappingWithNestedAugmentations();
-    }
-
-}
diff --git a/restconf/restconf-util/src/test/java/org/opendaylight/yangtools/restconf/utils/RestconfUtilsTest.java b/restconf/restconf-util/src/test/java/org/opendaylight/yangtools/restconf/utils/RestconfUtilsTest.java
deleted file mode 100644 (file)
index a327389..0000000
+++ /dev/null
@@ -1,82 +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.yangtools.restconf.utils;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import java.io.InputStream;
-
-import javassist.ClassPool;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.isis.topology.rev131021.IgpNodeAttributes1;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
-import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.nt.l3.unicast.igp.topology.rev131021.Node1;
-import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleInfoBackedContext;
-import org.opendaylight.yangtools.sal.binding.generator.impl.RuntimeGeneratedMappingServiceImpl;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-
-public class RestconfUtilsTest {
-
-    private RuntimeGeneratedMappingServiceImpl mappingService;
-
-    @Before
-    public void setup() {
-        this.mappingService = new RuntimeGeneratedMappingServiceImpl(new ClassPool());
-
-        final ModuleInfoBackedContext moduleInfo = ModuleInfoBackedContext.create();
-        moduleInfo.addModuleInfos(BindingReflections.loadModuleInfos());
-        this.mappingService.onGlobalContextUpdated(moduleInfo.tryToCreateSchemaContext().get());
-    }
-
-    @Test
-    public void firstTest() { // test static state collisions with the other test
-        final InstanceIdentifier<Topology> instanceIdentifier = InstanceIdentifier.builder(NetworkTopology.class)
-                .child(Topology.class, new TopologyKey(new TopologyId("example-pcep-topology"))).build();
-        final InputStream is = this.getClass().getClassLoader().getResourceAsStream("topology-bug1196-linux.xml");
-        RestconfUtils.toRestconfIdentifier(instanceIdentifier, this.mappingService,
-                this.mappingService.getSchemaContext()).getValue();
-    }
-
-    @Test
-    public void testToDataObjectMappingWithNestedAugmentations() {
-        final InstanceIdentifier<Topology> topologyIdentifier = InstanceIdentifier.builder(NetworkTopology.class)
-                .child(Topology.class).build();
-        final InputStream is = this.getClass().getClassLoader().getResourceAsStream("topology.xml");
-        final DataSchemaNode dataSchema = RestconfUtils.toRestconfIdentifier(topologyIdentifier, this.mappingService,
-                this.mappingService.getSchemaContext()).getValue();
-        final Topology topology = (Topology) RestconfUtils.dataObjectFromInputStream(topologyIdentifier, is,
-                this.mappingService.getSchemaContext(), this.mappingService, dataSchema);
-
-        assertNotNull(topology);
-        assertEquals(1, topology.getNode().size());
-        final Node node = topology.getNode().get(0);
-        assertEquals("bgpls://IsisLevel2:1/type=node&as=72&domain=673720360&router=0000.0000.0042", node.getNodeId()
-                .getValue());
-
-        final Node1 node1 = node.getAugmentation(Node1.class);
-        assertNotNull(node1);
-        assertNotNull(node1.getIgpNodeAttributes());
-        assertEquals("Of-9k-02", node1.getIgpNodeAttributes().getName().getValue());
-
-        final IgpNodeAttributes1 igpAttributes1 = node1.getIgpNodeAttributes()
-                .getAugmentation(IgpNodeAttributes1.class);
-        assertNotNull(igpAttributes1);
-        assertNotNull(igpAttributes1.getIsisNodeAttributes());
-        assertEquals("0000.1111.2222", igpAttributes1.getIsisNodeAttributes().getIso().getIsoSystemId().getValue());
-    }
-
-}
index a229553f39fe9466bf576498a7ddaa72835c2a19..01e71bd5477661fc2afa507ff58fb3cfaa7a909a 100644 (file)
@@ -36,7 +36,6 @@
         <module>yang-parser-api</module>
         <module>yang-parser-impl</module>
         <module>yang-model-export</module>
-        <module>yang-data-composite-node</module>
     </modules>
     <build>
         <plugins>
index 6d6decb8ec74d5bb25fa98e8b727f4306cc9b3dd..3f4c85e4b2a9b2aecc1c83a029be47ef227c1f62 100644 (file)
@@ -9,6 +9,7 @@ package org.opendaylight.yangtools.yang.binding.util;
 
 import static com.google.common.base.Preconditions.checkArgument;
 import static com.google.common.base.Preconditions.checkState;
+
 import com.google.common.base.Optional;
 import com.google.common.cache.CacheBuilder;
 import com.google.common.cache.CacheLoader;
@@ -20,6 +21,7 @@ import java.lang.reflect.Field;
 import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.Method;
 import java.lang.reflect.Type;
+import java.net.URI;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.LinkedList;
@@ -44,6 +46,7 @@ import org.opendaylight.yangtools.yang.binding.RpcService;
 import org.opendaylight.yangtools.yang.binding.YangModelBindingProvider;
 import org.opendaylight.yangtools.yang.binding.YangModuleInfo;
 import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.QNameModule;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -59,8 +62,6 @@ public class BindingReflections {
             .expireAfterAccess(EXPIRATION_TIME, TimeUnit.SECONDS) //
             .build(new ClassToQNameLoader());
 
-
-
     private BindingReflections() {
         throw new UnsupportedOperationException("Utility class.");
     }
@@ -68,8 +69,8 @@ public class BindingReflections {
     /**
      * Find augmentation target class from concrete Augmentation class
      *
-     * This method uses first generic argument of
-     * implemented {@link Augmentation} interface.
+     * This method uses first generic argument of implemented
+     * {@link Augmentation} interface.
      *
      * @param augmentation
      *            {@link Augmentation} subclass for which we want to determine
@@ -85,8 +86,8 @@ public class BindingReflections {
     /**
      * Find data hierarchy parent from concrete Data class
      *
-     * This method uses first generic argument of
-     * implemented {@link ChildOf} interface.
+     * This method uses first generic argument of implemented {@link ChildOf}
+     * interface.
      *
      * @param childClass
      *            child class for which we want to find the parent class.
@@ -100,7 +101,8 @@ public class BindingReflections {
      * Find data hierarchy parent from concrete Data class
      *
      * This method is shorthand which gets DataObject class by invoking
-     * {@link DataObject#getImplementedInterface()} and uses {@link #findHierarchicalParent(Class)}.
+     * {@link DataObject#getImplementedInterface()} and uses
+     * {@link #findHierarchicalParent(Class)}.
      *
      * @param child
      *            Child object for which the parent needs to be located.
@@ -133,7 +135,8 @@ public class BindingReflections {
      *
      *
      *
-     * @param possibleMethod Method to check
+     * @param possibleMethod
+     *            Method to check
      * @return true if method is RPC invocation, false otherwise.
      */
     public static boolean isRpcMethod(final Method possibleMethod) {
@@ -146,9 +149,10 @@ public class BindingReflections {
      *
      * Extracts Output class for RPC method
      *
-     * @param targetMethod method to scan
-     * @return Optional.absent() if result type could not be get,
-     *         or return type is Void.
+     * @param targetMethod
+     *            method to scan
+     * @return Optional.absent() if result type could not be get, or return type
+     *         is Void.
      */
     @SuppressWarnings("rawtypes")
     public static Optional<Class<?>> resolveRpcOutputClass(final Method targetMethod) {
@@ -166,7 +170,8 @@ public class BindingReflections {
      *
      * Extracts input class for RPC method
      *
-     * @param targetMethod method to scan
+     * @param targetMethod
+     *            method to scan
      * @return Optional.absent() if rpc has no input, Rpc input type otherwise.
      */
     @SuppressWarnings("unchecked")
@@ -215,7 +220,8 @@ public class BindingReflections {
     /**
      * Returns root package name for suplied package.
      *
-     * @param pkg Package for which find model root package.
+     * @param pkg
+     *            Package for which find model root package.
      * @return Package of model root.
      */
     public static String getModelRootPackageName(final Package pkg) {
@@ -225,7 +231,8 @@ public class BindingReflections {
     /**
      * Returns root package name for supplied package name.
      *
-     * @param name Package for which find model root package.
+     * @param name
+     *            Package for which find model root package.
      * @return Package of model root.
      */
     public static String getModelRootPackageName(final String name) {
@@ -238,12 +245,30 @@ public class BindingReflections {
         return match.group(0);
     }
 
+    public static final QNameModule getQNameModule(Class<?> clz) {
+        if(DataContainer.class.isAssignableFrom(clz) || BaseIdentity.class.isAssignableFrom(clz)) {
+            return findQName(clz).getModule();
+        }
+        try {
+            YangModuleInfo modInfo = BindingReflections.getModuleInfo(clz);
+            return getQNameModule(modInfo);
+        } catch (Exception e) {
+            throw new IllegalStateException("Unable to get QName of defining model.", e);
+        }
+    }
+
+    public static final QNameModule getQNameModule(YangModuleInfo modInfo) {
+        return QNameModule.create(URI.create(modInfo.getNamespace()), QName.parseRevision(modInfo.getRevision()));
+    }
+
     /**
      *
-     * Returns instance of {@link YangModuleInfo} of declaring model for specific class.
+     * Returns instance of {@link YangModuleInfo} of declaring model for
+     * specific class.
      *
      * @param cls
-     * @return Instance of {@link YangModuleInfo} associated with model, from which this class was derived.
+     * @return Instance of {@link YangModuleInfo} associated with model, from
+     *         which this class was derived.
      * @throws Exception
      */
     public static YangModuleInfo getModuleInfo(final Class<?> cls) throws Exception {
@@ -268,7 +293,8 @@ public class BindingReflections {
      *
      * Check if supplied class is derived from YANG model.
      *
-     * @param cls Class to check
+     * @param cls
+     *            Class to check
      * @return true if class is derived from YANG model.
      */
     public static boolean isBindingClass(final Class<?> cls) {
@@ -305,7 +331,7 @@ public class BindingReflections {
      * @return
      */
     public static boolean isNotification(final Class<?> potentialNotification) {
-        checkArgument(potentialNotification != null,"potentialNotification must not be null.");
+        checkArgument(potentialNotification != null, "potentialNotification must not be null.");
         return Notification.class.isAssignableFrom(potentialNotification);
     }
 
@@ -323,21 +349,24 @@ public class BindingReflections {
     }
 
     /**
-    *
-    * Loads {@link YangModuleInfo} infos available on supplied classloader.
-    *
-    * {@link YangModuleInfo} are discovered using {@link ServiceLoader}
-    * for {@link YangModelBindingProvider}. {@link YangModelBindingProvider}
-    * are simple classes which holds only pointers to actual instance
-    * {@link YangModuleInfo}.
-    *
-    * When {@link YangModuleInfo} is available, all dependencies are recursivelly collected
-    * into returning set by collecting results of {@link YangModuleInfo#getImportedModules()}.
-    *
-    *
-    * @param loader Classloader for which {@link YangModuleInfo} should be retrieved.
-    * @return Set of {@link YangModuleInfo} available for supplied classloader.
-    */
+     *
+     * Loads {@link YangModuleInfo} infos available on supplied classloader.
+     *
+     * {@link YangModuleInfo} are discovered using {@link ServiceLoader} for
+     * {@link YangModelBindingProvider}. {@link YangModelBindingProvider} are
+     * simple classes which holds only pointers to actual instance
+     * {@link YangModuleInfo}.
+     *
+     * When {@link YangModuleInfo} is available, all dependencies are
+     * recursivelly collected into returning set by collecting results of
+     * {@link YangModuleInfo#getImportedModules()}.
+     *
+     *
+     * @param loader
+     *            Classloader for which {@link YangModuleInfo} should be
+     *            retrieved.
+     * @return Set of {@link YangModuleInfo} available for supplied classloader.
+     */
     public static ImmutableSet<YangModuleInfo> loadModuleInfos(final ClassLoader loader) {
         Builder<YangModuleInfo> moduleInfoSet = ImmutableSet.<YangModuleInfo> builder();
         ServiceLoader<YangModelBindingProvider> serviceLoader = ServiceLoader.load(YangModelBindingProvider.class,
@@ -362,7 +391,8 @@ public class BindingReflections {
      *
      * Checks if supplied class represents RPC Input / RPC Output.
      *
-     * @param targetType Class to be checked
+     * @param targetType
+     *            Class to be checked
      * @return true if class represents RPC Input or RPC Output class.
      */
     public static boolean isRpcType(final Class<? extends DataObject> targetType) {
@@ -374,9 +404,11 @@ public class BindingReflections {
 
     /**
      *
-     * Scans supplied class and returns an iterable of all data children classes.
+     * Scans supplied class and returns an iterable of all data children
+     * classes.
      *
-     * @param type YANG Modeled Entity derived from DataContainer
+     * @param type
+     *            YANG Modeled Entity derived from DataContainer
      * @return Iterable of all data children, which have YANG modeled entity
      */
     @SuppressWarnings("unchecked")
@@ -394,24 +426,26 @@ public class BindingReflections {
     }
 
     /**
-    *
-    * Scans supplied class and returns an iterable of all data children classes.
-    *
-    * @param type YANG Modeled Entity derived from DataContainer
-    * @return Iterable of all data children, which have YANG modeled entity
-    */
-   public static Map<Class<?>,Method> getChildrenClassToMethod(final Class<?> type) {
-       checkArgument(type != null, "Target type must not be null");
-       checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
-       Map<Class<?>,Method> ret = new HashMap<>();
-       for (Method method : type.getMethods()) {
-           Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method);
-           if (entity.isPresent()) {
-               ret.put(entity.get(),method);
-           }
-       }
-       return ret;
-   }
+     *
+     * Scans supplied class and returns an iterable of all data children
+     * classes.
+     *
+     * @param type
+     *            YANG Modeled Entity derived from DataContainer
+     * @return Iterable of all data children, which have YANG modeled entity
+     */
+    public static Map<Class<?>, Method> getChildrenClassToMethod(final Class<?> type) {
+        checkArgument(type != null, "Target type must not be null");
+        checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
+        Map<Class<?>, Method> ret = new HashMap<>();
+        for (Method method : type.getMethods()) {
+            Optional<Class<? extends DataContainer>> entity = getYangModeledReturnType(method);
+            if (entity.isPresent()) {
+                ret.put(entity.get(), method);
+            }
+        }
+        return ret;
+    }
 
     @SuppressWarnings("unchecked")
     private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method) {
@@ -444,10 +478,9 @@ public class BindingReflections {
             } catch (Exception e) {
                 /*
                  *
-                 * It is safe to log this this exception on debug, since
-                 * this method should not fail. Only failures are possible if
-                 * the runtime / backing.
-                 *
+                 * It is safe to log this this exception on debug, since this
+                 * method should not fail. Only failures are possible if the
+                 * runtime / backing.
                  */
                 LOG.debug("Unable to find YANG modeled return type for {}", method, e);
             }
@@ -467,10 +500,12 @@ public class BindingReflections {
      *
      * Tries to resolve QName for supplied class.
      *
-     * Looks up for static field with name from constant {@link BindingMapping#QNAME_STATIC_FIELD_NAME}
-     * and returns value if present.
+     * Looks up for static field with name from constant
+     * {@link BindingMapping#QNAME_STATIC_FIELD_NAME} and returns value if
+     * present.
      *
-     * If field is not present uses {@link #computeQName(Class)} to compute QName for missing types.
+     * If field is not present uses {@link #computeQName(Class)} to compute
+     * QName for missing types.
      *
      * @param key
      * @return
@@ -489,12 +524,11 @@ public class BindingReflections {
         } catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
             /*
              *
-             * It is safe to log this this exception on debug, since
-             * this method should not fail. Only failures are possible if
-             * the runtime / backing.
-             *
+             * It is safe to log this this exception on debug, since this method
+             * should not fail. Only failures are possible if the runtime /
+             * backing.
              */
-            LOG.debug("Unexpected exception during extracting QName for {}",key,e);
+            LOG.debug("Unexpected exception during extracting QName for {}", key, e);
         }
         return Optional.absent();
     }
@@ -502,76 +536,78 @@ public class BindingReflections {
     /**
      * Computes QName for supplied class
      *
-     * Namespace and revision are same as {@link YangModuleInfo}
-     * associated with supplied class.
+     * Namespace and revision are same as {@link YangModuleInfo} associated with
+     * supplied class.
      * <p>
      * If class is
      * <ul>
-     *  <li>rpc input: local name is "input".
-     *  <li>rpc output: local name is "output".
-     *  <li>augmentation: local name is "module name".
+     * <li>rpc input: local name is "input".
+     * <li>rpc output: local name is "output".
+     * <li>augmentation: local name is "module name".
      * </ul>
      *
-     * There is also fallback, if it is not possible to compute QName
-     * using following algorithm returns module QName.
+     * There is also fallback, if it is not possible to compute QName using
+     * following algorithm returns module QName.
      *
-     * FIXME: Extend this algorithm to also provide QName for YANG modeled simple types.
+     * FIXME: Extend this algorithm to also provide QName for YANG modeled
+     * simple types.
      *
-     * @throws IllegalStateException If YangModuleInfo could not be resolved
-     * @throws IllegalArgumentException If supplied class was not derived from YANG model.
+     * @throws IllegalStateException
+     *             If YangModuleInfo could not be resolved
+     * @throws IllegalArgumentException
+     *             If supplied class was not derived from YANG model.
      *
      */
     @SuppressWarnings({ "rawtypes", "unchecked" })
     private static QName computeQName(final Class key) {
-        if(isBindingClass(key)) {
+        if (isBindingClass(key)) {
             YangModuleInfo moduleInfo;
             try {
                 moduleInfo = getModuleInfo(key);
             } catch (Exception e) {
-                throw new IllegalStateException("Unable to get QName for " + key + ". YangModuleInfo was not found.",e);
+                throw new IllegalStateException("Unable to get QName for " + key + ". YangModuleInfo was not found.", e);
             }
             final QName module = getModuleQName(moduleInfo);
             if (Augmentation.class.isAssignableFrom(key)) {
                 return module;
-            } else if(isRpcType(key)) {
+            } else if (isRpcType(key)) {
                 final String className = key.getSimpleName();
-                if(className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
-                    return QName.create(module,"output");
+                if (className.endsWith(BindingMapping.RPC_OUTPUT_SUFFIX)) {
+                    return QName.create(module, "output");
                 } else {
-                    return QName.create(module,"input");
+                    return QName.create(module, "input");
                 }
             }
             /*
-             *  Fallback for Binding types which fo not have QNAME
-             *  field
+             * Fallback for Binding types which fo not have QNAME field
              */
             return module;
         } else {
-            throw new IllegalArgumentException("Supplied class "+key+"is not derived from YANG.");
+            throw new IllegalArgumentException("Supplied class " + key + "is not derived from YANG.");
         }
     }
 
     /**
      * Given a {@link YangModuleInfo}, create a QName representing it. The QName
-     * is formed by reusing the module's namespace and revision using the module's
-     * name as the QName's local name.
+     * is formed by reusing the module's namespace and revision using the
+     * module's name as the QName's local name.
      *
-     * @param moduleInfo module information
+     * @param moduleInfo
+     *            module information
      * @return QName representing the module
      */
     public static QName getModuleQName(final YangModuleInfo moduleInfo) {
         checkArgument(moduleInfo != null, "moduleInfo must not be null.");
-        return QName.create(moduleInfo.getNamespace(), moduleInfo.getRevision(),
-                moduleInfo.getName());
+        return QName.create(moduleInfo.getNamespace(), moduleInfo.getRevision(), moduleInfo.getName());
     }
 
     /**
      * Extracts augmentation from Binding DTO field using reflection
      *
-     * @param input Instance of DataObject which is augmentable and
-     *      may contain augmentation
-     * @return Map of augmentations if read was successful, otherwise
-     *      empty map.
+     * @param input
+     *            Instance of DataObject which is augmentable and may contain
+     *            augmentation
+     * @return Map of augmentations if read was successful, otherwise empty map.
      */
     public static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Augmentable<?> input) {
         return AugmentationFieldGetter.getGetter(input.getClass()).getAugmentations(input);
@@ -579,46 +615,55 @@ public class BindingReflections {
 
     /**
      *
-     * Determines if two augmentation classes or case classes represents same data.
+     * Determines if two augmentation classes or case classes represents same
+     * data.
      * <p>
      * Two augmentations or cases could be substituted only if and if:
      * <ul>
      * <li>Both implements same interfaces</li>
      * <li>Both have same children</li>
-     * <li>If augmentations: Both have same augmentation target class. Target class was generated for data node in grouping.</li>
-     * <li>If cases: Both are from same choice. Choice class was generated for data node in grouping.</li>
+     * <li>If augmentations: Both have same augmentation target class. Target
+     * class was generated for data node in grouping.</li>
+     * <li>If cases: Both are from same choice. Choice class was generated for
+     * data node in grouping.</li>
      * </ul>
      * <p>
-     * <b>Explanation:</b> Binding Specification reuses classes generated for groupings as part of normal data tree,
-     * this classes from grouping could be used at various locations and user may not be aware of it
-     * and may use incorrect case or augmentation in particular subtree (via copy constructors, etc).
-     *
-     * @param potential Class which is potential substition
-     * @param target Class which should be used at particular subtree
+     * <b>Explanation:</b> Binding Specification reuses classes generated for
+     * groupings as part of normal data tree, this classes from grouping could
+     * be used at various locations and user may not be aware of it and may use
+     * incorrect case or augmentation in particular subtree (via copy
+     * constructors, etc).
+     *
+     * @param potential
+     *            Class which is potential substition
+     * @param target
+     *            Class which should be used at particular subtree
      * @return true if and only if classes represents same data.
      */
-    @SuppressWarnings({"rawtypes","unchecked"})
+    @SuppressWarnings({ "rawtypes", "unchecked" })
     public static boolean isSubstitutionFor(final Class potential, final Class target) {
         HashSet<Class> subImplemented = Sets.newHashSet(potential.getInterfaces());
         HashSet<Class> targetImplemented = Sets.newHashSet(target.getInterfaces());
-        if(!subImplemented.equals(targetImplemented)) {
+        if (!subImplemented.equals(targetImplemented)) {
             return false;
         }
-        if(Augmentation.class.isAssignableFrom(potential)
-                && !BindingReflections.findAugmentationTarget(potential).equals(BindingReflections.findAugmentationTarget(target))) {
-                return false;
+        if (Augmentation.class.isAssignableFrom(potential)
+                && !BindingReflections.findAugmentationTarget(potential).equals(
+                        BindingReflections.findAugmentationTarget(target))) {
+            return false;
         }
-        for(Method potentialMethod : potential.getMethods()) {
+        for (Method potentialMethod : potential.getMethods()) {
             try {
                 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
-                if(!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
+                if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
                     return false;
                 }
             } catch (NoSuchMethodException e) {
-                // Counterpart method is missing, so classes could not be substituted.
+                // Counterpart method is missing, so classes could not be
+                // substituted.
                 return false;
             } catch (SecurityException e) {
-                throw new IllegalStateException("Could not compare methods",e);
+                throw new IllegalStateException("Could not compare methods", e);
             }
         }
         return true;
diff --git a/yang/yang-binding/src/main/java/org/opendaylight/yangtools/yang/binding/util/NotificationListenerInvoker.java b/yang/yang-binding/src/main/java/org/opendaylight/yangtools/yang/binding/util/NotificationListenerInvoker.java
new file mode 100644 (file)
index 0000000..ca37fc1
--- /dev/null
@@ -0,0 +1,122 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.binding.util;
+
+import com.google.common.base.Preconditions;
+import com.google.common.base.Throwables;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableMap.Builder;
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodHandles.Lookup;
+import java.lang.invoke.MethodType;
+import java.lang.reflect.Method;
+import java.util.Map;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.opendaylight.yangtools.yang.binding.DataContainer;
+import org.opendaylight.yangtools.yang.binding.NotificationListener;
+import org.opendaylight.yangtools.yang.common.QName;
+
+/**
+ * Provides single method invocation of notificatoin callbacks on supplied instance.
+ *
+ * Notification Listener invoker provides common invocation interface for any subtype of {@link NotificationListener}.
+ * via {@link #invokeNotification(NotificationListener, QName, DataContainer)} method.
+ *
+ */
+public final class NotificationListenerInvoker {
+
+    private static final Lookup LOOKUP = MethodHandles.publicLookup();
+
+    private static final LoadingCache<Class<? extends NotificationListener>, NotificationListenerInvoker> INVOKERS = CacheBuilder
+            .newBuilder().weakKeys()
+            .build(new CacheLoader<Class<? extends NotificationListener>, NotificationListenerInvoker>() {
+
+                @Override
+                public NotificationListenerInvoker load(Class<? extends NotificationListener> key) throws Exception {
+                    return createInvoker(key);
+                }
+
+            });
+
+    private final Map<QName, MethodHandle> methodInvokers;
+
+    public NotificationListenerInvoker(Map<QName, MethodHandle> map) {
+        this.methodInvokers = map;
+    }
+
+    /**
+     *
+     * Creates RPCServiceInvoker for specified RpcService type
+     *
+     * @param type
+     *            RpcService interface, which was generated from model.
+     * @return Cached instance of {@link NotificationListenerInvoker} for
+     *         supplied RPC type.
+     *
+     */
+    public static NotificationListenerInvoker from(Class<? extends NotificationListener> type) {
+        Preconditions.checkArgument(type.isInterface());
+        Preconditions.checkArgument(BindingReflections.isBindingClass(type));
+        return INVOKERS.getUnchecked(type);
+    }
+
+    /**
+     * Invokes supplied RPC on provided implementation of RPC Service.
+     *
+     * @param impl
+     *            Imlementation on which notifiaction callback should be
+     *            invoked.
+     * @param rpcName
+     *            Name of RPC to be invoked.
+     * @param input
+     *            Input data for RPC.
+     *
+     */
+    public void invokeNotification(@Nonnull NotificationListener impl, @Nonnull QName rpcName,
+            @Nullable DataContainer input) {
+        Preconditions.checkNotNull(impl, "implemetation must be supplied");
+        MethodHandle invoker = methodInvokers.get(rpcName);
+        Preconditions.checkArgument(invoker != null, "Supplied notification is not valid for implementation %s", impl);
+        try {
+            invoker.invokeExact(impl, input);
+        } catch (Throwable e) {
+            throw Throwables.propagate(e);
+        }
+    }
+
+    private static NotificationListenerInvoker createInvoker(Class<? extends NotificationListener> key) {
+        return new NotificationListenerInvoker(createInvokerMap(key));
+    }
+
+    private static Map<QName, MethodHandle> createInvokerMap(Class<? extends NotificationListener> key) {
+        Builder<QName, MethodHandle> ret = ImmutableMap.<QName, MethodHandle> builder();
+        for (Method method : key.getMethods()) {
+            if (BindingReflections.isNotificationCallback(method)) {
+
+                Class<?> notification = method.getParameterTypes()[0];
+                QName name = BindingReflections.findQName(notification);
+                MethodHandle handle;
+                try {
+                    handle = LOOKUP.unreflect(method).asType(
+                            MethodType.methodType(Void.class, NotificationListener.class, DataContainer.class));
+                    ret.put(name, handle);
+                } catch (IllegalAccessException e) {
+                    throw new IllegalStateException("Can not access public method.", e);
+                }
+            }
+
+        }
+        return ret.build();
+    }
+
+}
diff --git a/yang/yang-binding/src/main/java/org/opendaylight/yangtools/yang/binding/util/RpcMethodInvoker.java b/yang/yang-binding/src/main/java/org/opendaylight/yangtools/yang/binding/util/RpcMethodInvoker.java
new file mode 100644 (file)
index 0000000..c93cd8a
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.binding.util;
+
+import com.google.common.base.Optional;
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodHandles.Lookup;
+import java.lang.reflect.Method;
+import java.util.concurrent.Future;
+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.common.RpcResult;
+
+abstract class RpcMethodInvoker {
+
+    private static Lookup LOOKUP = MethodHandles.publicLookup();
+
+    protected abstract Future<RpcResult<?>> invokeOn(RpcService impl, DataObject input);
+
+    protected static RpcMethodInvoker from(Method method) {
+        Optional<Class<? extends DataContainer>> input = BindingReflections.resolveRpcInputClass(method);
+        try {
+            MethodHandle methodHandle = LOOKUP.unreflect(method);
+            if(input.isPresent()) {
+                return new RpcMethodInvokerWithInput(methodHandle);
+            }
+            return new RpcMethodInvokerWithoutInput(methodHandle);
+        } catch (IllegalAccessException e) {
+            throw new IllegalStateException("Lookup on public method failed.",e);
+        }
+
+    }
+
+}
\ No newline at end of file
diff --git a/yang/yang-binding/src/main/java/org/opendaylight/yangtools/yang/binding/util/RpcMethodInvokerWithInput.java b/yang/yang-binding/src/main/java/org/opendaylight/yangtools/yang/binding/util/RpcMethodInvokerWithInput.java
new file mode 100644 (file)
index 0000000..a77dd35
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.binding.util;
+
+import com.google.common.base.Throwables;
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodType;
+import java.util.concurrent.Future;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.RpcService;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+
+class RpcMethodInvokerWithInput extends RpcMethodInvoker {
+
+    private static final MethodType INVOCATION_SIGNATURE = MethodType.methodType(Future.class, RpcService.class,DataObject.class);
+    private final MethodHandle handle;
+
+    RpcMethodInvokerWithInput(MethodHandle methodHandle) {
+        this.handle = methodHandle.asType(INVOCATION_SIGNATURE);
+    }
+
+    @Override
+    public Future<RpcResult<?>> invokeOn(RpcService impl, DataObject input) {
+        try {
+            return (Future<RpcResult<?>>) handle.invokeExact(impl,input);
+        } catch (Throwable e) {
+            throw Throwables.propagate(e);
+        }
+    }
+
+}
\ No newline at end of file
diff --git a/yang/yang-binding/src/main/java/org/opendaylight/yangtools/yang/binding/util/RpcMethodInvokerWithoutInput.java b/yang/yang-binding/src/main/java/org/opendaylight/yangtools/yang/binding/util/RpcMethodInvokerWithoutInput.java
new file mode 100644 (file)
index 0000000..740b98f
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.binding.util;
+
+import com.google.common.base.Throwables;
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodType;
+import java.util.concurrent.Future;
+import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.yangtools.yang.binding.RpcService;
+import org.opendaylight.yangtools.yang.common.RpcResult;
+
+class RpcMethodInvokerWithoutInput extends RpcMethodInvoker {
+
+    private static final MethodType INVOCATION_SIGNATURE = MethodType.methodType(Future.class, RpcService.class);
+    private final MethodHandle handle;
+
+    RpcMethodInvokerWithoutInput(MethodHandle methodHandle) {
+        this.handle = methodHandle.asType(INVOCATION_SIGNATURE);
+    }
+
+    @Override
+    public Future<RpcResult<?>> invokeOn(RpcService impl, DataObject input) {
+        try {
+            return (Future<RpcResult<?>>) handle.invokeExact(impl);
+        } catch (Throwable e) {
+            throw Throwables.propagate(e);
+        }
+    }
+
+}
\ No newline at end of file
diff --git a/yang/yang-binding/src/main/java/org/opendaylight/yangtools/yang/binding/util/RpcServiceInvoker.java b/yang/yang-binding/src/main/java/org/opendaylight/yangtools/yang/binding/util/RpcServiceInvoker.java
new file mode 100644 (file)
index 0000000..849b0a2
--- /dev/null
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.binding.util;
+
+import com.google.common.base.Preconditions;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableMap.Builder;
+import java.lang.reflect.Method;
+import java.util.Map;
+import java.util.concurrent.Future;
+import javax.annotation.Nonnull;
+import javax.annotation.Nullable;
+import org.opendaylight.yangtools.yang.binding.BindingMapping;
+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.RpcResult;
+
+/**
+ * Provides single method invocation of RPCs on supplied instance.
+ *
+ * Rpc Service invoker provides common invocation interface for any subtype of {@link RpcService}.
+ * via {@link #invokeRpc(RpcService, QName, DataObject)} method.
+ *
+ *
+ *
+ */
+public final class RpcServiceInvoker {
+
+    private static final LoadingCache<Class<? extends RpcService>, RpcServiceInvoker> INVOKERS = CacheBuilder.newBuilder()
+            .weakKeys()
+            .build(new CacheLoader<Class<? extends RpcService>, RpcServiceInvoker>() {
+
+                @Override
+                public RpcServiceInvoker load(Class<? extends RpcService> key) throws Exception {
+                    return createInvoker(key);
+                }
+
+            });
+
+    private final Map<String, RpcMethodInvoker> methodInvokers;
+
+    private RpcServiceInvoker(Map<String, RpcMethodInvoker> methodInvokers) {
+        this.methodInvokers  = Preconditions.checkNotNull(methodInvokers);
+    }
+
+    /**
+     *
+     * Creates RPCServiceInvoker for specified RpcService type
+     *
+     * @param type RpcService interface, which was generated from model.
+     * @return Cached instance of {@link RpcServiceInvoker} for supplied RPC type.
+     *
+     */
+    public static RpcServiceInvoker from(Class<? extends RpcService> type) {
+        Preconditions.checkArgument(type.isInterface());
+        Preconditions.checkArgument(BindingReflections.isBindingClass(type));
+        return INVOKERS.getUnchecked(type);
+    }
+
+    /**
+     * Invokes supplied RPC on provided implementation of RPC Service.
+     *
+     * @param impl Imlementation on which RPC should be invoked.
+     * @param rpcName Name of RPC to be invoked.
+     * @param input Input data for RPC.
+     * @return Future which will complete once rpc procesing is finished.
+     */
+    public Future<RpcResult<?>> invokeRpc(@Nonnull RpcService impl, @Nonnull QName rpcName,@Nullable DataObject input ) {
+        Preconditions.checkNotNull(impl, "implemetation must be supplied");
+        return invoke(impl,BindingMapping.getMethodName(rpcName),input);
+    }
+
+    private static RpcServiceInvoker createInvoker(Class<? extends RpcService> key) {
+        return new RpcServiceInvoker(createInvokerMap(key));
+    }
+
+    private static Map<String, RpcMethodInvoker> createInvokerMap(Class<? extends RpcService> key) {
+        Builder<String, RpcMethodInvoker> ret = ImmutableMap.<String, RpcMethodInvoker>builder();
+        for(Method method : key.getMethods()) {
+            if(BindingReflections.isRpcMethod(method)) {
+                ret.put(method.getName(), RpcMethodInvoker.from(method));
+            }
+
+        }
+        return ret.build();
+    }
+
+    private Future<RpcResult<?>> invoke(RpcService impl, String methodName, DataObject input) {
+        RpcMethodInvoker invoker = methodInvokers.get(methodName);
+        Preconditions.checkArgument(invoker != null,"Supplied rpc is not valid for implementation %s",impl);
+        return invoker.invokeOn(impl, input);
+    }
+}
index 5554efe66c60bf1a23d43ad59d1b15161648a915..7bbfb8828528a18e032c88e056273d4e46ee54d0 100644 (file)
@@ -8,27 +8,26 @@
 package org.opendaylight.yangtools.yang.data.api;
 
 import java.util.Map;
-
 import org.opendaylight.yangtools.yang.common.QName;
 
 /**
- * 
- * Container of attributes, which may be attached to {@link Node}
- * 
+ *
+ * Container of attributes, which may be attached to nodes.
+ *
  */
 public interface AttributesContainer {
 
     /**
      * Returns immutable map of QName and value of the attribute.
-     * 
+     *
      * @return immutable map of attribute names and values.
      */
     Map<QName, String> getAttributes();
 
     /**
      * Returns attribute value by supplied QName
-     * 
-     * 
+     *
+     *
      * @param name Attribute name
      * @return Value of attribute if present, null otherwise.
      */
diff --git a/yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/CompositeNode.java b/yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/CompositeNode.java
deleted file mode 100644 (file)
index 4b96bdc..0000000
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.api;
-
-import java.util.List;
-import java.util.Map;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
-
-/**
- * Composite node represents a branch in the data tree, which could contain
- * nested composite nodes or leaf nodes. In the terms of the XML the simple node
- * is element which does not text data directly (CDATA or PCDATA), only other
- * nodes. The composite node is the manifestation of the following data schema
- * constructs in the YANG:
- *
- * <ul>
- * <li><b>container</b> - the composite node represents the YANG container and
- * could contain all children schema nodes of that container</li>
- * <li><b>item</b> in the <b>list</b> - the composite node represents one item
- * in the YANG list and could contain all children schema nodes of that list
- * item.</li>
- * <li><b>anyxml</b></li>
- * </ul>
- *
- * @deprecated Use {@link NormalizedNodeContainer} instead.
- */
-@Deprecated
-public interface CompositeNode extends Node<List<Node<?>>>, NodeModification, Map<QName,List<Node<?>>> {
-
-    /**
-     * Returns a list of children as seens in resulting XML serialization
-     * defined by YANG specification.
-     *
-     * @return
-     *
-     * @deprecated Use {@link #getValue()} instead.
-     */
-    @Deprecated
-    List<Node<?>> getChildren();
-
-    List<CompositeNode> getCompositesByName(QName children);
-
-    List<CompositeNode> getCompositesByName(String children);
-
-    List<SimpleNode<?>> getSimpleNodesByName(QName children);
-
-    List<SimpleNode<?>> getSimpleNodesByName(String children);
-
-    CompositeNode getFirstCompositeByName(QName container);
-
-    SimpleNode<?> getFirstSimpleByName(QName leaf);
-
-    /**
-     * @return cast self to mutable, if possible
-     */
-    @Deprecated
-    MutableCompositeNode asMutable();
-
-}
diff --git a/yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/MutableCompositeNode.java b/yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/MutableCompositeNode.java
deleted file mode 100644 (file)
index 9aa3a4a..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.api;
-
-import java.util.List;
-
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
-
-
-/**
- * @author michal.rehak
- *
- * @deprecated Deprecated in favor of {@link NormalizedNodeContainer} classes.
- */
-@Deprecated
-public interface MutableCompositeNode extends MutableNode<List<Node<?>>>, CompositeNode {
-
-    /**
-     * update internal map
-     */
-    @Deprecated
-    void init();
-
-    /**
-     * @return original node, if available
-     */
-    CompositeNode getOriginal();
-}
diff --git a/yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/MutableNode.java b/yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/MutableNode.java
deleted file mode 100644 (file)
index 4713eac..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.api;
-
-import org.opendaylight.yangtools.concepts.Mutable;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-
-/**
- * Base representation of node in the data tree, defines basic parameters of
- * node such as a QName.
- *
- *
- * @param <T>
- *
- * @deprecated Use {@link NormalizedNode} instead.
- */
-@Deprecated
-public interface MutableNode<T> extends Node<T>,Mutable {
-
-    /**
-     * @param parent value to set
-     */
-    void setParent(CompositeNode parent);
-
-    /**
-     * @param value value to set (children list or leaf value)
-     */
-    @Override
-    T setValue(T value);
-
-    /**
-     * @param action value to set
-     */
-    void setModifyAction(ModifyAction action);
-}
diff --git a/yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/MutableSimpleNode.java b/yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/MutableSimpleNode.java
deleted file mode 100644 (file)
index 2dcd0a2..0000000
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.api;
-
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-
-/**
- * @author michal.rehak
- * @param <T> node value type
- *
- * @deprecated Use {@link NormalizedNode} instead.
- */
-@Deprecated
-public interface MutableSimpleNode<T> extends MutableNode<T>, SimpleNode<T> {
-
-    /**
-     * @return original node, if available
-     */
-    SimpleNode<T> getOriginal();
-
-}
diff --git a/yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/Node.java b/yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/Node.java
deleted file mode 100644 (file)
index 9057b74..0000000
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.api;
-
-import java.util.Map.Entry;
-
-import org.opendaylight.yangtools.yang.common.QName;
-
-/**
- * Base representation of node in the data tree, defines basic parameters of
- * node such as a QName.
- *
- *
- * @param <T>
- */
-public interface Node<T> extends Entry<QName, T> {
-
-    /**
-     * Returns the name of the Node
-     *
-     * @return qName of node
-     */
-    QName getNodeType();
-
-    /**
-     * Returns parent node
-     *
-     * @return parent node
-     * @deprecated Unused, Deprecated because  reference to parent disallows of sharing one instance
-     *   in multiple trees / subtress.
-     */
-    @Deprecated
-    CompositeNode getParent();
-
-    /**
-     * Returns the value that holds current node, if no value is defined method
-     * can return <code>null</code>
-     *
-     * @return Returns the value that holds current node.
-     */
-    @Override
-    T getValue();
-}
diff --git a/yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/NodeModificationBuilder.java b/yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/NodeModificationBuilder.java
deleted file mode 100644 (file)
index 5b37afe..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.api;
-
-
-/**
- * @author michal.rehak
- *
- * @deprecated Use {@link org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes} instead.
- */
-@Deprecated
-public interface NodeModificationBuilder {
-
-    Node<?> getMutableEquivalent(Node<?> originalNode);
-
-    CompositeNode buildDiffTree();
-
-    void mergeNode(MutableCompositeNode alteredNode);
-
-    void removeNode(MutableCompositeNode deadNode);
-
-    void removeNode(MutableSimpleNode<?> deadNode);
-
-    void deleteNode(MutableSimpleNode<?> deadNode);
-
-    void deleteNode(MutableCompositeNode deadNode);
-
-    void replaceNode(MutableCompositeNode replacementNode);
-
-    void replaceNode(MutableSimpleNode<?> replacementNode);
-
-    void addNode(MutableCompositeNode newNode);
-
-    void addNode(MutableSimpleNode<?> newNode);
-
-}
diff --git a/yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/SimpleNode.java b/yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/SimpleNode.java
deleted file mode 100644 (file)
index 59bb53d..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.api;
-
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-/**
- * Simple node represents a leaf in the data tree, which does not contain any
- * nested nodes, but the value of node. In the terms of the XML the simple node
- * is element which contains only text data (CDATA or PCDATA). The simple node
- * is the manifestation of the following data schema constructs in YANG:
- * <ul>
- * <li><b>leaf</b> - simple node could represent YANG leafs of all types except
- * the empty type, which in XML form is similar to the empty container.</li>
- * <li><b>item</b> in <b>leaf-list</b></li>
- * </ul>
- *
- *
- * @param <T>
- *
- * @deprecated Use {@link NormalizedNode} instead.
- */
-@Deprecated
-public interface SimpleNode<T> extends Node<T>, NodeModification {
-
-    /**
-     * @return cast self to mutable, if possible
-     */
-    MutableSimpleNode<T> asMutable();
-}
diff --git a/yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/codec/DataNodeCodec.java b/yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/codec/DataNodeCodec.java
deleted file mode 100644 (file)
index 86be5c6..0000000
+++ /dev/null
@@ -1,19 +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.yangtools.yang.data.api.codec;
-
-import org.opendaylight.yangtools.concepts.Codec;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-public interface DataNodeCodec<I> extends Codec<I, Node<?>> {
-    @Override
-    Node<?> deserialize(I input);
-
-    @Override
-    I serialize(Node<?> input);
-}
index 32491508fb1daddb4f9a85a143c5d7d6e23c31a8..a2bd7a72de76cb27a7ac741fe7ffcbc3712cc533 100644 (file)
@@ -7,50 +7,22 @@
  */
 package org.opendaylight.yangtools.yang.data.api.schema;
 
+import javax.xml.transform.dom.DOMSource;
 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
-import org.opendaylight.yangtools.yang.data.api.Node;
 
 /**
  * Anyxml normalizedNode.
- *
- * <p>
- * This node contains values for anyxml as either SimpleNode or CompositeNode.
- * The concrete value depends on the current value of anyxml node.
- * </p>
- *
- * <p>
- * For yang node: anyxml foo;
- *
- * <ul>
- * <li>
- * with xml value:
- * <pre>
- * {@code <foo>justSomeString</foo>}
- * </pre>
- * this AnyXmlNode returns SimpleNode with QName{namespace=someNamespace, revision=someRevision, localName=foo} and value="justSomeString"
- * </li>
- *
- * <li>
- * but with xml value:
- * <pre>
- * {@code <foo><bar>stringInXml</bar></foo>}
- * </pre>
- * this AnyXmlNode returns CompositeNode with QName{}namespace=someNamespace, revision=someRevision, localName=foo}
- * and values [SimpleNode with QName{}namespace=someNamespace, revision=someRevision, localName=bar} and value="stringInXml"]
- * </li>
- *
- * </ul>
  */
-public interface AnyXmlNode extends AttributesContainer, DataContainerChild<NodeIdentifier, Node<?>> {
+public interface AnyXmlNode extends AttributesContainer, DataContainerChild<NodeIdentifier, DOMSource> {
 
     @Override
     NodeIdentifier getIdentifier();
 
     /**
-     * @return anyxml node value represented as SimpleNode or CompositeNode.
-     * Returned node contains top level element that duplicates the anyxml node.
+     * @return anyxml node value represented as DOMSource.
+     * Returned source contains top level element that duplicates the anyxml node.
      */
     @Override
-    Node<?> getValue();
+    DOMSource getValue();
 }
index 71fa5c705a47a6395bfdf92a0fd71d6e66cc071f..2086542bf8980db133f14798773b20a2dcd46263 100644 (file)
@@ -7,6 +7,7 @@
  */
 package org.opendaylight.yangtools.yang.data.api.schema;
 
+import java.util.Collection;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
@@ -16,7 +17,7 @@ import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 /**
  *
  * Data instance of <code>augment</code> assiociated with parent node.
- * 
+ *
  * Augmentation is addition of subtree defined by other external YANG Model and
  * is schema for subtree is described by instance of  {@link AugmentationSchema}
  * associated with parent node of this node.
@@ -27,22 +28,22 @@ import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 public interface AugmentationNode extends //
     MixinNode, //
     DataContainerNode<AugmentationIdentifier>,
-    DataContainerChild<YangInstanceIdentifier.AugmentationIdentifier, Iterable<DataContainerChild<? extends PathArgument, ?>>> {
+    DataContainerChild<YangInstanceIdentifier.AugmentationIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> {
 
     /**
      * Gets identifier of augmentation node
-     * 
-     * Returned identifier of augmentation node contains all possible 
+     *
+     * Returned identifier of augmentation node contains all possible
      * direct child QNames.
-     * 
+     *
      * This is sufficient to identify instance of augmentation,
      * since RFC6020 states that <code>augment</code> that augment
-     * statement must not add multiple nodes from same namespace 
+     * statement must not add multiple nodes from same namespace
      * / module
      * to the target node.
-     * 
+     *
      * @return Identifier which uniquelly identifies augmentation in particular subtree.
-     * 
+     *
      */
     @Override
     public AugmentationIdentifier getIdentifier();
index dd18d47f9d8abaf6713d628dd43c99d44b5cf705..bba23440f04be438a65625de1d308a4939589998 100644 (file)
@@ -7,6 +7,7 @@
  */
 package org.opendaylight.yangtools.yang.data.api.schema;
 
+import java.util.Collection;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 
@@ -25,6 +26,6 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgum
 public interface ChoiceNode extends //
         MixinNode, //
         DataContainerNode<NodeIdentifier>,
-        DataContainerChild<NodeIdentifier, Iterable<DataContainerChild<? extends PathArgument, ?>>> {
+        DataContainerChild<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> {
 
 }
index 7872466b35e66af604758778254ba41ac78236b5..ee42baadb4d4b2148a456d77a9c82809b00a2f71 100644 (file)
@@ -7,21 +7,22 @@
  */
 package org.opendaylight.yangtools.yang.data.api.schema;
 
+import java.util.Collection;
 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 
 /**
  * Data subtree with cardinality 0..1 in the context of parent node
- * 
+ *
  * Node which does not have value but contains valid {@link DataContainerChild} nodes.
- * 
+ *
  * Schema of this node is described by instance of {@link org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode}.
- * 
+ *
  */
 public interface ContainerNode extends //
         AttributesContainer,
         DataContainerNode<NodeIdentifier>,
-        DataContainerChild<NodeIdentifier, Iterable<DataContainerChild<? extends PathArgument, ?>>> {
+        DataContainerChild<NodeIdentifier, Collection<DataContainerChild<? extends PathArgument, ?>>> {
 
 }
index a9e90d566e1c1245c6aa8a503ad9897d813a7587..1900a5ee27068f1dae3f522b0456cdf037fe857e 100644 (file)
@@ -6,6 +6,7 @@
  */
 package org.opendaylight.yangtools.yang.data.api.schema;
 
+import java.util.Collection;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 
 /**
@@ -42,5 +43,5 @@ public interface DataContainerNode<K extends PathArgument> extends //
      * @return Iteration of all child nodes
      */
     @Override
-    Iterable<DataContainerChild<? extends PathArgument, ?>> getValue();
+    Collection<DataContainerChild<? extends PathArgument, ?>> getValue();
 }
index cff390d6dfea5903a77e18a77862ce33014e5ca8..35f4fb43ff192b29ec7656e690dd5eaab15535dd 100644 (file)
@@ -7,6 +7,7 @@
  */
 package org.opendaylight.yangtools.yang.data.api.schema;
 
+import java.util.Collection;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
 
@@ -21,7 +22,7 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithV
  */
 public interface LeafSetNode<T> extends
     MixinNode, //
-    DataContainerChild<NodeIdentifier, Iterable<LeafSetEntryNode<T>>>, //
+    DataContainerChild<NodeIdentifier, Collection<LeafSetEntryNode<T>>>, //
     NormalizedNodeContainer<NodeIdentifier, NodeWithValue,LeafSetEntryNode<T>> {
 
 }
index d906050dea057a4053d4eff09d0c24c2edcb595c..e5631d4e7f387d65e1310c1de88069d074258d86 100644 (file)
@@ -7,6 +7,7 @@
  */
 package org.opendaylight.yangtools.yang.data.api.schema;
 
+import java.util.Collection;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
 
@@ -21,7 +22,7 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdent
  */
 public interface MapNode extends //
         MixinNode,
-        DataContainerChild<NodeIdentifier, Iterable<MapEntryNode>>,
+        DataContainerChild<NodeIdentifier, Collection<MapEntryNode>>,
         NormalizedNodeContainer<NodeIdentifier, NodeIdentifierWithPredicates, MapEntryNode> {
 
 }
index b416f78fa1e6f88d24144168f287f0eeba6a6d5d..52e5937b9065155537eb9195e2b74fb006b303c9 100644 (file)
@@ -6,21 +6,21 @@
  */
 package org.opendaylight.yangtools.yang.data.api.schema;
 
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
-
 import com.google.common.base.Optional;
+import java.util.Collection;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 
 /**
  * Node which is not leaf, but has child {@link NormalizedNode}s as its valzue.
- * 
- * 
+ *
+ *
  * NormalizedNodeContainer does not have a value, but it has a child
  * nodes. Definition of possible and valid child nodes is introduced
  * in subclasses of this interface.
- * 
+ *
  * This interface should not be used directly, but rather use of of derived subinterfaces
  * such as {@link DataContainerNode}, {@link MapNode}, {@link LeafSetNode}.
- * 
+ *
  * @param <I>
  *            Node Identifier type
  * @param <K>
@@ -29,21 +29,21 @@ import com.google.common.base.Optional;
  *            Child Node type
  */
 public interface NormalizedNodeContainer<I extends PathArgument, K extends PathArgument, V extends NormalizedNode<? extends K, ?>>
-        extends NormalizedNode<I, Iterable<V>> {
+        extends NormalizedNode<I, Collection<V>> {
 
     @Override
     I getIdentifier();
 
     /**
      * Returns immutable iteration of child nodes of this node.
-     * 
+     *
      */
     @Override
-    Iterable<V> getValue();
+    Collection<V> getValue();
 
     /**
      * Returns child node identified by provided key.
-     * 
+     *
      * @param child
      *            Path argument identifying child node
      * @return Optional with child node if child exists.
index 5f305d988c02e5d691e00405bff98775596ff950..a9dc73e5c697dc53660f87f170f10c7a46d3c6de 100644 (file)
@@ -11,6 +11,7 @@ import static com.google.common.base.Preconditions.checkNotNull;
 import com.google.common.annotations.Beta;
 import com.google.common.base.Optional;
 import com.google.common.base.Strings;
+import java.util.Arrays;
 import java.util.Iterator;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
@@ -38,18 +39,37 @@ public final class NormalizedNodes {
         }
     }
 
-    public static Optional<NormalizedNode<?, ?>> findNode(final NormalizedNode<?, ?> tree, final YangInstanceIdentifier path) {
-        checkNotNull(tree, "Tree must not be null");
-        checkNotNull(path, "Path must not be null");
+    public static Optional<NormalizedNode<?, ?>> findNode(final Optional<NormalizedNode<?, ?>> parent, final Iterable<PathArgument> relativePath) {
+        checkNotNull(parent, "Parent must not be null");
+        checkNotNull(relativePath, "Relative path must not be null");
 
-        Optional<NormalizedNode<?, ?>> currentNode = Optional.<NormalizedNode<?, ?>> of(tree);
-        final Iterator<PathArgument> pathIterator = path.getPathArguments().iterator();
+        Optional<NormalizedNode<?, ?>> currentNode = parent;
+        final Iterator<PathArgument> pathIterator = relativePath.iterator();
         while (currentNode.isPresent() && pathIterator.hasNext()) {
             currentNode = getDirectChild(currentNode.get(), pathIterator.next());
         }
         return currentNode;
     }
 
+    public static Optional<NormalizedNode<?, ?>> findNode(final Optional<NormalizedNode<?, ?>> parent, final PathArgument... relativePath) {
+        return findNode(parent, Arrays.asList(relativePath));
+    }
+
+    public static Optional<NormalizedNode<?, ?>> findNode(final NormalizedNode<?, ?> parent, final Iterable<PathArgument> relativePath) {
+        return findNode(Optional.<NormalizedNode<?, ?>>fromNullable(parent), relativePath);
+    }
+
+    public static Optional<NormalizedNode<?, ?>> findNode(final NormalizedNode<?, ?> parent, final PathArgument... relativePath) {
+        return findNode(parent, Arrays.asList(relativePath));
+    }
+
+    public static Optional<NormalizedNode<?, ?>> findNode(final NormalizedNode<?, ?> tree, final YangInstanceIdentifier path) {
+        checkNotNull(tree, "Tree must not be null");
+        checkNotNull(path, "Path must not be null");
+
+        return findNode(Optional.<NormalizedNode<?, ?>>of(tree), path.getPathArguments());
+    }
+
     @SuppressWarnings({ "unchecked", "rawtypes" })
     public static Optional<NormalizedNode<?, ?>> getDirectChild(final NormalizedNode<?, ?> node, final PathArgument pathArg) {
         if (node instanceof LeafNode<?> || node instanceof LeafSetEntryNode<?>) {
index 5d37b7dffaf9ed3cca89dd1e1fa4391b61a65371..3919c71fbafe826183df312ef5ad9b140bd59087 100644 (file)
@@ -7,16 +7,17 @@
  */
 package org.opendaylight.yangtools.yang.data.api.schema;
 
+import java.util.Collection;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 
 /**
  *
  * Normalized Node container which preserves user supplied ordering
- * and allows addressing of child elements by positiion.
+ * and allows addressing of child elements by position.
  *
- * @param <V>
+ * @param <V> child type
  */
-public interface OrderedNodeContainer<V extends NormalizedNode<?, ?>> extends MixinNode, NormalizedNode<NodeIdentifier, Iterable<V>> {
+public interface OrderedNodeContainer<V extends NormalizedNode<?, ?>> extends MixinNode, NormalizedNode<NodeIdentifier, Collection<V>> {
 
     /**
      * Returns child node by position
index 855705d36f5db5f79795893ca564a397fb7d4ecd..dfa06938e7de873f8b8b3ae6a32800bbd8f69702 100644 (file)
@@ -7,6 +7,7 @@
  */
 package org.opendaylight.yangtools.yang.data.api.schema;
 
+import java.util.Collection;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 
 
@@ -26,7 +27,7 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdent
  *
  */
 public interface UnkeyedListNode extends
-    DataContainerChild<NodeIdentifier, Iterable<UnkeyedListEntryNode>>,
+    DataContainerChild<NodeIdentifier, Collection<UnkeyedListEntryNode>>,
     OrderedNodeContainer<UnkeyedListEntryNode> {
 
 }
diff --git a/yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/schema/stream/NormalizedNodeStreamAttributeWriter.java b/yang/yang-data-api/src/main/java/org/opendaylight/yangtools/yang/data/api/schema/stream/NormalizedNodeStreamAttributeWriter.java
new file mode 100644 (file)
index 0000000..ca0e342
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.api.schema.stream;
+
+import java.io.IOException;
+import java.util.Map;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+
+/**
+ * Extension to the NormalizedNodeStreamWriter with attribute support
+ */
+public interface NormalizedNodeStreamAttributeWriter extends NormalizedNodeStreamWriter {
+
+    void leafNode(YangInstanceIdentifier.NodeIdentifier name, Object value, Map<QName, String> attributes) throws IOException, IllegalArgumentException;
+
+    void leafSetEntryNode(Object value, Map<QName, String> attributes) throws IOException, IllegalArgumentException;
+
+    void startContainerNode(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint, Map<QName, String> attributes) throws IOException, IllegalArgumentException;
+
+    void startUnkeyedListItem(YangInstanceIdentifier.NodeIdentifier name, int childSizeHint, Map<QName, String> attributes) throws IOException, IllegalStateException;
+
+    void startMapEntryNode(YangInstanceIdentifier.NodeIdentifierWithPredicates identifier, int childSizeHint, Map<QName, String> attributes) throws IOException, IllegalArgumentException;
+}
index 6a19b45f376a02b5d0346f3a28a7b704f0c6e098..9a0a7bd499cdee49001a55d001d888c6041734ba 100644 (file)
@@ -14,15 +14,12 @@ import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import com.google.common.base.Predicate;
 import com.google.common.collect.Iterables;
-
 import java.io.Closeable;
 import java.io.Flushable;
 import java.io.IOException;
 import java.util.Collection;
 import java.util.Set;
-
 import javax.xml.stream.XMLStreamReader;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
@@ -137,11 +134,19 @@ public class NormalizedNodeWriter implements Closeable, Flushable {
     private boolean wasProcessAsSimpleNode(final NormalizedNode<?, ?> node) throws IOException {
         if (node instanceof LeafSetEntryNode) {
             final LeafSetEntryNode<?> nodeAsLeafList = (LeafSetEntryNode<?>)node;
-            writer.leafSetEntryNode(nodeAsLeafList.getValue());
+            if(writer instanceof NormalizedNodeStreamAttributeWriter) {
+                ((NormalizedNodeStreamAttributeWriter) writer).leafSetEntryNode(nodeAsLeafList.getValue(), nodeAsLeafList.getAttributes());
+            } else {
+                writer.leafSetEntryNode(nodeAsLeafList.getValue());
+            }
             return true;
         } else if (node instanceof LeafNode) {
             final LeafNode<?> nodeAsLeaf = (LeafNode<?>)node;
-            writer.leafNode(nodeAsLeaf.getIdentifier(), nodeAsLeaf.getValue());
+            if(writer instanceof NormalizedNodeStreamAttributeWriter) {
+                ((NormalizedNodeStreamAttributeWriter) writer).leafNode(nodeAsLeaf.getIdentifier(), nodeAsLeaf.getValue(), nodeAsLeaf.getAttributes());
+            } else {
+                writer.leafNode(nodeAsLeaf.getIdentifier(), nodeAsLeaf.getValue());
+            }
             return true;
         } else if (node instanceof AnyXmlNode) {
             final AnyXmlNode anyXmlNode = (AnyXmlNode)node;
@@ -169,14 +174,23 @@ public class NormalizedNodeWriter implements Closeable, Flushable {
     }
 
     protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
-        writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
+        if(writer instanceof NormalizedNodeStreamAttributeWriter) {
+            ((NormalizedNodeStreamAttributeWriter) writer)
+                    .startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()), node.getAttributes());
+        } else {
+            writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
+        }
         return writeChildren(node.getValue());
     }
 
     private boolean wasProcessedAsCompositeNode(final NormalizedNode<?, ?> node) throws IOException {
         if (node instanceof ContainerNode) {
             final ContainerNode n = (ContainerNode) node;
-            writer.startContainerNode(n.getIdentifier(), childSizeHint(n.getValue()));
+            if(writer instanceof NormalizedNodeStreamAttributeWriter) {
+                ((NormalizedNodeStreamAttributeWriter) writer).startContainerNode(n.getIdentifier(), childSizeHint(n.getValue()), n.getAttributes());
+            } else {
+                writer.startContainerNode(n.getIdentifier(), childSizeHint(n.getValue()));
+            }
             return writeChildren(n.getValue());
         }
         if (node instanceof MapEntryNode) {
@@ -231,7 +245,12 @@ public class NormalizedNodeWriter implements Closeable, Flushable {
 
         @Override
         protected boolean writeMapEntryNode(final MapEntryNode node) throws IOException {
-            getWriter().startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
+            final NormalizedNodeStreamWriter writer = getWriter();
+            if(writer instanceof NormalizedNodeStreamAttributeWriter) {
+                ((NormalizedNodeStreamAttributeWriter) writer).startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()), node.getAttributes());
+            } else {
+                writer.startMapEntryNode(node.getIdentifier(), childSizeHint(node.getValue()));
+            }
 
             final Set<QName> qnames = node.getIdentifier().getKeyValues().keySet();
             // Write out all the key children
index 047d71e481bccae3df5bffd2014f6c9b12e94f80..3c2c299fff8735852f988dabb8773843bfb75e8d 100644 (file)
@@ -40,6 +40,11 @@ public enum ModificationType {
      * contents, it has been merged. This means that any incoming nodes which
      * were present in the tree have been replaced, but their child nodes have
      * been retained.
+     *
+     * @deprecated This value is never reported. Whenever it would be reported, based
+     *             on the actual effects, either {@link #WRITE} or {@link #SUBTREE_MODIFIED}
+     *             is reported.
      */
+    @Deprecated
     MERGE,
 }
index 94646531a8cf0ed607b00af1620abada67117b58..9b3f3d2ac4e12f942b43eb4943b048c677f08bc8 100644 (file)
@@ -8,7 +8,6 @@
 package org.opendaylight.yangtools.yang.data.codec.gson;
 
 import com.google.common.base.Preconditions;
-
 import org.opendaylight.yangtools.concepts.Codec;
 import org.opendaylight.yangtools.yang.data.api.codec.BooleanCodec;
 import org.opendaylight.yangtools.yang.data.api.codec.DecimalCodec;
@@ -39,16 +38,18 @@ abstract class AbstractJSONCodec<T> implements JSONCodec<T> {
      * @param codec underlying codec
      * @return A JSONCodec instance
      */
-    public static <T> JSONCodec<T> create(final Codec<String, T> codec) {
-        if (codec instanceof BooleanCodec || codec instanceof DecimalCodec ||
-                codec instanceof Int8Codec || codec instanceof Int16Codec ||
-                codec instanceof Int32Codec || codec instanceof Int64Codec ||
-                codec instanceof Uint8Codec || codec instanceof Uint16Codec ||
-                codec instanceof Uint32Codec || codec instanceof Uint64Codec) {
-            return new UnquotedJSONCodec<>(codec);
+    public static JSONCodec<?> create(final Codec<String, ?> codec) {
+        if (codec instanceof BooleanCodec) {
+            return new BooleanJSONCodec((BooleanCodec<String>) codec);
+        } else if (codec instanceof DecimalCodec || codec instanceof Int8Codec
+                || codec instanceof Int16Codec || codec instanceof Int32Codec
+                || codec instanceof Int64Codec || codec instanceof Uint8Codec
+                || codec instanceof Uint16Codec || codec instanceof Uint32Codec
+                || codec instanceof Uint64Codec) {
+            return new NumberJSONCodec(codec);
+        } else {
+            return new QuotedJSONCodec<>(codec);
         }
-
-        return new QuotedJSONCodec<>(codec);
     }
 
     @Override
diff --git a/yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/BooleanJSONCodec.java b/yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/BooleanJSONCodec.java
new file mode 100644 (file)
index 0000000..0840cd4
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.codec.gson;
+
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import org.opendaylight.yangtools.concepts.Codec;
+
+/**
+ * A {@link JSONCodec} which does not need double quotes in output representation.
+ *
+ * @param <T> Deserialized value type
+ */
+final class BooleanJSONCodec extends AbstractJSONCodec<Boolean> {
+    BooleanJSONCodec(final Codec<String, Boolean> codec) {
+        super(codec);
+    }
+
+    @Override
+    public boolean needQuotes() {
+        return false;
+    }
+
+    /**
+     * Serialize specified value with specified JsonWriter.
+     *
+     * @param writer JsonWriter
+     * @param value
+     */
+    @Override
+    public void serializeToWriter(JsonWriter writer, Boolean value) throws IOException {
+        writer.value(value);
+    };
+}
\ No newline at end of file
index 6f840bb3d67ab96ee89829b69a9eadd7f247c66e..b7ab6fa19bef10d50eccd9dc9f612c3b0e1f5022 100644 (file)
@@ -8,10 +8,9 @@
 package org.opendaylight.yangtools.yang.data.codec.gson;
 
 import java.io.IOException;
-
 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 
 /**
@@ -23,7 +22,7 @@ class ChoiceNodeDataWithSchema extends CompositeNodeDataWithSchema {
 
     private CaseNodeDataWithSchema caseNodeDataWithSchema;
 
-    public ChoiceNodeDataWithSchema(final ChoiceNode schema) {
+    public ChoiceNodeDataWithSchema(final ChoiceSchemaNode schema) {
         super(schema);
     }
 
index ee2541d8e651888fd4062db56828e0046b3a8168..d34712e4f12909e8dbecdebd87cdc76989d9ac73 100644 (file)
@@ -27,7 +27,7 @@ import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
@@ -71,9 +71,9 @@ class CompositeNodeDataWithSchema extends AbstractNodeDataWithSchema {
 
         // The choice/case mess, reuse what we already popped
         final DataSchemaNode choiceCandidate = schema;
-        Preconditions.checkArgument(choiceCandidate instanceof ChoiceNode,
+        Preconditions.checkArgument(choiceCandidate instanceof ChoiceSchemaNode,
             "Expected node of type ChoiceNode but was %s", choiceCandidate.getClass().getSimpleName());
-        final ChoiceNode choiceNode = (ChoiceNode) choiceCandidate;
+        final ChoiceSchemaNode choiceNode = (ChoiceSchemaNode) choiceCandidate;
 
         final DataSchemaNode caseCandidate = schemas.pop();
         Preconditions.checkArgument(caseCandidate instanceof ChoiceCaseNode,
@@ -96,7 +96,7 @@ class CompositeNodeDataWithSchema extends AbstractNodeDataWithSchema {
         CompositeNodeDataWithSchema caseNodeDataWithSchema = findChoice(childNodes, choiceCandidate, caseCandidate);
         if (caseNodeDataWithSchema == null) {
             ChoiceNodeDataWithSchema choiceNodeDataWithSchema = new ChoiceNodeDataWithSchema(choiceNode);
-            addChild(choiceNodeDataWithSchema);
+            childNodes.add(choiceNodeDataWithSchema);
             caseNodeDataWithSchema = choiceNodeDataWithSchema.addCompositeChild(caseNode);
         }
 
@@ -190,7 +190,7 @@ class CompositeNodeDataWithSchema extends AbstractNodeDataWithSchema {
      * node is found then it is returned, else null.
      */
     AugmentationSchema findCorrespondingAugment(final DataSchemaNode parent, final DataSchemaNode child) {
-        if (parent instanceof AugmentationTarget && !((parent instanceof ChoiceCaseNode) || (parent instanceof ChoiceNode))) {
+        if (parent instanceof AugmentationTarget && !((parent instanceof ChoiceCaseNode) || (parent instanceof ChoiceSchemaNode))) {
             for (AugmentationSchema augmentation : ((AugmentationTarget) parent).getAvailableAugmentations()) {
                 DataSchemaNode childInAugmentation = augmentation.getDataChildByName(child.getQName());
                 if (childInAugmentation != null) {
index aa52259c588a72d6411f7f26f87f877c2e90809d..003684cbf69d1c0179bbfeabf79816c191963a96 100644 (file)
@@ -7,8 +7,20 @@
  */
 package org.opendaylight.yangtools.yang.data.codec.gson;
 
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
 import org.opendaylight.yangtools.concepts.Codec;
 
 interface JSONCodec<T> extends Codec<String, T> {
+    // FIXME: Unused, remove once we are sure we do not need this anymore.
     boolean needQuotes();
+
+
+    /**
+     * Serialize specified value with specified JsonWriter.
+     *
+     * @param writer JsonWriter
+     * @param value
+     */
+    void serializeToWriter(JsonWriter writer, T value) throws IOException;
 }
index 8ee9517ec2db90f976aa64e5b26a883abe3a7c4e..c5840cff986b359c5f4271a29c8a5fa6829e0eb6 100644 (file)
@@ -12,13 +12,18 @@ import com.google.common.base.Preconditions;
 import com.google.common.cache.CacheBuilder;
 import com.google.common.cache.CacheLoader;
 import com.google.common.cache.LoadingCache;
-
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
 import org.opendaylight.yangtools.yang.model.util.IdentityrefType;
 import org.opendaylight.yangtools.yang.model.util.InstanceIdentifierType;
+import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -29,7 +34,6 @@ import org.slf4j.LoggerFactory;
 @Beta
 public final class JSONCodecFactory {
     private static final Logger LOG = LoggerFactory.getLogger(JSONCodecFactory.class);
-    private static final JSONCodec<Object> LEAFREF_DEFAULT_CODEC = new JSONLeafrefCodec();
     private static final JSONCodec<Object> NULL_CODEC = new JSONCodec<Object>() {
         @Override
         public Object deserialize(final String input) {
@@ -45,40 +49,27 @@ public final class JSONCodecFactory {
         public boolean needQuotes() {
             return false;
         }
-    };
 
-    private static TypeDefinition<?> resolveBaseTypeFrom(final TypeDefinition<?> type) {
-        TypeDefinition<?> superType = type;
-        while (superType.getBaseType() != null) {
-            superType = superType.getBaseType();
+        @Override
+        public void serializeToWriter(JsonWriter writer, Object value) throws IOException {
+            // NOOP since codec is unkwown.
+            LOG.warn("Call of the serializeToWriter method on JSONCodecFactory.NULL_CODEC object. No operation performed.");
         }
-        return superType;
-    }
+    };
 
-    private final LoadingCache<TypeDefinition<?>, JSONCodec<Object>> codecs =
-            CacheBuilder.newBuilder().softValues().build(new CacheLoader<TypeDefinition<?>, JSONCodec<Object>>() {
-        @SuppressWarnings("unchecked")
+    private final LoadingCache<DataSchemaNode, JSONCodec<Object>> codecs =
+            CacheBuilder.newBuilder().softValues().build(new CacheLoader<DataSchemaNode, JSONCodec<Object>>() {
         @Override
-        public JSONCodec<Object> load(final TypeDefinition<?> key) throws Exception {
-            final TypeDefinition<?> type = resolveBaseTypeFrom(key);
-
-            if (type instanceof InstanceIdentifierType) {
-                return (JSONCodec<Object>) iidCodec;
-            }
-            if (type instanceof IdentityrefType) {
-                return (JSONCodec<Object>) idrefCodec;
+        public JSONCodec<Object> load(final DataSchemaNode key) throws Exception {
+            final TypeDefinition<?> type;
+            if (key instanceof LeafSchemaNode) {
+                type = ((LeafSchemaNode) key).getType();
+            } else if (key instanceof LeafListSchemaNode) {
+                type = ((LeafListSchemaNode) key).getType();
+            } else {
+                throw new IllegalArgumentException("Not supported node type " + key.getClass().getName());
             }
-            if (type instanceof LeafrefTypeDefinition) {
-                return LEAFREF_DEFAULT_CODEC;
-            }
-
-            final TypeDefinitionAwareCodec<Object, ? extends TypeDefinition<?>> codec = TypeDefinitionAwareCodec.from(type);
-            if (codec == null) {
-                LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName().getLocalName());
-                return NULL_CODEC;
-            }
-
-            return AbstractJSONCodec.create(codec);
+            return createCodec(key,type);
         }
     });
 
@@ -102,11 +93,55 @@ public final class JSONCodecFactory {
         return new JSONCodecFactory(context);
     }
 
+    private static TypeDefinition<?> resolveBaseTypeFrom(final TypeDefinition<?> type) {
+        TypeDefinition<?> superType = type;
+        while (superType.getBaseType() != null) {
+            superType = superType.getBaseType();
+        }
+        return superType;
+    }
+
+    private JSONCodec<Object> createCodec(DataSchemaNode key, TypeDefinition<?> type) {
+        TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
+        if (baseType instanceof LeafrefTypeDefinition) {
+            return createReferencedTypeCodec(key, (LeafrefTypeDefinition) baseType);
+        }
+        return createFromSimpleType(type);
+    }
+
+    private JSONCodec<Object> createReferencedTypeCodec(DataSchemaNode schema,
+            LeafrefTypeDefinition type) {
+        // FIXME: Verify if this does indeed support leafref of leafref
+        TypeDefinition<?> referencedType =
+                SchemaContextUtil.getBaseTypeForLeafRef(type, getSchemaContext(), schema);
+        return createFromSimpleType(referencedType);
+    }
+
+    @SuppressWarnings("unchecked")
+    private JSONCodec<Object> createFromSimpleType(TypeDefinition<?> type) {
+        final TypeDefinition<?> baseType = resolveBaseTypeFrom(type);
+        if (baseType instanceof InstanceIdentifierType) {
+            return (JSONCodec<Object>) iidCodec;
+        }
+        if (baseType instanceof IdentityrefType) {
+            return (JSONCodec<Object>) idrefCodec;
+        }
+
+        final TypeDefinitionAwareCodec<Object, ?> codec = TypeDefinitionAwareCodec.from(type);
+        if (codec == null) {
+            LOG.debug("Codec for type \"{}\" is not implemented yet.", type.getQName()
+                    .getLocalName());
+            return NULL_CODEC;
+        }
+        return (JSONCodec<Object>) AbstractJSONCodec.create(codec);
+    }
+
     SchemaContext getSchemaContext() {
         return schemaContext;
     }
 
-    JSONCodec<Object> codecFor(final TypeDefinition<?> typeDefinition) {
-        return codecs.getUnchecked(typeDefinition);
+    JSONCodec<Object> codecFor(DataSchemaNode schema) {
+        return codecs.getUnchecked(schema);
     }
+
 }
diff --git a/yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONLeafrefCodec.java b/yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONLeafrefCodec.java
deleted file mode 100644 (file)
index 5613433..0000000
+++ /dev/null
@@ -1,27 +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.yangtools.yang.data.codec.gson;
-
-import org.opendaylight.yangtools.yang.data.api.codec.LeafrefCodec;
-
-final class JSONLeafrefCodec implements JSONCodec<Object>, LeafrefCodec<String> {
-    @Override
-    public Object deserialize(final String input) {
-        return input;
-    }
-
-    @Override
-    public String serialize(final Object input) {
-        return String.valueOf(input);
-    }
-
-    @Override
-    public boolean needQuotes() {
-        return true;
-    }
-}
\ No newline at end of file
index 59ef1f1e501ffc53011230f5f2f8ba61271f530c..6b412d583d3c7675b81bc4ae89563b5d8809828d 100644 (file)
@@ -7,9 +7,7 @@
  */
 package org.opendaylight.yangtools.yang.data.codec.gson;
 
-import com.google.common.base.CharMatcher;
 import com.google.common.base.Preconditions;
-import com.google.common.base.Strings;
 import com.google.gson.stream.JsonWriter;
 import java.io.IOException;
 import java.io.Writer;
@@ -31,7 +29,6 @@ import org.opendaylight.yangtools.yang.model.api.SchemaPath;
  *
  * Values of leaf and leaf-list are NOT translated according to codecs.
  *
- * FIXME: rewrite this in terms of {@link JsonWriter}.
  */
 public class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter {
     /**
@@ -40,58 +37,53 @@ public class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWrite
      */
     private static final boolean DEFAULT_EMIT_EMPTY_CONTAINERS = true;
 
-    /**
-     * Matcher used to check if a string needs to be escaped.
-     */
-    private static final CharMatcher JSON_ILLEGAL_STRING_CHARACTERS = CharMatcher.anyOf("\\\"\n\r");
-
     private final SchemaTracker tracker;
     private final JSONCodecFactory codecs;
-    private final Writer writer;
-    private final String indent;
+    private final JsonWriter writer;
     private JSONStreamWriterContext context;
 
-    private JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final SchemaPath path,
-            final Writer writer, final URI initialNs, final int indentSize) {
-        this.writer = Preconditions.checkNotNull(writer);
-
-        Preconditions.checkArgument(indentSize >= 0, "Indent size must be non-negative");
-        if (indentSize != 0) {
-            indent = Strings.repeat(" ", indentSize);
-        } else {
-            indent = null;
-        }
+    private JSONNormalizedNodeStreamWriter(final JSONCodecFactory codecFactory, final SchemaPath path, JsonWriter JsonWriter, JSONStreamWriterRootContext rootContext) {
+        this.writer = Preconditions.checkNotNull(JsonWriter);
         this.codecs = Preconditions.checkNotNull(codecFactory);
         this.tracker = SchemaTracker.create(codecFactory.getSchemaContext(), path);
-        this.context = new JSONStreamWriterRootContext(initialNs);
+        this.context = Preconditions.checkNotNull(rootContext);
     }
 
     /**
      * Create a new stream writer, which writes to the specified {@link Writer}.
      *
+     * This instance of writer can be used only to emit one top level element,
+     * therwise it will produce incorrect JSON.
+     *
      * @param schemaContext Schema context
      * @param writer Output writer
      * @return A stream writer instance
      */
     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer) {
-        return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), SchemaPath.ROOT, writer, null, 0);
+        return create(schemaContext, SchemaPath.ROOT, null, writer);
     }
 
     /**
      * Create a new stream writer, which writes to the specified {@link Writer}.
      *
+     * This instance of writer can be used only to emit one top level element,
+     * therwise it will produce incorrect JSON.
+     *
      * @param schemaContext Schema context
      * @param path Root schemapath
      * @param writer Output writer
      * @return A stream writer instance
      */
     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final SchemaPath path, final Writer writer) {
-        return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), path, writer, null, 0);
+        return create(schemaContext, path, null, writer);
     }
 
     /**
      * Create a new stream writer, which writes to the specified {@link Writer}.
      *
+     * This instance of writer can be used only to emit one top level element,
+     * therwise it will produce incorrect JSON.
+     *
      * @param schemaContext Schema context
      * @param path Root schemapath
      * @param writer Output writer
@@ -100,42 +92,105 @@ public class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWrite
      */
     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final SchemaPath path,
             final URI initialNs, final Writer writer) {
-        return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), path, writer, initialNs, 0);
+        return createExclusiveWriter(JSONCodecFactory.create(schemaContext), path, initialNs, JsonWriterFactory.createJsonWriter(writer));
     }
 
     /**
      * Create a new stream writer, which writes to the specified output stream.
      *
+     * This instance of writer can be used only to emit one top level element,
+     * therwise it will produce incorrect JSON.
+     *
      * @param schemaContext Schema context
      * @param writer Output writer
      * @param indentSize indentation size
      * @return A stream writer instance
      */
     public static NormalizedNodeStreamWriter create(final SchemaContext schemaContext, final Writer writer, final int indentSize) {
-        return new JSONNormalizedNodeStreamWriter(JSONCodecFactory.create(schemaContext), SchemaPath.ROOT, writer, null, indentSize);
+        return createExclusiveWriter(JSONCodecFactory.create(schemaContext), SchemaPath.ROOT, null,JsonWriterFactory.createJsonWriter(writer, indentSize));
     }
 
     /**
      * Create a new stream writer, which writes to the specified output stream. The codec factory
      * can be reused between multiple writers.
      *
+     * This instance of writer can be used only to emit one top level element,
+     * therwise it will produce incorrect JSON.
+     *
      * @param codecFactory JSON codec factory
      * @param writer Output writer
      * @param indentSize indentation size
      * @return A stream writer instance
      */
     public static NormalizedNodeStreamWriter create(final JSONCodecFactory codecFactory, final Writer writer, final int indentSize) {
-        return new JSONNormalizedNodeStreamWriter(codecFactory, SchemaPath.ROOT, writer, null, indentSize);
+        return createExclusiveWriter(codecFactory, SchemaPath.ROOT, null, JsonWriterFactory.createJsonWriter(writer,indentSize));
+    }
+
+    /**
+     * Create a new stream writer, which writes to the specified output stream.
+     *
+     * This instance of writer can be used only to emit one top level element,
+     * therwise it will produce incorrect JSON.
+     *
+     * @param schemaContext Schema context
+     * @param path Schema Path
+     * @param initialNs Initial namespace
+     * @param jsonWriter JsonWriter
+     * @return A stream writer instance
+     */
+    public static NormalizedNodeStreamWriter create(SchemaContext schemaContext, SchemaPath path, URI initialNs,
+            JsonWriter jsonWriter) {
+        return createExclusiveWriter(JSONCodecFactory.create(schemaContext), path, initialNs, jsonWriter);
+    }
+
+    /**
+     * Create a new stream writer, which writes to the specified output stream.
+     *
+     * The codec factory can be reused between multiple writers.
+     *
+     * Returned writer is exclusive user of JsonWriter, which means it will start
+     * top-level JSON element and ends it.
+     *
+     * This instance of writer can be used only to emit one top level element,
+     * therwise it will produce incorrect JSON.
+     *
+     * @param codecFactory JSON codec factory
+     * @param path Schema Path
+     * @param initialNs Initial namespace
+     * @param jsonWriter JsonWriter
+     * @return A stream writer instance
+     */
+    public static NormalizedNodeStreamWriter createExclusiveWriter(JSONCodecFactory codecFactory, SchemaPath path, URI initialNs, JsonWriter jsonWriter) {
+        return new JSONNormalizedNodeStreamWriter(codecFactory, path, jsonWriter, new JSONStreamWriterExclusiveRootContext(initialNs));
+    }
+
+    /**
+     * Create a new stream writer, which writes to the specified output stream.
+     *
+     * The codec factory can be reused between multiple writers.
+     *
+     * Returned writer can be used emit multiple top level element,
+     * but does not start / close parent JSON object, which must be done
+     * by user providing {@code jsonWriter} instance in order for
+     * JSON to be valid.
+     *
+     * @param codecFactory JSON codec factory
+     * @param path Schema Path
+     * @param initialNs Initial namespace
+     * @param jsonWriter JsonWriter
+     * @return A stream writer instance
+     */
+    public static NormalizedNodeStreamWriter createNestedWriter(JSONCodecFactory codecFactory, SchemaPath path, URI initialNs, JsonWriter jsonWriter) {
+        return new JSONNormalizedNodeStreamWriter(codecFactory, path, jsonWriter, new JSONStreamWriterSharedRootContext(initialNs));
     }
 
     @Override
     public void leafNode(final NodeIdentifier name, final Object value) throws IOException {
         final LeafSchemaNode schema = tracker.leafNode(name);
-        final JSONCodec<Object> codec = codecs.codecFor(schema.getType());
-
-        context.emittingChild(codecs.getSchemaContext(), writer, indent);
+        final JSONCodec<Object> codec = codecs.codecFor(schema);
+        context.emittingChild(codecs.getSchemaContext(), writer);
         context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
-        writeValue(codec.serialize(value), codec.needQuotes());
+        writeValue(value, codec);
     }
 
     @Override
@@ -147,10 +202,9 @@ public class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWrite
     @Override
     public void leafSetEntryNode(final Object value) throws IOException {
         final LeafListSchemaNode schema = tracker.leafSetEntryNode();
-        final JSONCodec<Object> codec = codecs.codecFor(schema.getType());
-
-        context.emittingChild(codecs.getSchemaContext(), writer, indent);
-        writeValue(codec.serialize(value), codec.needQuotes());
+        final JSONCodec<Object> codec = codecs.codecFor(schema);
+        context.emittingChild(codecs.getSchemaContext(), writer);
+        writeValue(value, codec);
     }
 
     /*
@@ -216,44 +270,27 @@ public class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWrite
         final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
         // FIXME: should have a codec based on this :)
 
-        context.emittingChild(codecs.getSchemaContext(), writer, indent);
+        context.emittingChild(codecs.getSchemaContext(), writer);
         context.writeChildJsonIdentifier(codecs.getSchemaContext(), writer, name.getNodeType());
-        writeValue(String.valueOf(value), true);
+        // FIXME this kind of serialization is incorrect since the value for AnyXml is now a DOMSource
+        writer.value(String.valueOf(value));
     }
 
     @Override
     public void endNode() throws IOException {
         tracker.endNode();
-        context = context.endNode(codecs.getSchemaContext(), writer, indent);
-    }
+        context = context.endNode(codecs.getSchemaContext(), writer);
 
-    private void writeValue(final String str, final boolean needQuotes) throws IOException {
-        if (needQuotes) {
-            writer.append('"');
-
-            final int needEscape = JSON_ILLEGAL_STRING_CHARACTERS.countIn(str);
-            if (needEscape != 0) {
-                final char[] escaped = new char[str.length() + needEscape];
-                int offset = 0;
-
-                for (int i = 0; i < str.length(); i++) {
-                    final char c = str.charAt(i);
-                    if (JSON_ILLEGAL_STRING_CHARACTERS.matches(c)) {
-                        escaped[offset++] = '\\';
-                    }
-                    escaped[offset++] = c;
-                }
-                writer.write(escaped);
-            } else {
-                writer.append(str);
-            }
-
-            writer.append('"');
-        } else {
-            writer.append(str);
+        if(context instanceof JSONStreamWriterRootContext) {
+            context.emitEnd(writer);
         }
     }
 
+    private void writeValue(Object value, JSONCodec<Object> codec)
+            throws IOException {
+        codec.serializeToWriter(writer,value);
+    }
+
     @Override
     public void flush() throws IOException {
         writer.flush();
@@ -265,4 +302,6 @@ public class JSONNormalizedNodeStreamWriter implements NormalizedNodeStreamWrite
         writer.close();
     }
 
+
+
 }
index a3ad80dfb3f28473b523f3b12c1a1cc335063715..a29972aa939e84a88f435225a559ed59ac1eb9f6 100644 (file)
@@ -8,8 +8,9 @@
 package org.opendaylight.yangtools.yang.data.codec.gson;
 
 import com.google.common.base.Preconditions;
+import com.google.gson.stream.JsonWriter;
 import java.io.IOException;
-import java.io.Writer;
+import java.io.StringWriter;
 import java.net.URI;
 import javax.annotation.Nonnull;
 import org.opendaylight.yangtools.yang.common.QName;
@@ -26,7 +27,6 @@ abstract class JSONStreamWriterContext {
     private final boolean mandatory;
     private final int depth;
     private boolean emittedMyself = false;
-    private boolean haveChild = false;
 
     /**
      * Construct a new context.
@@ -55,21 +55,21 @@ abstract class JSONStreamWriterContext {
      * @param qname Namespace/name tuple
      * @throws IOException when the writer reports it
      */
-    final void writeChildJsonIdentifier(final SchemaContext schema, final Writer writer, final QName qname) throws IOException {
-        writer.append('"');
+    final void writeChildJsonIdentifier(final SchemaContext schema, final JsonWriter writer, final QName qname) throws IOException {
 
+        StringWriter strWriter = new StringWriter();
         // Prepend module name if namespaces do not match
         final URI ns = qname.getNamespace();
         if (!ns.equals(getNamespace())) {
             final Module module = schema.findModuleByNamespaceAndRevision(ns, null);
             Preconditions.checkArgument(module != null, "Could not find module for namespace {}", ns);
 
-            writer.append(module.getName());
-            writer.append(':');
+            strWriter.append(module.getName());
+            strWriter.append(':');
         }
+        strWriter.append(qname.getLocalName());
 
-        writer.append(qname.getLocalName());
-        writer.append("\":");
+        writer.name(strWriter.toString());
     }
 
     /**
@@ -81,7 +81,7 @@ abstract class JSONStreamWriterContext {
      * @param qname Namespace/name tuple
      * @throws IOException when the writer reports it
      */
-    protected final void writeMyJsonIdentifier(final SchemaContext schema, final Writer writer, final QName qname) throws IOException {
+    protected final void writeMyJsonIdentifier(final SchemaContext schema, final JsonWriter writer, final QName qname) throws IOException {
         parent.writeChildJsonIdentifier(schema, writer, qname);
     }
 
@@ -99,7 +99,7 @@ abstract class JSONStreamWriterContext {
      * @param writer Output writer
      * @throws IOException
      */
-    protected abstract void emitStart(final SchemaContext schema, final Writer writer) throws IOException;
+    protected abstract void emitStart(final SchemaContext schema, final JsonWriter writer) throws IOException;
 
     /**
      * Emit the end of an element.
@@ -108,12 +108,12 @@ abstract class JSONStreamWriterContext {
      * @param writer Output writer
      * @throws IOException
      */
-    protected abstract void emitEnd(final Writer writer) throws IOException;
+    protected abstract void emitEnd(final JsonWriter writer) throws IOException;
 
-    private final void emitMyself(final SchemaContext schema, final Writer writer, final String indent) throws IOException {
+    private final void emitMyself(final SchemaContext schema, final JsonWriter writer) throws IOException {
         if (!emittedMyself) {
             if (parent != null) {
-                parent.emittingChild(schema, writer, indent);
+                parent.emittingChild(schema, writer);
             }
 
             emitStart(schema, writer);
@@ -128,23 +128,10 @@ abstract class JSONStreamWriterContext {
      *
      * @param schema Schema context
      * @param writer Output writer
-     * @param indent Indentation string
      * @throws IOException when writer reports it
      */
-    final void emittingChild(final SchemaContext schema, final Writer writer, final String indent) throws IOException {
-        emitMyself(schema, writer, indent);
-        if (haveChild) {
-            writer.append(',');
-        }
-
-        if (indent != null) {
-            writer.append('\n');
-
-            for (int i = 0; i < depth; i++) {
-                writer.append(indent);
-            }
-        }
-        haveChild = true;
+    final void emittingChild(final SchemaContext schema, final JsonWriter writer) throws IOException {
+        emitMyself(schema, writer);
     }
 
     /**
@@ -153,14 +140,13 @@ abstract class JSONStreamWriterContext {
      *
      * @param schema Schema context
      * @param writer Output writer
-     * @param indent Indentation string
      * @return Parent node context
      * @throws IOException when writer reports it
      * @throws IllegalArgumentException if this node cannot be ended (e.g. root)
      */
-    final JSONStreamWriterContext endNode(final SchemaContext schema, final Writer writer, final String indent) throws IOException {
+    final JSONStreamWriterContext endNode(final SchemaContext schema, final JsonWriter writer) throws IOException {
         if (!emittedMyself && mandatory) {
-            emitMyself(schema, writer, indent);
+            emitMyself(schema, writer);
         }
 
         if (emittedMyself) {
diff --git a/yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONStreamWriterExclusiveRootContext.java b/yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONStreamWriterExclusiveRootContext.java
new file mode 100644 (file)
index 0000000..5359df8
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.codec.gson;
+
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.net.URI;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+final class JSONStreamWriterExclusiveRootContext extends JSONStreamWriterRootContext {
+    JSONStreamWriterExclusiveRootContext(final URI namespace) {
+        super(namespace);
+    }
+
+    @Override
+    protected void emitStart(final SchemaContext schema, final JsonWriter writer) throws IOException {
+        writer.beginObject();
+    }
+
+    @Override
+    protected void emitEnd(final JsonWriter writer) throws IOException {
+        writer.endObject();
+    }
+}
index 7f22c194664637e2916e521849d8d59d9380cdcd..e43aead9f449496235284f17dbbba6aa474b644b 100644 (file)
@@ -8,8 +8,9 @@
 package org.opendaylight.yangtools.yang.data.codec.gson;
 
 import com.google.common.base.Preconditions;
+import com.google.gson.stream.JsonWriter;
+
 
-import java.io.Writer;
 
 /**
  * A virtual recursion level in {@link JSONNormalizedNodeStreamWriter}, used for nodes
@@ -21,7 +22,7 @@ final class JSONStreamWriterInvisibleContext extends JSONStreamWriterURIContext
     }
 
     @Override
-    protected void emitEnd(final Writer writer) {
+    protected void emitEnd(final JsonWriter writer) {
         // No-op
     }
 }
\ No newline at end of file
index 9c0be476b1bb332e4d91a2a36f85a6e47cced61a..e1505c7b10898d097b75783314b6f8f136c8ec92 100644 (file)
@@ -8,8 +8,8 @@
 package org.opendaylight.yangtools.yang.data.codec.gson;
 
 import com.google.common.base.Preconditions;
+import com.google.gson.stream.JsonWriter;
 import java.io.IOException;
-import java.io.Writer;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
@@ -23,13 +23,13 @@ final class JSONStreamWriterListContext extends JSONStreamWriterQNameContext {
     }
 
     @Override
-    protected void emitStart(final SchemaContext schema, final Writer writer) throws IOException {
+    protected void emitStart(final SchemaContext schema, final JsonWriter writer) throws IOException {
         writeMyJsonIdentifier(schema, writer, getQName());
-        writer.append('[');
+        writer.beginArray();
     }
 
     @Override
-    protected void emitEnd(final Writer writer) throws IOException {
-        writer.append(']');
+    protected void emitEnd(final JsonWriter writer) throws IOException {
+        writer.endArray();
     }
 }
index 91c6ca70ae2c5a613984610bbdba44ae5aeca598..fe08410cafa5620cc7b3e2b1a1d8dfa72f0455df 100644 (file)
@@ -7,11 +7,12 @@
  */
 package org.opendaylight.yangtools.yang.data.codec.gson;
 
+import com.google.gson.stream.JsonWriter;
 import java.io.IOException;
-import java.io.Writer;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
+
 /**
  * A recursion level of {@link JSONNormalizedNodeStreamWriter}, which represents
  * a JSON object which has to be prefixed with its identifier -- such as a
@@ -23,7 +24,7 @@ final class JSONStreamWriterNamedObjectContext extends JSONStreamWriterObjectCon
     }
 
     @Override
-    protected void emitStart(final SchemaContext schema, final Writer writer) throws IOException {
+    protected void emitStart(final SchemaContext schema, final JsonWriter writer) throws IOException {
         writeMyJsonIdentifier(schema, writer, getQName());
         super.emitStart(schema, writer);
     }
index d12f0449dd89e58ee4e6f3fd66be552dfb7ab919..fb4e48ed6091073550c02154113496c318e8016c 100644 (file)
@@ -8,10 +8,8 @@
 package org.opendaylight.yangtools.yang.data.codec.gson;
 
 import com.google.common.base.Preconditions;
-
+import com.google.gson.stream.JsonWriter;
 import java.io.IOException;
-import java.io.Writer;
-
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
@@ -26,12 +24,12 @@ class JSONStreamWriterObjectContext extends JSONStreamWriterQNameContext {
     }
 
     @Override
-    protected void emitStart(final SchemaContext schema, final Writer writer) throws IOException {
-        writer.append('{');
+    protected void emitStart(final SchemaContext schema, final JsonWriter writer) throws IOException {
+        writer.beginObject();
     }
 
     @Override
-    protected void emitEnd(final Writer writer) throws IOException {
-        writer.append('}');
+    protected void emitEnd(final JsonWriter writer) throws IOException {
+        writer.endObject();
     }
 }
\ No newline at end of file
index 36c3ff38c349d7ad05f4474aa024c02d8aff9db6..5c02498c4604ec8d31559e8a4ea1653155dde8f1 100644 (file)
@@ -7,20 +7,17 @@
  */
 package org.opendaylight.yangtools.yang.data.codec.gson;
 
-import java.io.Writer;
 import java.net.URI;
 
+
 /**
  * The root node of a particular {@link JSONNormalizedNodeStreamWriter} instance.
  * It holds the base namespace and can never be removed from the stack.
  */
-final class JSONStreamWriterRootContext extends JSONStreamWriterURIContext {
+abstract class JSONStreamWriterRootContext extends JSONStreamWriterURIContext {
+
     JSONStreamWriterRootContext(final URI namespace) {
         super(null, namespace);
     }
 
-    @Override
-    protected void emitEnd(final Writer writer) {
-        throw new IllegalArgumentException("Top-level node reached");
-    }
 }
diff --git a/yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONStreamWriterSharedRootContext.java b/yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JSONStreamWriterSharedRootContext.java
new file mode 100644 (file)
index 0000000..8704cb6
--- /dev/null
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.codec.gson;
+
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
+import java.net.URI;
+
+final class JSONStreamWriterSharedRootContext extends JSONStreamWriterRootContext {
+    JSONStreamWriterSharedRootContext(final URI namespace) {
+        super(namespace);
+    }
+
+    @Override
+    protected void emitEnd(final JsonWriter writer) throws IOException {
+        // NOOP
+    }
+}
index 06c32bf26d3ab37bef9738bc2749f30252103b16..f0d286a42781509bf61cce87fcfa0e1b4c0d4e82 100644 (file)
@@ -7,12 +7,12 @@
  */
 package org.opendaylight.yangtools.yang.data.codec.gson;
 
+import com.google.gson.stream.JsonWriter;
 import java.io.IOException;
-import java.io.Writer;
 import java.net.URI;
-
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
+
 /**
  * Abstract class tracking a virtual level of {@link JSONNormalizedNodeStreamWriter}
  * recursion. It only tracks the namespace associated with this node.
@@ -31,7 +31,7 @@ abstract class JSONStreamWriterURIContext extends JSONStreamWriterContext {
     }
 
     @Override
-    protected final void emitStart(final SchemaContext schema, final Writer writer) throws IOException {
+    protected void emitStart(final SchemaContext schema, final JsonWriter writer) throws IOException {
         // No-op
     }
 }
\ No newline at end of file
index fcbe473cca8dc6b414814a2e05ed3f92d9e3673e..7e099b4e2d8aa96f35f732e728ee2e9412681ce7 100644 (file)
@@ -8,9 +8,9 @@
 package org.opendaylight.yangtools.yang.data.codec.gson;
 
 import com.google.common.base.Preconditions;
-
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
 import java.net.URI;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.util.AbstractModuleStringIdentityrefCodec;
 import org.opendaylight.yangtools.yang.model.api.Module;
@@ -38,4 +38,15 @@ final class JSONStringIdentityrefCodec extends AbstractModuleStringIdentityrefCo
     public boolean needQuotes() {
         return true;
     }
+
+    /**
+     * Serialize QName with specified JsonWriter.
+     *
+     * @param writer JsonWriter
+     * @param value QName
+     */
+    @Override
+    public void serializeToWriter(JsonWriter writer, QName value) throws IOException {
+        writer.value(serialize(value));
+    }
 }
index a1580dd5bb2c3f5681569c1c3541e68d38f51cbf..528162a359e2151e2b971ec573cbe85abb2f63b0 100644 (file)
@@ -8,19 +8,22 @@
 package org.opendaylight.yangtools.yang.data.codec.gson;
 
 import com.google.common.base.Preconditions;
-
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
 import java.net.URI;
-
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.util.AbstractModuleStringInstanceIdentifierCodec;
+import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
 final class JSONStringInstanceIdentifierCodec extends AbstractModuleStringInstanceIdentifierCodec implements JSONCodec<YangInstanceIdentifier> {
     private final SchemaContext context;
+    private final DataSchemaContextTree dataContextTree;
 
     JSONStringInstanceIdentifierCodec(final SchemaContext context) {
         this.context = Preconditions.checkNotNull(context);
+        this.dataContextTree = DataSchemaContextTree.from(context);
     }
 
     @Override
@@ -34,8 +37,24 @@ final class JSONStringInstanceIdentifierCodec extends AbstractModuleStringInstan
         return module == null ? null : module.getName();
     }
 
+    @Override
+    protected DataSchemaContextTree getDataContextTree() {
+        return dataContextTree;
+    }
+
     @Override
     public boolean needQuotes() {
         return true;
     }
+
+    /**
+     * Serialize YangInstanceIdentifier with specified JsonWriter.
+     *
+     * @param writer JsonWriter
+     * @param value YangInstanceIdentifier
+     */
+    @Override
+    public void serializeToWriter(JsonWriter writer, YangInstanceIdentifier value) throws IOException {
+        writer.value(serialize(value));
+    }
 }
index 1721f428d5c276edd109dd1cec93b29bb6d2ae15..f0b4de3b03a90546f17c957ffcf1bc01625b9938 100644 (file)
@@ -8,14 +8,12 @@
 package org.opendaylight.yangtools.yang.data.codec.gson;
 
 import com.google.common.annotations.Beta;
-import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import com.google.gson.JsonIOException;
 import com.google.gson.JsonParseException;
 import com.google.gson.JsonSyntaxException;
 import com.google.gson.stream.JsonReader;
 import com.google.gson.stream.MalformedJsonException;
-
 import java.io.Closeable;
 import java.io.EOFException;
 import java.io.Flushable;
@@ -23,25 +21,22 @@ import java.io.IOException;
 import java.net.URI;
 import java.util.ArrayDeque;
 import java.util.ArrayList;
-import java.util.Arrays;
+import java.util.Collections;
 import java.util.Deque;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
+import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
 
 /**
  * This class parses JSON elements from a GSON JsonReader. It disallows multiple elements of the same name unlike the
@@ -63,6 +58,9 @@ public final class JsonParserStream implements Closeable, Flushable {
     }
 
     public static JsonParserStream create(final NormalizedNodeStreamWriter writer, final SchemaContext schemaContext, final SchemaNode parentNode ) {
+        if(parentNode instanceof RpcDefinition) {
+            return new JsonParserStream(writer, schemaContext, new RpcAsContainer((RpcDefinition) parentNode));
+        }
         Preconditions.checkArgument(parentNode instanceof DataSchemaNode, "Instance of DataSchemaNode class awaited.");
         return new JsonParserStream(writer, schemaContext, (DataSchemaNode) parentNode);
     }
@@ -74,30 +72,30 @@ public final class JsonParserStream implements Closeable, Flushable {
     public JsonParserStream parse(final JsonReader reader) throws JsonIOException, JsonSyntaxException {
         // code copied from gson's JsonParser and Stream classes
 
-        boolean lenient = reader.isLenient();
+        final boolean lenient = reader.isLenient();
         reader.setLenient(true);
         boolean isEmpty = true;
         try {
             reader.peek();
             isEmpty = false;
-            CompositeNodeDataWithSchema compositeNodeDataWithSchema = new CompositeNodeDataWithSchema(parentNode);
+            final CompositeNodeDataWithSchema compositeNodeDataWithSchema = new CompositeNodeDataWithSchema(parentNode);
             read(reader, compositeNodeDataWithSchema);
             compositeNodeDataWithSchema.write(writer);
 
             return this;
             // return read(reader);
-        } catch (EOFException e) {
+        } catch (final EOFException e) {
             if (isEmpty) {
                 return this;
                 // return JsonNull.INSTANCE;
             }
             // The stream ended prematurely so it is likely a syntax error.
             throw new JsonSyntaxException(e);
-        } catch (MalformedJsonException e) {
+        } catch (final MalformedJsonException e) {
             throw new JsonSyntaxException(e);
-        } catch (IOException e) {
+        } catch (final IOException e) {
             throw new JsonIOException(e);
-        } catch (NumberFormatException e) {
+        } catch (final NumberFormatException e) {
             throw new JsonSyntaxException(e);
         } catch (StackOverflowError | OutOfMemoryError e) {
             throw new JsonParseException("Failed parsing JSON source: " + reader + " to Json", e);
@@ -113,7 +111,7 @@ public final class JsonParserStream implements Closeable, Flushable {
         ((SimpleNodeDataWithSchema) parent).setValue(translatedValue);
     }
 
-    public void read(final JsonReader in, final AbstractNodeDataWithSchema parent) throws IOException {
+    public void read(final JsonReader in, AbstractNodeDataWithSchema parent) throws IOException {
         switch (in.peek()) {
         case STRING:
         case NUMBER:
@@ -129,24 +127,27 @@ public final class JsonParserStream implements Closeable, Flushable {
         case BEGIN_ARRAY:
             in.beginArray();
             while (in.hasNext()) {
-                AbstractNodeDataWithSchema newChild = null;
-                if (parent instanceof ListNodeDataWithSchema) {
-                    newChild = new ListEntryNodeDataWithSchema(parent.getSchema());
-                    ((CompositeNodeDataWithSchema) parent).addChild(newChild);
-                } else if (parent instanceof LeafListNodeDataWithSchema) {
-                    newChild = new LeafListEntryNodeDataWithSchema(parent.getSchema());
-                    ((CompositeNodeDataWithSchema) parent).addChild(newChild);
-                }
+                final AbstractNodeDataWithSchema newChild = newArrayEntry(parent);
                 read(in, newChild);
             }
             in.endArray();
             return;
         case BEGIN_OBJECT:
-            Set<String> namesakes = new HashSet<>();
+            final Set<String> namesakes = new HashSet<>();
             in.beginObject();
+            /*
+             * This allows parsing of incorrectly /as showcased/
+             * in testconf nesting of list items - eg.
+             * lists with one value are sometimes serialized
+             * without wrapping array.
+             *
+             */
+            if(isArray(parent)) {
+                parent = newArrayEntry(parent);
+            }
             while (in.hasNext()) {
                 final String jsonElementName = in.nextName();
-                final NamespaceAndName namespaceAndName = resolveNamespace(jsonElementName);
+                final NamespaceAndName namespaceAndName = resolveNamespace(jsonElementName, parent.getSchema());
                 final String localName = namespaceAndName.getName();
                 addNamespace(namespaceAndName.getUri());
                 if (namesakes.contains(jsonElementName)) {
@@ -160,9 +161,12 @@ public final class JsonParserStream implements Closeable, Flushable {
                             + getCurrentNamespace() + " doesn't exist.");
                 }
 
-                AbstractNodeDataWithSchema newChild;
-                newChild = ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes);
-//                FIXME:anyxml data shouldn't be skipped but should be loaded somehow. will be specified after 17AUG2014
+                final AbstractNodeDataWithSchema newChild = ((CompositeNodeDataWithSchema) parent).addChild(childDataSchemaNodes);
+                /*
+                 * FIXME:anyxml data shouldn't be skipped but should be loaded somehow.
+                 * will be able to load anyxml which conforms to YANG data using these
+                 * parser, for other anyxml will be harder.
+                 */
                 if (newChild instanceof AnyXmlNodeDataWithSchema) {
                     in.skipValue();
                 } else {
@@ -180,53 +184,45 @@ public final class JsonParserStream implements Closeable, Flushable {
         }
     }
 
-    private Object translateValueByType(final String value, final DataSchemaNode node) {
-        final TypeDefinition<? extends Object> typeDefinition = typeDefinition(node);
-        if (typeDefinition == null) {
-            return value;
-        }
-
-        return codecs.codecFor(typeDefinition).deserialize(value);
+    private boolean isArray(final AbstractNodeDataWithSchema parent) {
+        return parent instanceof ListNodeDataWithSchema || parent instanceof ListNodeDataWithSchema;
     }
 
-    private static TypeDefinition<? extends Object> typeDefinition(final DataSchemaNode node) {
-        TypeDefinition<?> baseType = null;
-        if (node instanceof LeafListSchemaNode) {
-            baseType = ((LeafListSchemaNode) node).getType();
-        } else if (node instanceof LeafSchemaNode) {
-            baseType = ((LeafSchemaNode) node).getType();
-        } else if (node instanceof AnyXmlSchemaNode) {
-            return null;
+    private AbstractNodeDataWithSchema newArrayEntry(final AbstractNodeDataWithSchema parent) {
+        AbstractNodeDataWithSchema newChild;
+        if (parent instanceof ListNodeDataWithSchema) {
+            newChild = new ListEntryNodeDataWithSchema(parent.getSchema());
+        } else if (parent instanceof LeafListNodeDataWithSchema) {
+            newChild = new LeafListEntryNodeDataWithSchema(parent.getSchema());
         } else {
-            throw new IllegalArgumentException("Unhandled parameter types: " + Arrays.<Object> asList(node).toString());
+            throw new IllegalStateException("Incorrec nesting caused by parser.");
         }
+        ((CompositeNodeDataWithSchema) parent).addChild(newChild);
+        return newChild;
+    }
 
-        if (baseType != null) {
-            while (baseType.getBaseType() != null) {
-                baseType = baseType.getBaseType();
-            }
+    private Object translateValueByType(final String value, final DataSchemaNode node) {
+        if (node instanceof AnyXmlSchemaNode) {
+            /*
+             *  FIXME: Figure out some YANG extension dispatch, which will
+             *  reuse JSON parsing or XML parsing - anyxml is not well-defined in
+             * JSON.
+             */
+            return value;
         }
-        return baseType;
+        return codecs.codecFor(node).deserialize(value);
     }
 
     private void removeNamespace() {
         namespaces.pop();
     }
 
-    private void addNamespace(final Optional<URI> namespace) {
-        if (!namespace.isPresent()) {
-            if (namespaces.isEmpty()) {
-                throw new IllegalStateException("Namespace has to be specified at top level.");
-            } else {
-                namespaces.push(namespaces.peek());
-            }
-        } else {
-            namespaces.push(namespace.get());
-        }
+    private void addNamespace(final URI namespace) {
+        namespaces.push(namespace);
     }
 
-    private NamespaceAndName resolveNamespace(final String childName) {
-        int lastIndexOfColon = childName.lastIndexOf(':');
+    private NamespaceAndName resolveNamespace(final String childName, final DataSchemaNode dataSchemaNode) {
+        final int lastIndexOfColon = childName.lastIndexOf(':');
         String moduleNamePart = null;
         String nodeNamePart = null;
         URI namespace = null;
@@ -240,8 +236,52 @@ public final class JsonParserStream implements Closeable, Flushable {
             nodeNamePart = childName;
         }
 
-        Optional<URI> namespaceOpt = namespace == null ? Optional.<URI> absent() : Optional.of(namespace);
-        return new NamespaceAndName(nodeNamePart, namespaceOpt);
+        if (namespace == null) {
+            Set<URI> potentialUris = Collections.emptySet();
+            potentialUris = resolveAllPotentialNamespaces(nodeNamePart, dataSchemaNode);
+            if (potentialUris.contains(getCurrentNamespace())) {
+                namespace = getCurrentNamespace();
+            } else if (potentialUris.size() == 1) {
+                namespace = potentialUris.iterator().next();
+            } else if (potentialUris.size() > 1) {
+                throw new IllegalStateException("Choose suitable module name for element "+nodeNamePart+":"+toModuleNames(potentialUris));
+            } else if (potentialUris.isEmpty()) {
+                throw new IllegalStateException("Schema node with name "+nodeNamePart+" wasn't found.");
+            }
+        }
+
+        return new NamespaceAndName(nodeNamePart, namespace);
+    }
+
+    private String toModuleNames(final Set<URI> potentialUris) {
+        final StringBuilder builder = new StringBuilder();
+        for (final URI potentialUri : potentialUris) {
+            builder.append("\n");
+            //FIXME how to get information about revision from JSON input? currently first available is used.
+            builder.append(schema.findModuleByNamespace(potentialUri).iterator().next().getName());
+        }
+        return builder.toString();
+    }
+
+    private Set<URI> resolveAllPotentialNamespaces(final String elementName, final DataSchemaNode dataSchemaNode) {
+        final Set<URI> potentialUris = new HashSet<>();
+        final Set<ChoiceSchemaNode> choices = new HashSet<>();
+        if (dataSchemaNode instanceof DataNodeContainer) {
+            for (final DataSchemaNode childSchemaNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
+                if (childSchemaNode instanceof ChoiceSchemaNode) {
+                    choices.add((ChoiceSchemaNode)childSchemaNode);
+                } else if (childSchemaNode.getQName().getLocalName().equals(elementName)) {
+                    potentialUris.add(childSchemaNode.getQName().getNamespace());
+                }
+            }
+
+            for (final ChoiceSchemaNode choiceNode : choices) {
+                for (final ChoiceCaseNode concreteCase : choiceNode.getCases()) {
+                    potentialUris.addAll(resolveAllPotentialNamespaces(elementName, concreteCase));
+                }
+            }
+        }
+        return potentialUris;
     }
 
     private URI getCurrentNamespace() {
@@ -262,11 +302,11 @@ public final class JsonParserStream implements Closeable, Flushable {
     private Deque<DataSchemaNode> findSchemaNodeByNameAndNamespace(final DataSchemaNode dataSchemaNode,
             final String childName, final URI namespace) {
         final Deque<DataSchemaNode> result = new ArrayDeque<>();
-        List<ChoiceNode> childChoices = new ArrayList<>();
+        final List<ChoiceSchemaNode> childChoices = new ArrayList<>();
         if (dataSchemaNode instanceof DataNodeContainer) {
-            for (DataSchemaNode childNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
-                if (childNode instanceof ChoiceNode) {
-                    childChoices.add((ChoiceNode) childNode);
+            for (final DataSchemaNode childNode : ((DataNodeContainer) dataSchemaNode).getChildNodes()) {
+                if (childNode instanceof ChoiceSchemaNode) {
+                    childChoices.add((ChoiceSchemaNode) childNode);
                 } else {
                     final QName childQName = childNode.getQName();
                     if (childQName.getLocalName().equals(childName) && childQName.getNamespace().equals(namespace)) {
@@ -277,9 +317,9 @@ public final class JsonParserStream implements Closeable, Flushable {
             }
         }
         // try to find data schema node in choice (looking for first match)
-        for (ChoiceNode choiceNode : childChoices) {
-            for (ChoiceCaseNode concreteCase : choiceNode.getCases()) {
-                Deque<DataSchemaNode> resultFromRecursion = findSchemaNodeByNameAndNamespace(concreteCase, childName,
+        for (final ChoiceSchemaNode choiceNode : childChoices) {
+            for (final ChoiceCaseNode concreteCase : choiceNode.getCases()) {
+                final Deque<DataSchemaNode> resultFromRecursion = findSchemaNodeByNameAndNamespace(concreteCase, childName,
                         namespace);
                 if (!resultFromRecursion.isEmpty()) {
                     resultFromRecursion.push(concreteCase);
@@ -292,10 +332,10 @@ public final class JsonParserStream implements Closeable, Flushable {
     }
 
     private static class NamespaceAndName {
-        private final Optional<URI> uri;
+        private final URI uri;
         private final String name;
 
-        public NamespaceAndName(final String name, final Optional<URI> uri) {
+        public NamespaceAndName(final String name, final URI uri) {
             this.name = name;
             this.uri = uri;
         }
@@ -304,7 +344,7 @@ public final class JsonParserStream implements Closeable, Flushable {
             return name;
         }
 
-        public Optional<URI> getUri() {
+        public URI getUri() {
             return uri;
         }
     }
diff --git a/yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JsonWriterFactory.java b/yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/JsonWriterFactory.java
new file mode 100644 (file)
index 0000000..3b3bf8d
--- /dev/null
@@ -0,0 +1,47 @@
+/**
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.codec.gson;
+
+import com.google.common.annotations.Beta;
+import com.google.common.base.Strings;
+import com.google.gson.stream.JsonWriter;
+import java.io.Writer;
+
+/**
+ * Factory Method class for JsonWriter creation
+ */
+@Beta
+public final class JsonWriterFactory {
+
+    private JsonWriterFactory() {
+    }
+    /**
+     * Create a new JsonWriter, which writes to the specified output writer.
+     *
+     * @param writer Output writer
+     * @return A JsonWriter instance
+     */
+    public static JsonWriter createJsonWriter(Writer writer) {
+        return new JsonWriter(writer);
+    }
+
+    /**
+     * Create a new JsonWriter, which writes to the specified output writer.
+     *
+     * @param writer Output writer
+     * @param indentSize size of the indent
+     * @return A JsonWriter instance
+     */
+    public static JsonWriter createJsonWriter(Writer writer, int indentSize) {
+        JsonWriter jsonWriter = new JsonWriter(writer);
+        final String indent = Strings.repeat(" ", indentSize);
+        jsonWriter.setIndent(indent);
+        return jsonWriter;
+    }
+
+}
index d21cd9a77a01000a9e48cb3b941899e68dc7d06f..2c5311417b272bd9a6e24eb9131c16da39a52eba 100644 (file)
@@ -21,8 +21,11 @@ class ListNodeDataWithSchema extends CompositeNodeDataWithSchema {
 
     @Override
     public void write(final NormalizedNodeStreamWriter writer) throws IOException {
-        if (((ListSchemaNode) getSchema()).getKeyDefinition().isEmpty()) {
+        final ListSchemaNode schema = (ListSchemaNode) getSchema();
+        if (schema.getKeyDefinition().isEmpty()) {
             writer.startUnkeyedList(provideNodeIdentifier(), childSizeHint());
+        } else if(schema.isUserOrdered()) {
+            writer.startOrderedMapNode(provideNodeIdentifier(), childSizeHint());
         } else {
             writer.startMapNode(provideNodeIdentifier(), childSizeHint());
         }
similarity index 58%
rename from yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/UnquotedJSONCodec.java
rename to yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/NumberJSONCodec.java
index f29db5d1eeeea56e38ac9a3db5b26b98c8062a0f..d262a440ce86681bc2d9508f601b8ee74b502abc 100644 (file)
@@ -7,6 +7,8 @@
  */
 package org.opendaylight.yangtools.yang.data.codec.gson;
 
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
 import org.opendaylight.yangtools.concepts.Codec;
 
 /**
@@ -14,8 +16,8 @@ import org.opendaylight.yangtools.concepts.Codec;
  *
  * @param <T> Deserialized value type
  */
-final class UnquotedJSONCodec<T> extends AbstractJSONCodec<T> {
-    UnquotedJSONCodec(final Codec<String, T> codec) {
+final class NumberJSONCodec<T extends Number> extends AbstractJSONCodec<T > {
+    NumberJSONCodec(final Codec<String, T> codec) {
         super(codec);
     }
 
@@ -23,4 +25,15 @@ final class UnquotedJSONCodec<T> extends AbstractJSONCodec<T> {
     public boolean needQuotes() {
         return false;
     }
+
+    /**
+     * Serialize specified value with specified JsonWriter.
+     *
+     * @param writer JsonWriter
+     * @param value
+     */
+    @Override
+    public void serializeToWriter(JsonWriter writer, T value) throws IOException {
+        writer.value(value);
+    }
 }
\ No newline at end of file
index e8606f8d9587f4304d752cfe2215e19d5e6ced0b..45782896cf2b3bbe3d9040da4904713519e69365 100644 (file)
@@ -7,6 +7,8 @@
  */
 package org.opendaylight.yangtools.yang.data.codec.gson;
 
+import com.google.gson.stream.JsonWriter;
+import java.io.IOException;
 import org.opendaylight.yangtools.concepts.Codec;
 
 /**
@@ -23,4 +25,15 @@ final class QuotedJSONCodec<T> extends AbstractJSONCodec<T> {
     public boolean needQuotes() {
         return true;
     }
+
+    /**
+     * Serialize specified value with specified JsonWriter.
+     *
+     * @param writer JsonWriter
+     * @param value
+     */
+    @Override
+    public void serializeToWriter(JsonWriter writer, T value) throws IOException {
+        writer.value(serialize(value));
+    }
 }
\ No newline at end of file
diff --git a/yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/RpcAsContainer.java b/yang/yang-data-codec-gson/src/main/java/org/opendaylight/yangtools/yang/data/codec/gson/RpcAsContainer.java
new file mode 100644 (file)
index 0000000..0b64b22
--- /dev/null
@@ -0,0 +1,150 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.codec.gson;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
+import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.Status;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.UsesNode;
+
+final class RpcAsContainer implements ContainerSchemaNode {
+
+    private final RpcDefinition delegate;
+
+    @Override
+    public String getDescription() {
+        return delegate.getDescription();
+    }
+
+    @Override
+    public String getReference() {
+        return delegate.getReference();
+    }
+
+    @Override
+    public Set<TypeDefinition<?>> getTypeDefinitions() {
+        return delegate.getTypeDefinitions();
+    }
+
+    @Override
+    public Set<GroupingDefinition> getGroupings() {
+        return delegate.getGroupings();
+    }
+
+    @Override
+    public Status getStatus() {
+        return delegate.getStatus();
+    }
+
+    public ContainerSchemaNode getInput() {
+        return delegate.getInput();
+    }
+
+    public ContainerSchemaNode getOutput() {
+        return delegate.getOutput();
+    }
+
+    RpcAsContainer(final RpcDefinition parentNode) {
+        delegate = parentNode;
+    }
+
+    @Override
+    public QName getQName() {
+        return delegate.getQName();
+    }
+
+    @Override
+    public SchemaPath getPath() {
+        return delegate.getPath();
+    }
+
+    @Override
+    public List<UnknownSchemaNode> getUnknownSchemaNodes() {
+        return Collections.emptyList();
+    }
+
+    @Override
+    public DataSchemaNode getDataChildByName(final QName name) {
+        return getDataChildByName(name.getLocalName());
+    }
+
+    @Override
+    public DataSchemaNode getDataChildByName(final String name) {
+        switch (name) {
+            case "input":
+                return delegate.getInput();
+            case "output":
+                return delegate.getOutput();
+        }
+        return null;
+    }
+
+    @Override
+    public Set<UsesNode> getUses() {
+        return Collections.emptySet();
+    }
+
+    @Override
+    public Set<AugmentationSchema> getAvailableAugmentations() {
+        return Collections.emptySet();
+    }
+
+    @Override
+    public boolean isPresenceContainer() {
+        return false;
+    }
+
+    @Override
+    public Collection<DataSchemaNode> getChildNodes() {
+        final ArrayList<DataSchemaNode> ret = new ArrayList<>();
+        final ContainerSchemaNode input = getInput();
+        final ContainerSchemaNode output = getOutput();
+        if(input != null) {
+            ret.add(input);
+        }
+        if(output != null) {
+            ret.add(output);
+        }
+        return ret;
+    }
+
+    @Override
+    public boolean isAugmenting() {
+        return false;
+    }
+
+    @Override
+    public boolean isAddedByUses() {
+        return false;
+    }
+
+    @Override
+    public boolean isConfiguration() {
+        return false;
+    }
+
+    @Override
+    public ConstraintDefinition getConstraints() {
+        // TODO Auto-generated method stub
+        return null;
+    }
+
+}
index 56d12104bd8b86e27888762767bca7f4b5b88d81..c1ff375d2374ba29a7e3a9e61bd02ad768e4ccf2 100644 (file)
@@ -8,6 +8,8 @@
 package org.opendaylight.yangtools.yang.data.codec.gson;
 
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
 import static org.opendaylight.yangtools.yang.data.codec.gson.TestUtils.loadModules;
 import static org.opendaylight.yangtools.yang.data.codec.gson.TestUtils.loadTextFile;
 
@@ -23,6 +25,7 @@ import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStre
 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaNode;
 
 /**
  *
@@ -59,34 +62,34 @@ public class JsonStreamToNormalizedNodeTest {
 
     @Test
     public void leafNodeInContainer() throws IOException, URISyntaxException {
-        String inputJson = loadTextFile("/complexjson/leaf-node-in-container.json");
+        final String inputJson = loadTextFile("/complexjson/leaf-node-in-container.json");
         verifyTransformationToNormalizedNode(inputJson, TestingNormalizedNodeStructuresCreator.leafNodeInContainer());
     }
 
     @Test
     public void leafNodeViaAugmentationInContainer() throws IOException, URISyntaxException {
-        String inputJson = loadTextFile("/complexjson/leaf-node-via-augmentation-in-container.json");
+        final String inputJson = loadTextFile("/complexjson/leaf-node-via-augmentation-in-container.json");
         verifyTransformationToNormalizedNode(inputJson,
                 TestingNormalizedNodeStructuresCreator.leafNodeViaAugmentationInContainer());
     }
 
     @Test
     public void leafListNodeInContainer() throws IOException, URISyntaxException {
-        String inputJson = loadTextFile("/complexjson/leaflist-node-in-container.json");
+        final String inputJson = loadTextFile("/complexjson/leaflist-node-in-container.json");
         verifyTransformationToNormalizedNode(inputJson,
                 TestingNormalizedNodeStructuresCreator.leafListNodeInContainer());
     }
 
     @Test
     public void keyedListNodeInContainer() throws IOException, URISyntaxException {
-        String inputJson = loadTextFile("/complexjson/keyed-list-node-in-container.json");
+        final String inputJson = loadTextFile("/complexjson/keyed-list-node-in-container.json");
         verifyTransformationToNormalizedNode(inputJson,
                 TestingNormalizedNodeStructuresCreator.keyedListNodeInContainer());
     }
 
     @Test
     public void choiceNodeInContainer() throws IOException, URISyntaxException {
-        String inputJson = loadTextFile("/complexjson/choice-node-in-container.json");
+        final String inputJson = loadTextFile("/complexjson/choice-node-in-container.json");
         verifyTransformationToNormalizedNode(inputJson, TestingNormalizedNodeStructuresCreator.choiceNodeInContainer());
     }
 
@@ -99,7 +102,7 @@ public class JsonStreamToNormalizedNodeTest {
      */
     @Test
     public void caseNodeAugmentationInChoiceInContainer() throws IOException, URISyntaxException {
-        String inputJson = loadTextFile("/complexjson/case-node-augmentation-in-choice-in-container.json");
+        final String inputJson = loadTextFile("/complexjson/case-node-augmentation-in-choice-in-container.json");
         verifyTransformationToNormalizedNode(inputJson,
                 TestingNormalizedNodeStructuresCreator.caseNodeAugmentationInChoiceInContainer());
     }
@@ -112,7 +115,7 @@ public class JsonStreamToNormalizedNodeTest {
      */
     @Test
     public void caseNodeExternalAugmentationInChoiceInContainer() throws IOException, URISyntaxException {
-        String inputJson = loadTextFile("/complexjson/case-node-external-augmentation-in-choice-in-container.json");
+        final String inputJson = loadTextFile("/complexjson/case-node-external-augmentation-in-choice-in-container.json");
         verifyTransformationToNormalizedNode(inputJson,
                 TestingNormalizedNodeStructuresCreator.caseNodeExternalAugmentationInChoiceInContainer());
     }
@@ -122,24 +125,101 @@ public class JsonStreamToNormalizedNodeTest {
      */
     @Test
     public void choiceNodeAugmentationInContainer() throws IOException, URISyntaxException {
-        String inputJson = loadTextFile("/complexjson/choice-node-augmentation-in-container.json");
+        final String inputJson = loadTextFile("/complexjson/choice-node-augmentation-in-container.json");
         verifyTransformationToNormalizedNode(inputJson,
                 TestingNormalizedNodeStructuresCreator.choiceNodeAugmentationInContainer());
     }
 
     @Test
     public void unkeyedNodeInContainer() throws IOException, URISyntaxException {
-        String inputJson = loadTextFile("/complexjson/unkeyed-node-in-container.json");
+        final String inputJson = loadTextFile("/complexjson/unkeyed-node-in-container.json");
         verifyTransformationToNormalizedNode(inputJson, TestingNormalizedNodeStructuresCreator.unkeyedNodeInContainer());
     }
 
+    /**
+     * Top level JSON element contains no information about module name.
+     *
+     * It should be possible to find out potential module name from available schema context.
+     *
+     */
+    @Test
+    public void missingModuleInfoInTopLevelElement() throws IOException, URISyntaxException {
+        final String inputJson = loadTextFile("/complexjson/missing-module-in-top-level.json");
+        verifyTransformationToNormalizedNode(inputJson, TestingNormalizedNodeStructuresCreator.topLevelContainer());
+    }
+
+    /**
+     *
+     * Exception expected.
+     *
+     * It tests case when several elements with the same name and various namespaces exists and are in JSON specified
+     * without module name prefix.
+     */
+    @Test
+    public void leafNamesakes() throws IOException, URISyntaxException {
+        final String inputJson = loadTextFile("/complexjson/namesakes.json");
+        try {
+            //second parameter isn't necessary because error will be raised before it is used.
+            verifyTransformationToNormalizedNode(inputJson, null);
+        } catch (final IllegalStateException e) {
+            final String errorMessage = e.getMessage();
+            assertTrue(errorMessage.contains("Choose suitable module name for element lf11-namesake:"));
+            assertTrue(errorMessage.contains("complexjson-augmentation"));
+            assertTrue(errorMessage.contains("complexjson-augmentation-namesake"));
+        }
+    }
+
+    /**
+     *
+     * Exception expected.
+     *
+     * Json input contains element which doesn't exist in YANG schema
+     */
+    @Test
+    public void parsingNotExistingElement() throws IOException, URISyntaxException {
+        final String inputJson = loadTextFile("/complexjson/not-existing-element.json");
+        try {
+            //second parameter isn't necessary because error will be raised before it is used.
+            verifyTransformationToNormalizedNode(inputJson, null);
+        } catch (final IllegalStateException e) {
+            assertTrue(e.getMessage().contains("Schema node with name dummy-element wasn't found."));
+        }
+    }
+
+
+    @Test
+    public void listItemWithoutArray() throws IOException, URISyntaxException {
+        final String inputJson = loadTextFile("/complexjson/keyed-list-restconf-behaviour.json");
+
+        final NormalizedNodeResult result = new NormalizedNodeResult();
+        final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);
+        final SchemaNode parentNode = schemaContext.getDataChildByName("cont1");
+        final JsonParserStream jsonParser = JsonParserStream.create(streamWriter, schemaContext, parentNode);
+        jsonParser.parse(new JsonReader(new StringReader(inputJson)));
+        final NormalizedNode<?, ?> transformedInput = result.getResult();
+        assertNotNull(transformedInput);
+    }
+
+    @Test
+    public void listItemWithArray() throws IOException, URISyntaxException {
+        final String inputJson = loadTextFile("/complexjson/keyed-list-yang-json-behaviour.json");
+
+        final NormalizedNodeResult result = new NormalizedNodeResult();
+        final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);
+        final SchemaNode parentNode = schemaContext.getDataChildByName("cont1");
+        final JsonParserStream jsonParser = JsonParserStream.create(streamWriter, schemaContext, parentNode);
+        jsonParser.parse(new JsonReader(new StringReader(inputJson)));
+        final NormalizedNode<?, ?> transformedInput = result.getResult();
+        assertNotNull(transformedInput);
+    }
+
     private void verifyTransformationToNormalizedNode(final String inputJson,
             final NormalizedNode<?, ?> awaitedStructure) {
-        NormalizedNodeResult result = new NormalizedNodeResult();
+        final NormalizedNodeResult result = new NormalizedNodeResult();
         final NormalizedNodeStreamWriter streamWriter = ImmutableNormalizedNodeStreamWriter.from(result);
-        JsonParserStream jsonParser = JsonParserStream.create(streamWriter, schemaContext);
+        final JsonParserStream jsonParser = JsonParserStream.create(streamWriter, schemaContext);
         jsonParser.parse(new JsonReader(new StringReader(inputJson)));
-        NormalizedNode<?, ?> transformedInput = result.getResult();
+        final NormalizedNode<?, ?> transformedInput = result.getResult();
         assertEquals("Transformation of json input to normalized node wasn't successful.", awaitedStructure,
                 transformedInput);
     }
index 39a1f1bc7bbe30c9cd131cd581d7269650ed4b0a..90fd51b80302a420df40ef01a93ef81cec99a4f0 100644 (file)
@@ -7,11 +7,26 @@
  */
 package org.opendaylight.yangtools.yang.data.codec.gson;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.opendaylight.yangtools.yang.data.codec.gson.TestUtils.childArray;
+import static org.opendaylight.yangtools.yang.data.codec.gson.TestUtils.childPrimitive;
+import static org.opendaylight.yangtools.yang.data.codec.gson.TestUtils.loadModules;
+import static org.opendaylight.yangtools.yang.data.codec.gson.TestUtils.resolveCont1;
+
 import com.google.common.collect.Sets;
 import com.google.gson.JsonArray;
 import com.google.gson.JsonElement;
 import com.google.gson.JsonObject;
 import com.google.gson.JsonPrimitive;
+import java.io.IOException;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.net.URISyntaxException;
+import java.util.HashSet;
+import java.util.Iterator;
 import org.junit.BeforeClass;
 import org.junit.Ignore;
 import org.junit.Test;
@@ -20,22 +35,6 @@ import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStre
 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
-import java.io.IOException;
-import java.io.StringWriter;
-import java.io.Writer;
-import java.net.URISyntaxException;
-import java.util.HashSet;
-import java.util.Iterator;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.opendaylight.yangtools.yang.data.codec.gson.TestUtils.childArray;
-import static org.opendaylight.yangtools.yang.data.codec.gson.TestUtils.childPrimitive;
-import static org.opendaylight.yangtools.yang.data.codec.gson.TestUtils.loadModules;
-import static org.opendaylight.yangtools.yang.data.codec.gson.TestUtils.resolveCont1;
-
 /**
  * Each test tests whether json output obtained after transformation contains is corect. The transformation takes
  * normalized node data structure and transform it to json output. To make it easier validate json output it is loaded
@@ -201,7 +200,7 @@ public class NormalizedNodeToJsonStreamTest {
                 assertNotNull(lf111);
 
                 assertEquals("key111 value", key111.getAsString());
-                assertEquals("/complexjson:cont1/complexjson:lflst11", lf112.getAsString());
+                assertEquals("/complexjson:cont1/complexjson:lflst11[.='foo']", lf112.getAsString());
                 assertEquals("lf113 value", lf113.getAsString());
                 assertEquals("lf111 value", lf111.getAsString());
             }
@@ -382,11 +381,11 @@ public class NormalizedNodeToJsonStreamTest {
 
     private String normalizedNodeToJsonStreamTransformation(final Writer writer,
             final NormalizedNode<?, ?> inputStructure) throws IOException {
-        writer.write("{\n");
+
         final NormalizedNodeStreamWriter jsonStream = JSONNormalizedNodeStreamWriter.create(schemaContext, writer, 2);
         final NormalizedNodeWriter nodeWriter = NormalizedNodeWriter.forStreamWriter(jsonStream);
         nodeWriter.write(inputStructure);
-        writer.write("\n}");
+
         nodeWriter.close();
         return writer.toString();
     }
index 71a2b99e7f9f914cac06c50fcfdb8480d2981c8c..978b11005156243bb118dcb5cf88761b9d6f5aa6 100644 (file)
@@ -9,12 +9,11 @@ package org.opendaylight.yangtools.yang.data.codec.gson;
 
 import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
+import java.util.HashMap;
+import java.util.Map;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.InstanceIdentifierBuilder;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
@@ -30,17 +29,12 @@ import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
-import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
 
-import java.util.HashMap;
-import java.util.Map;
-
 public class TestingNormalizedNodeStructuresCreator {
 
     static NormalizedNode<?, ?> cont1Node(
@@ -215,10 +209,11 @@ public class TestingNormalizedNodeStructuresCreator {
     }
 
     private static Object lf112Value() {
-        InstanceIdentifierBuilder builder = YangInstanceIdentifier.builder();
-        builder.node(QName.create("ns:complex:json", "2014-08-11", "cont1"));
-        builder.node(QName.create("ns:complex:json", "2014-08-11", "lflst11"));
-        return builder.build();
+        return YangInstanceIdentifier.create(
+                new NodeIdentifier(QName.create("ns:complex:json", "2014-08-11", "cont1")),
+                new NodeIdentifier(QName.create("ns:complex:json", "2014-08-11", "lflst11")),
+                new NodeWithValue(QName.create("ns:complex:json", "2014-08-11", "lflst11"),"foo")
+        );
     }
 
     private static DataContainerChild<? extends PathArgument, ?> childLflst11() {
@@ -253,24 +248,10 @@ public class TestingNormalizedNodeStructuresCreator {
         return lflst11.build();
     }
 
-    private static CompositeNode prepareLf12Value() {
-        SimpleNode<?> anyxmlInData = NodeFactory.createImmutableSimpleNode(
-                QName.create("ns:complex:json", "2014-08-11", "anyxml-in-data"), null, "foo");
-        return ImmutableCompositeNode.builder().add(anyxmlInData)
-                .setQName(QName.create("ns:complex:json", "2014-08-11", "lf12-any")).build();
-    }
-
-    private static CompositeNode prepareLf13Value() {
-        SimpleNode<?> anyxmlInData = NodeFactory.createImmutableSimpleNode(
-                QName.create("ns:complex:json", "2014-08-11", "anyxml-in-data"), null, "foo");
-        return ImmutableCompositeNode.builder().add(anyxmlInData)
-                .setQName(QName.create("ns:complex:json", "2014-08-11", "lf13-any")).build();
-    }
-
     public static NormalizedNode<?, ?> leafNodeInContainer() {
         LeafNode<Object> lf11 = Builders.leafBuilder()
                 .withNodeIdentifier(new NodeIdentifier(QName.create("ns:complex:json", "2014-08-11", "lf11")))
-                .withValue((int) 453).build();
+                .withValue(453).build();
         return cont1Node(lf11);
     }
 
@@ -314,4 +295,7 @@ public class TestingNormalizedNodeStructuresCreator {
         return cont1Node(lst12Node());
     }
 
+    public static NormalizedNode<?, ?> topLevelContainer() {
+        return cont1Node();
+    }
 }
index fd4538833bd40457a225437a51e3a0e3692bafa6..07490bdb633bd712fe96f3c4c039cdc30c98d069 100644 (file)
@@ -17,7 +17,7 @@
         "lst11":[
             {
                 "key111":"key111 value",
-                "lf112":"/complexjson:cont1/complexjson:lflst11",
+                "lf112":"/complexjson:cont1/complexjson:lflst11[.='foo']",
                 "lf113":"lf113 value",
                 "lf111":"lf111 value"
             }
index 7cb51939ab4e479896b9e1f5a995e84473e8943b..dbcc8a91e830e292df7c67d32adecb38b2f8ddd8 100644 (file)
@@ -3,7 +3,7 @@
         "lst11":[
             {
                 "key111":"key111 value",
-                "lf112":"/complexjson:cont1/complexjson:lflst11",
+                "lf112":"/complexjson:cont1/complexjson:lflst11[.='foo']",
                 "lf113":"lf113 value",
                 "lf111":"lf111 value"
             }
diff --git a/yang/yang-data-codec-gson/src/test/resources/complexjson/keyed-list-restconf-behaviour.json b/yang/yang-data-codec-gson/src/test/resources/complexjson/keyed-list-restconf-behaviour.json
new file mode 100644 (file)
index 0000000..2844d7d
--- /dev/null
@@ -0,0 +1,8 @@
+{
+  "lst11": {
+                "key111":"key111 value",
+                "lf112":"/complexjson:cont1/complexjson:lflst11[.='foo']",
+                "lf113":"lf113 value",
+                "lf111":"lf111 value"
+            }
+}
diff --git a/yang/yang-data-codec-gson/src/test/resources/complexjson/keyed-list-yang-json-behaviour.json b/yang/yang-data-codec-gson/src/test/resources/complexjson/keyed-list-yang-json-behaviour.json
new file mode 100644 (file)
index 0000000..af6b3ec
--- /dev/null
@@ -0,0 +1,8 @@
+{
+  "lst11": [{
+                "key111":"key111 value",
+                "lf112":"/complexjson:cont1/complexjson:lflst11[.='foo']",
+                "lf113":"lf113 value",
+                "lf111":"lf111 value"
+            }]
+}
diff --git a/yang/yang-data-codec-gson/src/test/resources/complexjson/missing-module-in-top-level.json b/yang/yang-data-codec-gson/src/test/resources/complexjson/missing-module-in-top-level.json
new file mode 100644 (file)
index 0000000..1070c36
--- /dev/null
@@ -0,0 +1,4 @@
+{
+    "cont1": {
+    }
+}
diff --git a/yang/yang-data-codec-gson/src/test/resources/complexjson/namesakes.json b/yang/yang-data-codec-gson/src/test/resources/complexjson/namesakes.json
new file mode 100644 (file)
index 0000000..9c0fab4
--- /dev/null
@@ -0,0 +1,5 @@
+{
+    "cont1": {
+        "lf11-namesake":"value lf11"
+    }
+}
\ No newline at end of file
diff --git a/yang/yang-data-codec-gson/src/test/resources/complexjson/not-existing-element.json b/yang/yang-data-codec-gson/src/test/resources/complexjson/not-existing-element.json
new file mode 100644 (file)
index 0000000..ebc44bb
--- /dev/null
@@ -0,0 +1,5 @@
+{
+    "cont1": {
+        "dummy-element":"value lf11"
+    }
+}
\ No newline at end of file
diff --git a/yang/yang-data-codec-gson/src/test/resources/complexjson/yang/complexjson-augmentation-namesake.yang b/yang/yang-data-codec-gson/src/test/resources/complexjson/yang/complexjson-augmentation-namesake.yang
new file mode 100644 (file)
index 0000000..e94acb2
--- /dev/null
@@ -0,0 +1,18 @@
+module complexjson-augmentation-namesake {
+    namespace "ns:complex:json:augmentation:namesake";
+    prefix cjaugnmsk;
+
+  import complexjson {
+    prefix cj;
+  }
+
+    revision "2014-08-14" {
+    }
+
+    augment "/cj:cont1" {
+        leaf lf11-namesake {
+            type string;
+        }
+    }
+
+}
index d4ea623b19098c9d073b2d00012839ad99f16113..a4cf5adeb52738569597e4aa6614ea2ff8e5a12b 100644 (file)
@@ -1,24 +1,30 @@
 module complexjson-augmentation {
     namespace "ns:complex:json:augmentation";
     prefix cjaug;
-    
+
   import complexjson {
     prefix cj;
-  }    
+  }
 
-    revision "2014-08-14" {        
+    revision "2014-08-14" {
     }
-    
+
+    augment "/cj:cont1" {
+        leaf lf11-namesake {
+            type string;
+        }
+    }
+
     augment "/cj:cont1/cj:choc11/cj:c11A" {
-        leaf lf15_11  {
+        leaf lf15_11 {
                     type string;
                 }
-        leaf lf15_12  {
+        leaf lf15_12 {
                     type string;
                 }
-                
-    }    
-    
+
+    }
+
     augment "/cj:cont1" {
         leaf lf12_1aug {
                     type string;
@@ -26,12 +32,12 @@ module complexjson-augmentation {
         leaf lf12_2aug {
             type string;
         }
-    }    
-    
+    }
+
     augment "/cj:cont1/cj:choc11/cj:c11A" {
         leaf lf15_21aug {
                     type string;
                 }
-    }    
+    }
 
 }
diff --git a/yang/yang-data-composite-node/pom.xml b/yang/yang-data-composite-node/pom.xml
deleted file mode 100644 (file)
index 3d62dee..0000000
+++ /dev/null
@@ -1,64 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: -->
-<!-- Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
-       This program and the accompanying materials are made available under the
-       terms of the Eclipse Public License v1.0 which accompanies this distribution,
-       and is available at http://www.eclipse.org/legal/epl-v10.html -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
-       xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
-
-       <parent>
-               <groupId>org.opendaylight.yangtools</groupId>
-               <artifactId>yangtools-parent</artifactId>
-               <version>0.7.0-SNAPSHOT</version>
-               <relativePath>/../../common/parent/pom.xml</relativePath>
-       </parent>
-
-       <modelVersion>4.0.0</modelVersion>
-       <artifactId>yang-data-composite-node</artifactId>
-       <name>${project.artifactId}</name>
-       <description>${project.artifactId}</description>
-    <packaging>bundle</packaging>
-
-    <dependencies>
-        <dependency>
-            <groupId>${project.groupId}</groupId>
-            <artifactId>yang-data-api</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>${project.groupId}</groupId>
-            <artifactId>yang-data-impl</artifactId>
-        </dependency>
-        <dependency>
-            <groupId>${project.groupId}</groupId>
-            <artifactId>yang-model-api</artifactId>
-        </dependency>
-        <dependency>
-          <groupId>junit</groupId>
-          <artifactId>junit</artifactId>
-          <scope>test</scope>
-        </dependency>
-        <dependency>
-            <groupId>${project.groupId}</groupId>
-            <artifactId>yang-parser-impl</artifactId>
-            <scope>test</scope>
-        </dependency>
-    </dependencies>
-
-  <build>
-    <plugins>
-      <plugin>
-        <groupId>org.apache.felix</groupId>
-        <artifactId>maven-bundle-plugin</artifactId>
-        <extensions>true</extensions>
-        <configuration>
-          <instructions>
-            <Bundle-Name>Composite node Normalized node transformator</Bundle-Name>
-            <Import-Package>*</Import-Package>
-          </instructions>
-        </configuration>
-      </plugin>
-    </plugins>
-  </build>
-
-</project>
diff --git a/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/AnyXmlNodeCnSnParser.java b/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/AnyXmlNodeCnSnParser.java
deleted file mode 100644 (file)
index a13dd4b..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.AnyXmlNodeBaseParser;
-import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
-
-public class AnyXmlNodeCnSnParser extends AnyXmlNodeBaseParser<Node<?>> {
-
-    public AnyXmlNodeCnSnParser() {
-        super();
-    }
-
-    @Override
-    protected Node<?> parseAnyXml(Node<?> element, AnyXmlSchemaNode schema) {
-        return element;
-    }
-}
diff --git a/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/AugmentationNodeCnSnParser.java b/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/AugmentationNodeCnSnParser.java
deleted file mode 100644 (file)
index 452ec95..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser;
-
-import org.opendaylight.yangtools.yang.data.composite.node.schema.json.CnSnToNormalizedNodesUtils;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.AugmentationNodeBaseParser;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.NodeParserDispatcher;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.LinkedListMultimap;
-
-public final class AugmentationNodeCnSnParser extends AugmentationNodeBaseParser<Node<?>> {
-
-    private final NodeParserDispatcher<Node<?>> dispatcher;
-
-    public AugmentationNodeCnSnParser(final NodeParserDispatcher<Node<?>> dispatcher) {
-        this.dispatcher = Preconditions.checkNotNull(dispatcher);
-    }
-
-    @Override
-    protected LinkedListMultimap<QName, Node<?>> mapChildElements(Iterable<Node<?>> elements) {
-        return CnSnToNormalizedNodesUtils.mapChildElements(elements);
-    }
-
-    @Override
-    protected NodeParserDispatcher<Node<?>> getDispatcher() {
-        return dispatcher;
-    }
-
-}
diff --git a/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/ChoiceNodeCnSnParser.java b/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/ChoiceNodeCnSnParser.java
deleted file mode 100644 (file)
index 389ffcf..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser;
-
-import org.opendaylight.yangtools.yang.data.composite.node.schema.json.CnSnToNormalizedNodesUtils;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.ChoiceNodeBaseParser;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.NodeParserDispatcher;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.LinkedListMultimap;
-
-public final class ChoiceNodeCnSnParser extends ChoiceNodeBaseParser<Node<?>> {
-
-    private final NodeParserDispatcher<Node<?>> dispatcher;
-
-    public ChoiceNodeCnSnParser(final NodeParserDispatcher<Node<?>> dispatcher) {
-        this.dispatcher = Preconditions.checkNotNull(dispatcher);
-    }
-
-    @Override
-    protected LinkedListMultimap<QName, Node<?>> mapChildElements(Iterable<Node<?>> elements) {
-        return CnSnToNormalizedNodesUtils.mapChildElements(elements);
-    }
-
-    @Override
-    protected NodeParserDispatcher<Node<?>> getDispatcher() {
-        return dispatcher;
-    }
-
-}
diff --git a/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/CnSnToNormalizedNodeParserFactory.java b/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/CnSnToNormalizedNodeParserFactory.java
deleted file mode 100644 (file)
index ce0e20a..0000000
+++ /dev/null
@@ -1,109 +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.yangtools.yang.data.composite.node.schema.cnsn.parser;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
-import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
-import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
-import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
-import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParser;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParserFactory;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.NodeParserDispatcher;
-import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-
-public class CnSnToNormalizedNodeParserFactory implements ToNormalizedNodeParserFactory<Node<?>> {
-
-    private final ContainerNodeCnSnParser containerNodeCnSnParser;
-    private final LeafNodeCnSnParser leafNodeCnSnParser;
-    private final LeafSetEntryNodeCnSnParser leafSetEntryNodeCnSnParser;
-    private final LeafSetNodeCnSnParser leafSetNodeCnSnParser;
-    private final MapNodeCnSnParser mapNodeCnSnParser;
-    private final MapEntryNodeCnSnParser mapEntryNodeCnSnParser;
-    private final ChoiceNodeCnSnParser choiceNodeCnSnParser;
-    private final AugmentationNodeCnSnParser augmentationNodeCnSnParser;
-    private final AnyXmlNodeCnSnParser anyXmlNodeCnSnParser;
-
-    private CnSnToNormalizedNodeParserFactory() {
-        leafNodeCnSnParser = new LeafNodeCnSnParser();
-        leafSetEntryNodeCnSnParser = new LeafSetEntryNodeCnSnParser();
-        leafSetNodeCnSnParser = new LeafSetNodeCnSnParser(leafSetEntryNodeCnSnParser);
-        anyXmlNodeCnSnParser = new AnyXmlNodeCnSnParser();
-
-        final NodeParserDispatcher<Node<?>> dispatcher = new NodeParserDispatcher.BaseNodeParserDispatcher<Node<?>>(
-                this) {
-
-        };
-
-        containerNodeCnSnParser = new ContainerNodeCnSnParser(dispatcher);
-        mapEntryNodeCnSnParser = new MapEntryNodeCnSnParser(dispatcher);
-        mapNodeCnSnParser = new MapNodeCnSnParser(mapEntryNodeCnSnParser);
-        choiceNodeCnSnParser = new ChoiceNodeCnSnParser(dispatcher);
-        augmentationNodeCnSnParser = new AugmentationNodeCnSnParser(dispatcher);
-
-    }
-
-    public static CnSnToNormalizedNodeParserFactory getInstance() {
-        return new CnSnToNormalizedNodeParserFactory();
-    }
-
-    @Override
-    public ToNormalizedNodeParser<Node<?>, ContainerNode, ContainerSchemaNode> getContainerNodeParser() {
-        return containerNodeCnSnParser;
-    }
-
-    @Override
-    public ToNormalizedNodeParser<Node<?>, LeafNode<?>, LeafSchemaNode> getLeafNodeParser() {
-        return leafNodeCnSnParser;
-    }
-
-    @Override
-    public ToNormalizedNodeParser<Node<?>, LeafSetNode<?>, LeafListSchemaNode> getLeafSetNodeParser() {
-        return leafSetNodeCnSnParser;
-    }
-
-    @Override
-    public ToNormalizedNodeParser<Node<?>, MapNode, ListSchemaNode> getMapNodeParser() {
-        return mapNodeCnSnParser;
-    }
-
-    @Override
-    public ToNormalizedNodeParser<Node<?>, org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode, ChoiceNode> getChoiceNodeParser() {
-        return choiceNodeCnSnParser;
-    }
-
-    @Override
-    public ToNormalizedNodeParser<Node<?>, AugmentationNode, AugmentationSchema> getAugmentationNodeParser() {
-        return augmentationNodeCnSnParser;
-    }
-
-    @Override
-    public ToNormalizedNodeParser<Node<?>, LeafSetEntryNode<?>, LeafListSchemaNode> getLeafSetEntryNodeParser() {
-        return leafSetEntryNodeCnSnParser;
-    }
-
-    @Override
-    public ToNormalizedNodeParser<Node<?>, MapEntryNode, ListSchemaNode> getMapEntryNodeParser() {
-        return mapEntryNodeCnSnParser;
-    }
-
-    @Override
-    public ToNormalizedNodeParser<Node<?>, AnyXmlNode, AnyXmlSchemaNode> getAnyXmlNodeParser() {
-        return anyXmlNodeCnSnParser;
-    }
-}
diff --git a/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/ContainerNodeCnSnParser.java b/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/ContainerNodeCnSnParser.java
deleted file mode 100644 (file)
index 623d81d..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser;
-
-import org.opendaylight.yangtools.yang.data.composite.node.schema.json.CnSnToNormalizedNodesUtils;
-
-import java.util.Collections;
-import java.util.Map;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.ContainerNodeBaseParser;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.NodeParserDispatcher;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.LinkedListMultimap;
-
-public final class ContainerNodeCnSnParser extends ContainerNodeBaseParser<Node<?>> {
-
-    private final NodeParserDispatcher<Node<?>> dispatcher;
-
-    public ContainerNodeCnSnParser(final NodeParserDispatcher<Node<?>> dispatcher) {
-        this.dispatcher = Preconditions.checkNotNull(dispatcher);
-    }
-
-    @Override
-    protected NodeParserDispatcher<Node<?>> getDispatcher() {
-        return dispatcher;
-    }
-
-    @Override
-    protected LinkedListMultimap<QName, Node<?>> mapChildElements(Iterable<Node<?>> elements) {
-        return CnSnToNormalizedNodesUtils.mapChildElementsForSingletonNode(elements.iterator().next());
-    }
-
-    @Override
-    protected Map<QName, String> getAttributes(Node<?> e) {
-        return Collections.emptyMap();
-    }
-
-}
diff --git a/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/LeafNodeCnSnParser.java b/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/LeafNodeCnSnParser.java
deleted file mode 100644 (file)
index cede56c..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser;
-
-import java.util.Collections;
-import java.util.Map;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.LeafNodeBaseParser;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
-
-public class LeafNodeCnSnParser extends LeafNodeBaseParser<Node<?>> {
-
-    public LeafNodeCnSnParser() {
-        super();
-    }
-
-    @Override
-    protected Object parseLeaf(Node<?> elements, LeafSchemaNode schema) {
-        return elements.getValue();
-    }
-
-    @Override
-    protected Map<QName, String> getAttributes(Node<?> e) {
-        return Collections.emptyMap();
-    }
-}
diff --git a/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/LeafSetEntryNodeCnSnParser.java b/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/LeafSetEntryNodeCnSnParser.java
deleted file mode 100644 (file)
index 41a5a9e..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser;
-
-import java.util.Collections;
-import java.util.Map;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.LeafSetEntryNodeBaseParser;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-
-public class LeafSetEntryNodeCnSnParser extends LeafSetEntryNodeBaseParser<Node<?>> {
-
-    public LeafSetEntryNodeCnSnParser() {
-        super();
-    }
-
-    @Override
-    protected Object parseLeafListEntry(Node<?> elements, LeafListSchemaNode schema) {
-        return elements.getValue();
-    }
-
-    @Override
-    protected Map<QName, String> getAttributes(Node<?> e) {
-        return Collections.emptyMap();
-    }
-}
diff --git a/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/LeafSetNodeCnSnParser.java b/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/LeafSetNodeCnSnParser.java
deleted file mode 100644 (file)
index b0ffefa..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParser;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.LeafSetNodeBaseParser;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-
-public class LeafSetNodeCnSnParser extends LeafSetNodeBaseParser<Node<?>> {
-
-    private final LeafSetEntryNodeCnSnParser leafSetEntryNodeCnSnParser;
-
-    public LeafSetNodeCnSnParser(LeafSetEntryNodeCnSnParser leafSetEntryNodeCnSnParser) {
-        this.leafSetEntryNodeCnSnParser = leafSetEntryNodeCnSnParser;
-    }
-
-    @Override
-    protected ToNormalizedNodeParser<Node<?>, LeafSetEntryNode<?>, LeafListSchemaNode> getLeafSetEntryNodeParser() {
-        return leafSetEntryNodeCnSnParser;
-    }
-}
diff --git a/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/MapEntryNodeCnSnParser.java b/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/parser/MapEntryNodeCnSnParser.java
deleted file mode 100644 (file)
index ad0b846..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser;
-
-import org.opendaylight.yangtools.yang.data.composite.node.schema.json.CnSnToNormalizedNodesUtils;
-
-import java.util.Collections;
-import java.util.Map;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.MapEntryNodeBaseParser;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.NodeParserDispatcher;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.LinkedListMultimap;
-
-public final class MapEntryNodeCnSnParser extends MapEntryNodeBaseParser<Node<?>> {
-
-    private final NodeParserDispatcher<Node<?>> dispatcher;
-
-    public MapEntryNodeCnSnParser(final NodeParserDispatcher<Node<?>> dispatcher) {
-        this.dispatcher = Preconditions.checkNotNull(dispatcher);
-    }
-
-
-    @Override
-    protected LinkedListMultimap<QName, Node<?>> mapChildElements(Iterable<Node<?>> elements) {
-        return CnSnToNormalizedNodesUtils.mapChildElementsForSingletonNode(elements.iterator().next());
-    }
-
-    @Override
-    protected NodeParserDispatcher<Node<?>> getDispatcher() {
-        return dispatcher;
-    }
-
-    @Override
-    protected Map<QName, String> getAttributes(Node<?> e) {
-        return Collections.emptyMap();
-    }
-}
diff --git a/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/AnyXmlNodeCnSnSerializer.java b/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/AnyXmlNodeCnSnSerializer.java
deleted file mode 100644 (file)
index db941ed..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.AnyXmlNodeBaseSerializer;
-
-public class AnyXmlNodeCnSnSerializer extends AnyXmlNodeBaseSerializer<Node<?>> {
-
-    @Override
-    protected Node<?> serializeAnyXml(AnyXmlNode node) {
-        return node.getValue();
-    }
-}
diff --git a/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/AugmentationNodeCnSnSerializer.java b/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/AugmentationNodeCnSnSerializer.java
deleted file mode 100644 (file)
index 6aa294e..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.AugmentationNodeBaseSerializer;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
-
-import com.google.common.base.Preconditions;
-
-public class AugmentationNodeCnSnSerializer extends AugmentationNodeBaseSerializer<Node<?>> {
-
-    private NodeSerializerDispatcher<Node<?>> dispatcher;
-
-    AugmentationNodeCnSnSerializer(final NodeSerializerDispatcher<Node<?>> dispatcher) {
-        this.dispatcher = Preconditions.checkNotNull(dispatcher);
-    }
-
-    @Override
-    protected NodeSerializerDispatcher<Node<?>> getNodeDispatcher() {
-        return dispatcher;
-    }
-}
diff --git a/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/ChoiceNodeCnSnSerializer.java b/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/ChoiceNodeCnSnSerializer.java
deleted file mode 100644 (file)
index 2a79170..0000000
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.ChoiceNodeBaseSerializer;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
-
-import com.google.common.base.Preconditions;
-
-public class ChoiceNodeCnSnSerializer
-        extends
-        ChoiceNodeBaseSerializer<Node<?>> {
-
-    private final NodeSerializerDispatcher<Node<?>> dispatcher;
-
-    ChoiceNodeCnSnSerializer(final NodeSerializerDispatcher<Node<?>> dispatcher) {
-        this.dispatcher = Preconditions.checkNotNull(dispatcher);
-    }
-
-    @Override
-    protected NodeSerializerDispatcher<Node<?>> getNodeDispatcher() {
-        return dispatcher;
-    }
-}
diff --git a/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/CnSnFromNormalizedNodeSerializerFactory.java b/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/CnSnFromNormalizedNodeSerializerFactory.java
deleted file mode 100644 (file)
index 681c624..0000000
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
-import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
-import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
-import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
-import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
-import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializer;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializerFactory;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
-import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-
-public final class CnSnFromNormalizedNodeSerializerFactory implements FromNormalizedNodeSerializerFactory<Node<?>> {
-    private final ContainerNodeCnSnSerializer containerSerializer;
-    private final ChoiceNodeCnSnSerializer choiceSerializer;
-    private final AugmentationNodeCnSnSerializer augmentSerializer;
-    private final LeafNodeCnSnSerializer leafNodeSerializer;
-    private final LeafSetNodeCnSnSerializer leafSetSerializer;
-    private final MapNodeCnSnSerializer mapNodeSerializer;
-    private final LeafSetEntryNodeCnSnSerializer leafSetEntryNodeSerializer;
-    private final MapEntryNodeCnSnSerializer mapEntryNodeSerializer;
-    private final AnyXmlNodeCnSnSerializer anyXmlNodeSerializer;
-
-    private CnSnFromNormalizedNodeSerializerFactory() {
-        final NodeSerializerDispatcher.BaseNodeSerializerDispatcher<Node<?>> dispatcher = new NodeSerializerDispatcher.BaseNodeSerializerDispatcher<Node<?>>(
-                this) {
-
-        };
-
-        containerSerializer = new ContainerNodeCnSnSerializer(dispatcher);
-        choiceSerializer = new ChoiceNodeCnSnSerializer(dispatcher);
-        augmentSerializer = new AugmentationNodeCnSnSerializer(dispatcher);
-        leafNodeSerializer = new LeafNodeCnSnSerializer();
-        anyXmlNodeSerializer = new AnyXmlNodeCnSnSerializer();
-
-        leafSetEntryNodeSerializer = new LeafSetEntryNodeCnSnSerializer();
-        leafSetSerializer = new LeafSetNodeCnSnSerializer(leafSetEntryNodeSerializer);
-
-        mapEntryNodeSerializer = new MapEntryNodeCnSnSerializer(dispatcher);
-        mapNodeSerializer = new MapNodeCnSnSerializer(mapEntryNodeSerializer);
-    }
-
-
-    public static CnSnFromNormalizedNodeSerializerFactory getInstance() {
-        return new CnSnFromNormalizedNodeSerializerFactory();
-}
-
-    @Override
-    public FromNormalizedNodeSerializer<Node<?>, ContainerNode, ContainerSchemaNode> getContainerNodeSerializer() {
-        return containerSerializer;
-    }
-
-    @Override
-    public FromNormalizedNodeSerializer<Node<?>, LeafNode<?>, LeafSchemaNode> getLeafNodeSerializer() {
-        return leafNodeSerializer;
-    }
-
-    @Override
-    public FromNormalizedNodeSerializer<Node<?>, LeafSetNode<?>, LeafListSchemaNode> getLeafSetNodeSerializer() {
-        return leafSetSerializer;
-    }
-
-    @Override
-    public FromNormalizedNodeSerializer<Node<?>, MapNode, ListSchemaNode> getMapNodeSerializer() {
-        return mapNodeSerializer;
-    }
-
-    @Override
-    public FromNormalizedNodeSerializer<Node<?>, ChoiceNode, org.opendaylight.yangtools.yang.model.api.ChoiceNode> getChoiceNodeSerializer() {
-        return choiceSerializer;
-    }
-
-    @Override
-    public FromNormalizedNodeSerializer<Node<?>, AugmentationNode, AugmentationSchema> getAugmentationNodeSerializer() {
-        return augmentSerializer;
-    }
-
-
-    @Override
-    public FromNormalizedNodeSerializer<Node<?>, LeafSetEntryNode<?>, LeafListSchemaNode> getLeafSetEntryNodeSerializer() {
-        return leafSetEntryNodeSerializer;
-    }
-
-
-    @Override
-    public FromNormalizedNodeSerializer<Node<?>, MapEntryNode, ListSchemaNode> getMapEntryNodeSerializer() {
-        return mapEntryNodeSerializer;
-    }
-
-    @Override
-    public FromNormalizedNodeSerializer<Node<?>, AnyXmlNode, AnyXmlSchemaNode> getAnyXmlNodeSerializer() {
-        return anyXmlNodeSerializer;
-    }
-}
diff --git a/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/ContainerNodeCnSnSerializer.java b/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/ContainerNodeCnSnSerializer.java
deleted file mode 100644 (file)
index ddba0e1..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer;
-
-import com.google.common.base.Preconditions;
-import java.util.Collections;
-import java.util.List;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.ContainerNodeBaseSerializer;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
-import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
-
-public class ContainerNodeCnSnSerializer extends ContainerNodeBaseSerializer<Node<?>> {
-
-    private final NodeSerializerDispatcher<Node<?>> dispatcher;
-
-    ContainerNodeCnSnSerializer(final NodeSerializerDispatcher<Node<?>> dispatcher) {
-        this.dispatcher = Preconditions.checkNotNull(dispatcher);
-    }
-
-    @Override
-    public List<Node<?>> serialize(final ContainerSchemaNode schema, final ContainerNode node) {
-        CompositeNodeBuilder<ImmutableCompositeNode> compNodeBuilder = ImmutableCompositeNode.builder();
-        compNodeBuilder.setQName(node.getNodeType());
-        compNodeBuilder.addAll(super.serialize(schema, node));
-        return Collections.<Node<?>> singletonList(compNodeBuilder.build());
-    }
-
-    @Override
-    protected NodeSerializerDispatcher<Node<?>> getNodeDispatcher() {
-        return dispatcher;
-    }
-
-}
diff --git a/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/LeafNodeCnSnSerializer.java b/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/LeafNodeCnSnSerializer.java
deleted file mode 100644 (file)
index 7a627b7..0000000
+++ /dev/null
@@ -1,22 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.LeafNodeBaseSerializer;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
-
-public class LeafNodeCnSnSerializer extends LeafNodeBaseSerializer<Node<?>> {
-
-    @Override
-    protected Node<?> serializeLeaf(LeafSchemaNode schema, LeafNode<?> node) {
-        return NodeFactory.createMutableSimpleNode(node.getNodeType(), null, node.getValue(), null, null);
-    }
-}
diff --git a/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/LeafSetEntryNodeCnSnSerializer.java b/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/LeafSetEntryNodeCnSnSerializer.java
deleted file mode 100644 (file)
index cba8e48..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.LeafSetEntryNodeBaseSerializer;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-
-public class LeafSetEntryNodeCnSnSerializer extends
-        LeafSetEntryNodeBaseSerializer<Node<?>> {
-
-    @Override
-    protected Node<?> serializeLeaf(LeafListSchemaNode schema, LeafSetEntryNode<?> node) {
-        return NodeFactory.createMutableSimpleNode(
-                               node.getNodeType(), null, node.getValue(), null, null);
-    }
-}
diff --git a/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/LeafSetNodeCnSnSerializer.java b/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/LeafSetNodeCnSnSerializer.java
deleted file mode 100644 (file)
index 6d3b22b..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializer;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.LeafSetNodeBaseSerializer;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-
-public class LeafSetNodeCnSnSerializer extends
-        LeafSetNodeBaseSerializer<Node<?>> {
-
-    private FromNormalizedNodeSerializer<Node<?>, LeafSetEntryNode<?>, LeafListSchemaNode> leafSetEntryNodeSerializer;
-
-    public LeafSetNodeCnSnSerializer(final LeafSetEntryNodeCnSnSerializer leafSetEntryNodeSerializer) {
-        this.leafSetEntryNodeSerializer = leafSetEntryNodeSerializer;
-    }
-
-    @Override
-    protected FromNormalizedNodeSerializer<Node<?>, LeafSetEntryNode<?>, LeafListSchemaNode> getLeafSetEntryNodeSerializer() {
-        return leafSetEntryNodeSerializer;
-    }
-}
diff --git a/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/MapEntryNodeCnSnSerializer.java b/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/MapEntryNodeCnSnSerializer.java
deleted file mode 100644 (file)
index 1cadd4c..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer;
-
-import com.google.common.base.Preconditions;
-import java.util.Collections;
-import java.util.List;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
-import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.MapEntryNodeBaseSerializer;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
-import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-
-public class MapEntryNodeCnSnSerializer extends MapEntryNodeBaseSerializer<Node<?>> {
-
-    private final NodeSerializerDispatcher<Node<?>> dispatcher;
-
-    MapEntryNodeCnSnSerializer(final NodeSerializerDispatcher<Node<?>> dispatcher) {
-        this.dispatcher = Preconditions.checkNotNull(dispatcher);
-    }
-
-    @Override
-    public List<Node<?>> serialize(ListSchemaNode schema, MapEntryNode node) {
-        CompositeNodeBuilder<ImmutableCompositeNode> compNodeBuilder = ImmutableCompositeNode.builder();
-        compNodeBuilder.setQName(node.getNodeType());
-        compNodeBuilder.addAll(super.serialize(schema, node));
-        return Collections.<Node<?>> singletonList(compNodeBuilder.build());
-    }
-
-    @Override
-    protected NodeSerializerDispatcher<Node<?>> getNodeDispatcher() {
-        return dispatcher;
-    }
-}
diff --git a/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/MapNodeCnSnSerializer.java b/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/cnsn/serializer/MapNodeCnSnSerializer.java
deleted file mode 100644 (file)
index f610721..0000000
+++ /dev/null
@@ -1,28 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializer;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.MapNodeBaseSerializer;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-
-public class MapNodeCnSnSerializer extends MapNodeBaseSerializer<Node<?>> {
-
-    private final FromNormalizedNodeSerializer<Node<?>, MapEntryNode, ListSchemaNode> mapEntrySerializer;
-
-    public MapNodeCnSnSerializer(final MapEntryNodeCnSnSerializer mapEntrySerializer) {
-        this.mapEntrySerializer = mapEntrySerializer;
-    }
-
-    @Override
-    protected FromNormalizedNodeSerializer<Node<?>, MapEntryNode, ListSchemaNode> getMapEntryNodeDomSerializer() {
-        return mapEntrySerializer;
-    }
-}
diff --git a/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/json/CnSnToNormalizedNodesUtils.java b/yang/yang-data-composite-node/src/main/java/org/opendaylight/yangtools/yang/data/composite/node/schema/json/CnSnToNormalizedNodesUtils.java
deleted file mode 100644 (file)
index 7a22b08..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.json;
-
-import com.google.common.collect.LinkedListMultimap;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-public final class CnSnToNormalizedNodesUtils {
-
-
-    private CnSnToNormalizedNodesUtils() {
-        throw new UnsupportedOperationException("Utility class should not be instantiated");
-    }
-
-    public static LinkedListMultimap<QName, Node<?>> mapChildElementsForSingletonNode(Node<?> node) {
-        return mapChildElements( ((CompositeNode)node).getValue());
-    }
-
-    public static LinkedListMultimap<QName, Node<?>> mapChildElements(Iterable<Node<?>> childNodesCollection) {
-        LinkedListMultimap<QName, Node<?>> mappedChildElements = LinkedListMultimap.create();
-
-        for (Node<?> node : childNodesCollection) {
-            mappedChildElements.put(node.getNodeType(), node);
-        }
-
-        return mappedChildElements;
-    }
-}
diff --git a/yang/yang-data-composite-node/src/test/java/org/opendaylight/yangtools/yang/data/composite/node/schema/TestUtils.java b/yang/yang-data-composite-node/src/test/java/org/opendaylight/yangtools/yang/data/composite/node/schema/TestUtils.java
deleted file mode 100644 (file)
index 58c28a8..0000000
+++ /dev/null
@@ -1,311 +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.yangtools.yang.data.composite.node.schema;
-
-import static org.junit.Assert.assertNotNull;
-import static org.opendaylight.yangtools.yang.data.impl.NodeFactory.createMutableSimpleNode;
-
-import java.io.File;
-import java.io.FileNotFoundException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-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.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
-import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
-import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
-import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
-import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.impl.NodeFactory;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuilder;
-import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.parser.api.YangModelParser;
-import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public class TestUtils {
-
-    private static final Logger LOG = LoggerFactory.getLogger(TestUtils.class);
-    private static final QNameModule MODULE_AUGMENT;
-    private static final QNameModule MODULE_BASE;
-
-    static {
-        final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
-
-        try {
-            MODULE_BASE = QNameModule.create(URI.create("simple:container:yang"), df.parse("2013-11-12"));
-            MODULE_AUGMENT = QNameModule.create(URI.create("augment:container:yang"), df.parse("2014-03-19"));
-        } catch (ParseException e) {
-            throw new ExceptionInInitializerError(e);
-        }
-    }
-
-    public static Set<Module> loadModules(final URI resourceURI) throws FileNotFoundException {
-        final YangModelParser parser = new YangParserImpl();
-        final File testDir = new File(resourceURI);
-        final String[] fileList = testDir.list();
-        final List<File> testFiles = new ArrayList<>();
-        if (fileList == null) {
-            throw new FileNotFoundException(resourceURI.toString());
-        }
-        for (String fileName : fileList) {
-            testFiles.add(new File(testDir, fileName));
-        }
-        return parser.parseYangModels(testFiles);
-    }
-
-    public static Set<Module> loadModulesFrom(final String yangPath) throws URISyntaxException {
-        try {
-            return loadModules(TestUtils.class.getResource(yangPath).toURI());
-        } catch (FileNotFoundException e) {
-            LOG.error("Yang files at path: " + yangPath + " weren't loaded.");
-        }
-
-        return null;
-    }
-
-    public static DataSchemaNode resolveDataSchemaNode(final String searchedDataSchemaName, final Module module) {
-        assertNotNull("Module can't be null", module);
-
-        if (searchedDataSchemaName != null) {
-            for (DataSchemaNode dsn : module.getChildNodes()) {
-                if (dsn.getQName().getLocalName().equals(searchedDataSchemaName)) {
-                    return dsn;
-                }
-            }
-        } else if (module.getChildNodes().size() == 1) {
-            return module.getChildNodes().iterator().next();
-        }
-        return null;
-    }
-
-    public static Module resolveModule(final String searchedModuleName, final Set<Module> modules) {
-        assertNotNull("Modules can't be null.", modules);
-        if (searchedModuleName != null) {
-            for (Module m : modules) {
-                if (m.getName().equals(searchedModuleName)) {
-                    return m;
-                }
-            }
-        } else if (modules.size() == 1) {
-            return modules.iterator().next();
-        }
-        return null;
-    }
-
-    /**
-     * Prepare composite node structure according to
-     * /cnsn-to-normalized-node/simple-conainer.json
-     */
-    public static CompositeNode prepareCompositeNodeStruct() {
-        CompositeNodeBuilder<ImmutableCompositeNode> contBuilder = ImmutableCompositeNode.builder();
-        contBuilder.setQName(QName.create(MODULE_BASE, "cont"));
-
-        // cont1
-        contBuilder.add(ImmutableCompositeNode.builder().setQName(QName.create(MODULE_BASE, "cont1")).build());
-
-        // cont2
-        CompositeNodeBuilder<ImmutableCompositeNode> cont2 = ImmutableCompositeNode.builder().setQName(
-                QName.create(MODULE_BASE, "cont2"));
-        cont2.add(createMutableSimpleNode(QName.create(MODULE_BASE, "lf21"), null, "value in cont2/lf21", null, null));
-        contBuilder.add(cont2.build());
-
-        // lst1
-        contBuilder.add(ImmutableCompositeNode.builder().setQName(QName.create(MODULE_BASE, "lst1")).build());
-
-        // lst2
-        CompositeNodeBuilder<ImmutableCompositeNode> lst2_1Builder = ImmutableCompositeNode.builder().setQName(
-                QName.create(MODULE_BASE, "lst2"));
-        lst2_1Builder.add(createMutableSimpleNode(QName.create(MODULE_BASE, "lf21"), null, "some value21", null, null));
-        contBuilder.add(lst2_1Builder.build());
-
-        CompositeNodeBuilder<ImmutableCompositeNode> lst2_2Builder = ImmutableCompositeNode.builder().setQName(
-                QName.create(MODULE_BASE, "lst2"));
-        lst2_2Builder.add(createMutableSimpleNode(QName.create(MODULE_BASE, "lf22"), null, "some value22", null, null));
-        contBuilder.add(lst2_2Builder.build());
-
-        // lflst1
-        contBuilder.add(createMutableSimpleNode(QName.create(MODULE_BASE, "lflst1"), null, "lflst1_1", null, null));
-        contBuilder.add(createMutableSimpleNode(QName.create(MODULE_BASE, "lflst1"), null, "lflst1_2", null, null));
-
-        // lf1
-        contBuilder.add(createMutableSimpleNode(QName.create(MODULE_BASE, "lf1"), null, "lf1", null, null));
-
-        // lf11
-        contBuilder.add(createMutableSimpleNode(QName.create(MODULE_BASE, "lf11"), null, "value from case (cs1)", null,
-                null));
-
-        // cont3
-        CompositeNodeBuilder<ImmutableCompositeNode> cont3Builder = ImmutableCompositeNode.builder().setQName(
-                QName.create(MODULE_AUGMENT, "cont3"));
-        cont3Builder.add(createMutableSimpleNode(QName.create(MODULE_AUGMENT, "lf31"), null,
-                "value in leaf in augment", null, null));
-        contBuilder.add(cont3Builder.build());
-
-        // anxml-composite
-        CompositeNodeBuilder<ImmutableCompositeNode> anxmlCompositeBuilder = ImmutableCompositeNode.builder().setQName(
-                QName.create(MODULE_BASE, "anxml-composite"));
-        anxmlCompositeBuilder.add(NodeFactory.createImmutableSimpleNode(QName.create(MODULE_BASE, "anxml-cont"), null,
-                null));
-        contBuilder.add(anxmlCompositeBuilder.build());
-
-        // anxml-simple
-        contBuilder.add(NodeFactory.createImmutableSimpleNode(QName.create(MODULE_BASE, "anxml-simple"), null,43));
-
-        return contBuilder.build();
-    }
-
-    /**
-     * Prepare composite node structure according to
-     * /cnsn-to-normalized-node/simple-conainer.json
-     */
-    public static ContainerNode prepareNormalizedNodeStruct() throws URISyntaxException {
-        DataContainerNodeBuilder<NodeIdentifier, ContainerNode> containerBuilder = Builders.containerBuilder();
-        containerBuilder.withNodeIdentifier(getNodeIdentifier("cont"));
-        containerBuilder.withChild(Builders.containerBuilder().withNodeIdentifier(getNodeIdentifier("cont1")).build());
-        containerBuilder.withChild(Builders
-                .containerBuilder()
-                .withNodeIdentifier(getNodeIdentifier("cont2"))
-                .withChild(
-                        Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("lf21"))
-                                .withValue("value in cont2/lf21").build()).build());
-
-        CollectionNodeBuilder<MapEntryNode, MapNode> lst1 = Builders.mapBuilder().withNodeIdentifier(
-                getNodeIdentifier("lst1"));
-        lst1.withChild(Builders.mapEntryBuilder()
-                .withNodeIdentifier(getNodeIdentifierPredicate("lst1", new HashMap<String, Object>()))
-                .withValue(Collections.<DataContainerChild<? extends PathArgument, ?>> emptyList()).build());
-        containerBuilder.withChild(lst1.build());
-
-        CollectionNodeBuilder<MapEntryNode, MapNode> lst2 = Builders.mapBuilder().withNodeIdentifier(
-                getNodeIdentifier("lst2"));
-
-        Map<String, Object> lst2_1 = new HashMap<>();
-        lst2_1.put("lf21", "some value21");
-
-        List<DataContainerChild<? extends PathArgument, ?>> lst2_1_values = new ArrayList<>();
-        lst2_1_values.add(Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("lf21"))
-                .withValue("some value21").build());
-        lst2.withChild(Builders.mapEntryBuilder().withNodeIdentifier(getNodeIdentifierPredicate("lst2", lst2_1))
-                .withValue(lst2_1_values).build());
-
-        Map<String, Object> lst2_2 = new HashMap<>();
-        lst2_2.put("lf22", "some value22");
-        List<DataContainerChild<? extends PathArgument, ?>> lst2_2_values = new ArrayList<>();
-        lst2_2_values.add(Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("lf22"))
-                .withValue("some value22").build());
-        lst2.withChild(Builders.mapEntryBuilder().withNodeIdentifier(getNodeIdentifierPredicate("lst2", lst2_2))
-                .withValue(lst2_2_values).build());
-        containerBuilder.withChild(lst2.build());
-
-        ListNodeBuilder<Object, LeafSetEntryNode<Object>> lflst1 = Builders.leafSetBuilder().withNodeIdentifier(
-                getNodeIdentifier("lflst1"));
-        lflst1.withChild(Builders.leafSetEntryBuilder().withNodeIdentifier(getNodeIdentifier("lflst1", "lflst1_1"))
-                .withValue("lflst1_1").build());
-        lflst1.withChild(Builders.leafSetEntryBuilder().withNodeIdentifier(getNodeIdentifier("lflst1", "lflst1_2"))
-                .withValue("lflst1_2").build());
-        containerBuilder.withChild(lflst1.build());
-
-        containerBuilder.withChild(Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("lf1")).withValue("lf1")
-                .build());
-
-        containerBuilder.withChild(Builders
-                .choiceBuilder()
-                .withNodeIdentifier(getNodeIdentifier("chc"))
-                .withChild(
-                        Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("lf11"))
-                                .withValue("value from case (cs1)").build()).build());
-
-        Set<QName> children = new HashSet<>();
-        children.add(QName.create(MODULE_AUGMENT, "cont3"));
-
-        containerBuilder.withChild(Builders
-                .augmentationBuilder()
-                .withNodeIdentifier(getAugmentationIdentifier(null, null, null, children))
-                .withChild(
-                        Builders.containerBuilder()
-                                .withNodeIdentifier(getNodeIdentifier(MODULE_AUGMENT, "cont3"))
-                                .withChild(
-                                        Builders.leafBuilder()
-                                                .withNodeIdentifier(getNodeIdentifier(MODULE_AUGMENT, "lf31"))
-                                                .withValue("value in leaf in augment").build()).build()).build());
-
-        containerBuilder.withChild(Builders
-                .anyXmlBuilder()
-                .withNodeIdentifier(getNodeIdentifier("anxml-composite"))
-                .withValue(
-                        ImmutableCompositeNode
-                                .builder()
-                                .setQName(QName.create("simple:container:yang", "2013-11-12", "anxml-composite"))
-                                .add(NodeFactory.createImmutableSimpleNode(
-                                        QName.create("simple:container:yang", "2013-11-12", "anxml-cont"), null, null))
-                                .build()).build());
-
-        containerBuilder
-                .withChild(Builders
-                        .anyXmlBuilder()
-                        .withNodeIdentifier(getNodeIdentifier("anxml-simple"))
-                        .withValue(
-                                NodeFactory.createImmutableSimpleNode(
-                                        QName.create("simple:container:yang", "2013-11-12", "anxml-simple"), null, 43))
-                        .build());
-
-        ContainerNode build = containerBuilder.build();
-        return build;
-    }
-
-    private static YangInstanceIdentifier.NodeIdentifier getNodeIdentifier(final String localName) {
-        return getNodeIdentifier(MODULE_BASE, localName);
-    }
-
-    private static YangInstanceIdentifier.NodeIdentifier getNodeIdentifier(final QNameModule module, final String localName) {
-        return new YangInstanceIdentifier.NodeIdentifier(QName.create(module, localName));
-    }
-
-    private static YangInstanceIdentifier.NodeWithValue getNodeIdentifier(final String localName, final Object value) {
-        return new YangInstanceIdentifier.NodeWithValue(QName.create(MODULE_BASE, localName),
-                value);
-    }
-
-    private static YangInstanceIdentifier.NodeIdentifierWithPredicates getNodeIdentifierPredicate(final String localName,
-            final Map<String, Object> keys) {
-        Map<QName, Object> predicate = new HashMap<>();
-        for (String key : keys.keySet()) {
-            predicate.put(QName.create(MODULE_BASE, key), keys.get(key));
-        }
-
-        return new YangInstanceIdentifier.NodeIdentifierWithPredicates(QName.create(MODULE_BASE, localName), predicate);
-    }
-
-    private static YangInstanceIdentifier.AugmentationIdentifier getAugmentationIdentifier(final String localName,
-            final String namespace, final Date revision, final Set<QName> children) {
-        return new YangInstanceIdentifier.AugmentationIdentifier(children);
-    }
-
-}
diff --git a/yang/yang-data-composite-node/src/test/java/org/opendaylight/yangtools/yang/data/composite/node/schema/parser/Bug2180Test.java b/yang/yang-data-composite-node/src/test/java/org/opendaylight/yangtools/yang/data/composite/node/schema/parser/Bug2180Test.java
deleted file mode 100644 (file)
index c3f48bd..0000000
+++ /dev/null
@@ -1,77 +0,0 @@
-package org.opendaylight.yangtools.yang.data.composite.node.schema.parser;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
-import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
-import org.opendaylight.yangtools.yang.data.api.schema.OrderedLeafSetNode;
-import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
-import org.opendaylight.yangtools.yang.data.composite.node.schema.TestUtils;
-import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser.CnSnToNormalizedNodeParserFactory;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParser;
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
-
-import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.Set;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-public class Bug2180Test {
-    private Module simpleContainerModule;
-    private Module bug2111TestModule;
-
-    @Before
-    public void init() throws URISyntaxException {
-        Set<Module> modules = TestUtils.loadModulesFrom("/cnsn-to-normalized-node/yang");
-        simpleContainerModule = TestUtils.resolveModule("simple-container-yang", modules);
-        bug2111TestModule = TestUtils.resolveModule("bug2180-test-module", modules);
-    }
-
-    @Test
-    public void orderedListParseTest() throws DataValidationFailedException, URISyntaxException {
-        ContainerSchemaNode topContainerSchemaNode = (ContainerSchemaNode) TestUtils.resolveDataSchemaNode("top", bug2111TestModule);
-        ListSchemaNode aceListSchemaNode = (ListSchemaNode) topContainerSchemaNode.getDataChildByName("ordered-list");
-        ToNormalizedNodeParser<Node<?>, MapNode, ListSchemaNode> mapNodeParser =
-                CnSnToNormalizedNodeParserFactory.getInstance().getMapNodeParser();
-        MapNode mapNode = mapNodeParser.parse(new ArrayList<Node<?>>(), aceListSchemaNode);
-        assertTrue(mapNode instanceof OrderedMapNode);
-    }
-
-    @Test
-    public void unorderedListParseTest() throws DataValidationFailedException, URISyntaxException {
-        ContainerSchemaNode topContainerSchemaNode = (ContainerSchemaNode) TestUtils.resolveDataSchemaNode("cont", simpleContainerModule);
-        ListSchemaNode aceListSchemaNode = (ListSchemaNode) topContainerSchemaNode.getDataChildByName("lst2");
-        ToNormalizedNodeParser<Node<?>, MapNode, ListSchemaNode> mapNodeParser =
-                CnSnToNormalizedNodeParserFactory.getInstance().getMapNodeParser();
-        MapNode mapNode = mapNodeParser.parse(new ArrayList<Node<?>>(), aceListSchemaNode);
-        assertFalse(mapNode instanceof OrderedMapNode);
-    }
-
-    @Test
-    public void orderedLeafListParseTest() throws DataValidationFailedException, URISyntaxException {
-        ContainerSchemaNode topContainerSchemaNode = (ContainerSchemaNode) TestUtils.resolveDataSchemaNode("top", bug2111TestModule);
-        LeafListSchemaNode aceListSchemaNode = (LeafListSchemaNode) topContainerSchemaNode.getDataChildByName("ordered-leaf-list");
-        ToNormalizedNodeParser<Node<?>, LeafSetNode<?>, LeafListSchemaNode> leafSetNodeParser =
-                CnSnToNormalizedNodeParserFactory.getInstance().getLeafSetNodeParser();
-        LeafSetNode<?> leafSetNode = leafSetNodeParser.parse(new ArrayList<Node<?>>(), aceListSchemaNode);
-        assertTrue(leafSetNode instanceof OrderedLeafSetNode);
-    }
-
-    @Test
-    public void unorderedLeafListParseTest() throws DataValidationFailedException, URISyntaxException {
-        ContainerSchemaNode topContainerSchemaNode = (ContainerSchemaNode) TestUtils.resolveDataSchemaNode("cont", simpleContainerModule);
-        LeafListSchemaNode aceListSchemaNode = (LeafListSchemaNode) topContainerSchemaNode.getDataChildByName("lflst1");
-        ToNormalizedNodeParser<Node<?>, LeafSetNode<?>, LeafListSchemaNode> leafSetNodeParser =
-                CnSnToNormalizedNodeParserFactory.getInstance().getLeafSetNodeParser();
-        LeafSetNode<?> leafSetNode = leafSetNodeParser.parse(new ArrayList<Node<?>>(), aceListSchemaNode);
-        assertFalse(leafSetNode instanceof OrderedLeafSetNode);
-    }
-
-}
diff --git a/yang/yang-data-composite-node/src/test/java/org/opendaylight/yangtools/yang/data/composite/node/schema/parser/ParseCnSnStructToNormalizedStructTest.java b/yang/yang-data-composite-node/src/test/java/org/opendaylight/yangtools/yang/data/composite/node/schema/parser/ParseCnSnStructToNormalizedStructTest.java
deleted file mode 100644 (file)
index 56fd812..0000000
+++ /dev/null
@@ -1,56 +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.yangtools.yang.data.composite.node.schema.parser;
-
-import static org.junit.Assert.assertEquals;
-
-import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser.CnSnToNormalizedNodeParserFactory;
-
-
-import org.opendaylight.yangtools.yang.data.composite.node.schema.TestUtils;
-
-import java.net.URISyntaxException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
-
-public class ParseCnSnStructToNormalizedStructTest {
-
-    private static DataSchemaNode resolvedDataSchemaNode;
-
-    @BeforeClass
-    public static void loadData() throws URISyntaxException {
-        Set<Module> modules = TestUtils.loadModulesFrom("/cnsn-to-normalized-node/yang");
-        Module resolvedModule = TestUtils.resolveModule("simple-container-yang", modules);
-        resolvedDataSchemaNode = TestUtils.resolveDataSchemaNode("cont", resolvedModule);
-    }
-
-    @Test
-    public void testCnSnToNormalizedNode() throws URISyntaxException {
-
-        CompositeNode compNode = TestUtils.prepareCompositeNodeStruct();
-
-        List<Node<?>> lst = new ArrayList<Node<?>>();
-        lst.add(compNode);
-        ContainerNode parsed = CnSnToNormalizedNodeParserFactory.getInstance().getContainerNodeParser()
-                .parse(lst, (ContainerSchemaNode) resolvedDataSchemaNode);
-
-        ContainerNode prepareExpectedStruct = TestUtils.prepareNormalizedNodeStruct();
-        assertEquals(prepareExpectedStruct, parsed);
-    }
-
-}
diff --git a/yang/yang-data-composite-node/src/test/java/org/opendaylight/yangtools/yang/data/composite/node/schema/serializer/SerializeNormalizedStructToCnSnStructTest.java b/yang/yang-data-composite-node/src/test/java/org/opendaylight/yangtools/yang/data/composite/node/schema/serializer/SerializeNormalizedStructToCnSnStructTest.java
deleted file mode 100644 (file)
index 95b0ec8..0000000
+++ /dev/null
@@ -1,60 +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.yangtools.yang.data.composite.node.schema.serializer;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-
-import org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.serializer.CnSnFromNormalizedNodeSerializerFactory;
-
-
-import org.opendaylight.yangtools.yang.data.composite.node.schema.TestUtils;
-
-import java.net.URISyntaxException;
-import java.util.Set;
-
-import com.google.common.collect.Sets;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.Module;
-
-public class SerializeNormalizedStructToCnSnStructTest {
-
-    private static DataSchemaNode resolvedDataSchemaNode;
-
-    @BeforeClass
-    public static void loadData() throws URISyntaxException {
-        Set<Module> modules = TestUtils.loadModulesFrom("/cnsn-to-normalized-node/yang");
-        Module resolvedModule = TestUtils.resolveModule("simple-container-yang", modules);
-        resolvedDataSchemaNode = TestUtils.resolveDataSchemaNode("cont", resolvedModule);
-    }
-
-    @Test
-    public void testCnSnToNormalizedNode() throws URISyntaxException {
-        ContainerNode containerNode = TestUtils.prepareNormalizedNodeStruct();
-
-        Iterable<Node<?>> serialized = CnSnFromNormalizedNodeSerializerFactory.getInstance()
-                .getContainerNodeSerializer().serialize((ContainerSchemaNode) resolvedDataSchemaNode, containerNode);
-
-        assertNotNull(serialized);
-        assertNotNull(serialized.iterator());
-        assertNotNull(serialized.iterator().hasNext());
-
-        CompositeNode compNode = TestUtils.prepareCompositeNodeStruct();
-
-        assertEquals(serialized.iterator().next().getNodeType(), compNode.getNodeType());
-
-        Set<Node<?>> value = Sets.newHashSet(((CompositeNode)serialized.iterator().next()).getValue());
-        assertEquals(value, Sets.newHashSet(compNode.getValue()));
-    }
-}
diff --git a/yang/yang-data-composite-node/src/test/resources/cnsn-to-normalized-node/json/simple-container.json b/yang/yang-data-composite-node/src/test/resources/cnsn-to-normalized-node/json/simple-container.json
deleted file mode 100644 (file)
index 37dd7c0..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-{
-    "simple-container-yang:cont":{
-        "cont1":{
-        },
-        "cont2":{
-            "lf21":"value in cont2/lf21"
-        },
-        "augment-container-yang:cont3":{
-            "lf31":"value in leaf in augment"
-        },
-        "lst1": [
-            {
-            }
-        ],
-        "lst2": [
-          {
-              "lf21":"some value21"
-          },
-          {
-              "lf22":"some value22"
-          }
-        ],      
-        "lflst1":[
-            "lflst1_1",
-            "lflst1_2"
-        ],
-        "lf1":"lf1",
-        
-        "lf11":"value from case (cs1)"
-        "anxml-composite": {            
-            "anxml-cont" {
-            }
-        }
-        
-        "anxml-simple":43;
-    }
-}
\ No newline at end of file
diff --git a/yang/yang-data-composite-node/src/test/resources/cnsn-to-normalized-node/yang/augment-simple-container.yang b/yang/yang-data-composite-node/src/test/resources/cnsn-to-normalized-node/yang/augment-simple-container.yang
deleted file mode 100644 (file)
index 9f24f13..0000000
+++ /dev/null
@@ -1,18 +0,0 @@
-module augment-container-yang {
-  namespace "augment:container:yang";  
-
-  prefix "auconyang";
-  import simple-container-yang { prefix "simple"; revision-date 2013-11-12; }
-  
-  revision 2014-03-19 {    
-  }
-
-  augment "/simple:cont" {
-    container cont3 {
-        leaf lf31 {
-            type string;
-        }
-    }
-  }
-   
-}
diff --git a/yang/yang-data-composite-node/src/test/resources/cnsn-to-normalized-node/yang/bug2180-test-model.yang b/yang/yang-data-composite-node/src/test/resources/cnsn-to-normalized-node/yang/bug2180-test-model.yang
deleted file mode 100644 (file)
index c8c699d..0000000
+++ /dev/null
@@ -1,26 +0,0 @@
-module bug2180-test-module {
-  yang-version 1;
-
-  namespace "urn:opendaylight:params:xml:ns:yang:controller:md:sal:bug2180:test";
-
-  prefix bug2180-test-module;
-
-  revision 2014-10-22 {
-    description "creating base model for netmod";
-  }
-
-  container top {
-    list ordered-list {
-      key id;
-      ordered-by user;
-      leaf id{
-        type string;
-      }
-    }
-
-    leaf-list ordered-leaf-list {
-      type string;
-      ordered-by user;      
-    }
-  }
-}
\ No newline at end of file
diff --git a/yang/yang-data-composite-node/src/test/resources/cnsn-to-normalized-node/yang/simple-container.yang b/yang/yang-data-composite-node/src/test/resources/cnsn-to-normalized-node/yang/simple-container.yang
deleted file mode 100644 (file)
index b96b548..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-module simple-container-yang {
-  namespace "simple:container:yang";  
-
-  prefix "smpdtp";
-  revision 2013-11-12 {    
-  }
-  
-  container cont {
-       container cont1 {
-       }
-       container cont2 {
-            leaf lf21 {
-                type string;
-            } 
-       }
-       list lst1 {
-       }
-       list lst2 {
-            leaf lf21 {
-                type string;
-            }
-            leaf lf22 {
-                type string;
-            }
-       }
-       leaf-list lflst1 {
-               type string;
-       }
-       leaf lf1 {
-               type string;
-       }
-       
-    choice chc {
-      case cs1 {
-          leaf lf11 {
-              type string;
-          }
-      }
-      case cs2 {
-          leaf lf21 {
-              type string;
-          }
-      }
-    }
-    
-    anyxml anxml-composite;
-    anyxml anxml-simple;
-  }
-}
index 4ae9186ca42e614a63d5c569d4be34b15edc6470..0953073f529a66582b9b9537aa560d0f1d92572b 100644 (file)
         <dependency>
             <groupId>commons-lang</groupId>
             <artifactId>commons-lang</artifactId>
+            <scope>test</scope>
         </dependency>
         <dependency>
             <groupId>com.google.code.findbugs</groupId>
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/AbstractNodeTO.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/AbstractNodeTO.java
deleted file mode 100644 (file)
index 307bf12..0000000
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.NodeModification;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
-
-/**
- * @author michal.rehak
- * @param <T>
- *            type of node value
- * @deprecated Use one of the {@link NormalizedNodeBuilder} implementations.
- */
-@Deprecated
-public abstract class AbstractNodeTO<T> implements Node<T>, NodeModification {
-
-    private QName qName;
-    private CompositeNode parent;
-    private T value;
-    private ModifyAction modifyAction;
-
-    // Only for Serialization use
-    public AbstractNodeTO(){
-
-    }
-
-    /**
-     * @param qname
-     * @param parent
-     * @param value
-     */
-    public AbstractNodeTO(final QName qname, final CompositeNode parent, final T value) {
-        this(qname, parent, value, null);
-    }
-
-    /**
-     * @param qname
-     * @param parent
-     * @param value
-     * @param modifyAction
-     */
-    public AbstractNodeTO(final QName qname, final CompositeNode parent, final T value, final ModifyAction modifyAction) {
-        this.qName = qname;
-        this.parent = parent;
-        this.value = value;
-        this.modifyAction = modifyAction;
-    }
-
-    @Override
-    public QName getNodeType() {
-        return qName;
-    }
-
-    /**
-     * @return the qName
-     */
-    public QName getQName() {
-        return qName;
-    }
-
-    @Override
-    public CompositeNode getParent() {
-        return parent;
-    }
-
-    /**
-     * @param parent
-     *            the parent to set
-     */
-    public void setParent(final CompositeNode parent) {
-        this.parent = parent;
-    }
-
-    /**
-     * @param value
-     *            the value to set
-     */
-    @Override
-    public T setValue(final T value) {
-        T oldValue = this.value;
-        this.value = value;
-        return oldValue;
-    }
-
-    @Override
-    public T getValue() {
-        return value;
-    }
-
-    /**
-     * @return modification action
-     * @see NodeModification#getModificationAction()
-     */
-    @Override
-    public ModifyAction getModificationAction() {
-        return modifyAction;
-    }
-
-    /**
-     * @param modifyAction
-     *            the modifyAction to set
-     */
-    protected void setModificationAction(final ModifyAction modifyAction) {
-        this.modifyAction = modifyAction;
-    }
-
-    @Override
-    public String toString() {
-        StringBuffer out = new StringBuffer();
-        out.append(String.format("Node[%s], qName[%s], modify[%s]", getClass().getSimpleName(), getQName()
-                .getLocalName(), getModificationAction() == null ? "n/a" : getModificationAction()));
-        return out.toString();
-    }
-
-
-    @Override
-    public final QName getKey() {
-        return getNodeType();
-    }
-
-    /* */
-    @Override
-    public int hashCode() {
-        final int prime = 31;
-        int result = 1;
-        result = prime * result + ((qName == null) ? 0 : qName.hashCode());
-        result = prime * result + ((value == null) ? 0 : value.hashCode());
-        return result % 2;
-    }
-
-    @Override
-    public boolean equals(final Object obj) {
-        if (this == obj) {
-            return true;
-        }
-        if (obj == null) {
-            return false;
-        }
-        if (getClass() != obj.getClass()) {
-            return false;
-        }
-        @SuppressWarnings("unchecked")
-        AbstractNodeTO<T> other = (AbstractNodeTO<T>) obj;
-        if (parent == null) {
-            if (other.parent != null) {
-                return false;
-            }
-        } else if (other.parent == null) {
-            return false;
-        }
-        if (qName == null) {
-            if (other.qName != null) {
-                return false;
-            }
-        } else if (!qName.equals(other.qName)) {
-            return false;
-        }
-        if (value == null) {
-            if (other.value != null) {
-                return false;
-            }
-        } else if (!value.equals(other.value)) {
-            return false;
-        }
-        return true;
-    }
-    /* */
-
-
-    //Serialization related
-
-    protected final void init(final QName qName, final CompositeNode parent, final T value, final ModifyAction modifyAction){
-        this.qName = qName;
-        this.modifyAction = modifyAction;
-        this.parent = parent;
-        this.value = value;
-    }
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/CompositeNodeModificationTOImpl.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/CompositeNodeModificationTOImpl.java
deleted file mode 100644 (file)
index 5026db5..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import java.util.List;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-/**
- * @author michal.rehak
- *
- * @deprecated Use one of the {@link NormalizedNode} implementations.
- */
-@Deprecated
-public class CompositeNodeModificationTOImpl extends CompositeNodeTOImpl {
-    private static final long serialVersionUID = 1L;
-
-    /**
-     * @param qname
-     * @param parent
-     * @param value
-     * @param modifyAction
-     */
-    public CompositeNodeModificationTOImpl(final QName qname, final CompositeNode parent,
-            final List<Node<?>> value, final ModifyAction modifyAction) {
-        super(qname, parent, value);
-        super.setModificationAction(modifyAction);
-    }
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/CompositeNodeTOImpl.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/CompositeNodeTOImpl.java
deleted file mode 100644 (file)
index 3e59659..0000000
+++ /dev/null
@@ -1,242 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import 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;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
-
-/**
- * @author michal.rehak
- *
- * @deprecated Use one of the {@link NormalizedNodeContainer} implementations.
- */
-@Deprecated
-public class CompositeNodeTOImpl extends AbstractNodeTO<List<Node<?>>> implements CompositeNode, Serializable {
-
-    private static final long serialVersionUID = 100L;
-
-    private Map<QName, List<Node<?>>> nodeMap = new HashMap<>();
-
-    /**
-     * @param qname
-     * @param parent
-     *            use null to create top composite node (without parent)
-     * @param value
-     */
-    public CompositeNodeTOImpl(final QName qname, final CompositeNode parent, final List<Node<?>> value) {
-        super(qname, parent, value);
-        init();
-    }
-
-    /**
-     * @param qname
-     * @param parent
-     *            use null to create top composite node (without parent)
-     * @param value
-     * @param modifyAction
-     */
-    public CompositeNodeTOImpl(final QName qname, final CompositeNode parent, final List<Node<?>> value, final ModifyAction modifyAction) {
-        super(qname, parent, value, modifyAction);
-        init();
-    }
-
-    protected void init() {
-        if (getValue() != null) {
-            nodeMap = NodeUtils.buildNodeMap(getValue());
-        }
-    }
-
-    protected Map<QName, List<Node<?>>> getNodeMap() {
-        return nodeMap;
-    }
-
-    @Override
-    public List<Node<?>> getChildren() {
-        return Collections.unmodifiableList(getValue() == null ? new ArrayList<Node<?>>() : getValue());
-    }
-
-    @Override
-    public SimpleNode<?> getFirstSimpleByName(final QName leafQName) {
-        List<SimpleNode<?>> list = getSimpleNodesByName(leafQName);
-        if (list.isEmpty()) {
-            return null;
-        }
-        return list.get(0);
-    }
-
-    @Override
-    public List<CompositeNode> getCompositesByName(final QName children) {
-        List<Node<?>> toFilter = getNodeMap().get(children);
-        if(toFilter == null) {
-            return Collections.emptyList();
-        }
-        List<CompositeNode> list = new ArrayList<CompositeNode>();
-        for (Node<?> node : toFilter) {
-            if (node instanceof CompositeNode) {
-                list.add((CompositeNode) node);
-            }
-        }
-        return list;
-    }
-
-    @Override
-    public List<SimpleNode<?>> getSimpleNodesByName(final QName children) {
-        List<Node<?>> toFilter = getNodeMap().get(children);
-        if(toFilter == null) {
-            return Collections.emptyList();
-        }
-        List<SimpleNode<?>> list = new ArrayList<SimpleNode<?>>();
-
-        for (Node<?> node : toFilter) {
-            if (node instanceof SimpleNode<?>) {
-                list.add((SimpleNode<?>) node);
-            }
-        }
-        return list;
-    }
-
-    @Override
-    public CompositeNode getFirstCompositeByName(final QName container) {
-        List<CompositeNode> list = getCompositesByName(container);
-        if (list.isEmpty()) {
-            return null;
-        }
-        return list.get(0);
-    }
-
-    /**
-     * @param leaf
-     * @return TODO:: do we need this method?
-     */
-    public SimpleNode<?> getFirstLeafByName(final QName leaf) {
-        List<SimpleNode<?>> list = getSimpleNodesByName(leaf);
-        if (list.isEmpty()) {
-            return null;
-        }
-        return list.get(0);
-    }
-
-    @Override
-    public List<CompositeNode> getCompositesByName(final String children) {
-        return getCompositesByName(QName.create(getNodeType(), children));
-    }
-
-    @Override
-    public List<SimpleNode<?>> getSimpleNodesByName(final String children) {
-        return getSimpleNodesByName(QName.create(getNodeType(), children));
-    }
-
-    @Override
-    public MutableCompositeNode asMutable() {
-        throw new IllegalAccessError("cast to mutable is not supported - " + getClass().getSimpleName());
-    }
-
-    @Override
-    public String toString() {
-        return super.toString() + ", children.size = " + (!getChildren().isEmpty() ? getChildren().size() : "n/a");
-    }
-
-    @Override
-    public void clear() {
-        nodeMap.clear();
-    }
-
-    @Override
-    public boolean containsKey(final Object key) {
-        return nodeMap.containsKey(key);
-    }
-
-    @Override
-    public boolean containsValue(final Object value) {
-        return nodeMap.containsValue(value);
-    }
-
-    @Override
-    public Set<java.util.Map.Entry<QName, List<Node<?>>>> entrySet() {
-        return nodeMap.entrySet();
-    }
-
-    @Override
-    public int size() {
-        return nodeMap.size();
-    }
-
-    @Override
-    public boolean isEmpty() {
-        return nodeMap.isEmpty();
-    }
-
-    @Override
-    public List<Node<?>> get(final Object key) {
-        return nodeMap.get(key);
-    }
-
-    @Override
-    public List<Node<?>> put(final QName key, final List<Node<?>> value) {
-        return nodeMap.put(key, value);
-    }
-
-    @Override
-    public List<Node<?>> remove(final Object key) {
-        return nodeMap.remove(key);
-    }
-
-    @Override
-    public void putAll(final Map<? extends QName, ? extends List<Node<?>>> m) {
-        nodeMap.putAll(m);
-    }
-
-    @Override
-    public Set<QName> keySet() {
-        return nodeMap.keySet();
-    }
-
-    @Override
-    public Collection<List<Node<?>>> values() {
-        return nodeMap.values();
-    }
-
-    // Serialization related
-
-    private void readObject(final ObjectInputStream aStream) throws IOException, ClassNotFoundException {
-        aStream.defaultReadObject();
-        QName qName = (QName)aStream.readObject();
-        CompositeNode parent = (CompositeNode) aStream.readObject();
-        @SuppressWarnings("unchecked")
-        List<Node<?>> value = (List<Node<?>>) aStream.readObject();
-        ModifyAction modifyAction = (ModifyAction) aStream.readObject();
-
-        init(qName, parent, value, modifyAction);
-    }
-
-    private void writeObject(final ObjectOutputStream aStream) throws IOException {
-        aStream.defaultWriteObject();
-        //manually serialize superclass
-        aStream.writeObject(getQName());
-        aStream.writeObject(getParent());
-        aStream.writeObject(getValue());
-        aStream.writeObject(getModificationAction());
-    }
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/ImmutableCompositeNode.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/ImmutableCompositeNode.java
deleted file mode 100644 (file)
index d104fe3..0000000
+++ /dev/null
@@ -1,301 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-import org.opendaylight.yangtools.concepts.Immutable;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
-import org.opendaylight.yangtools.yang.data.impl.util.AbstractCompositeNodeBuilder;
-import org.opendaylight.yangtools.yang.data.impl.util.CompositeNodeBuilder;
-
-/**
- * @deprecated Use one of the {@link NormalizedNodeContainer} implementations.
- */
-@Deprecated
-public final class ImmutableCompositeNode extends AbstractNodeTO<List<Node<?>>> implements Immutable, CompositeNode, AttributesContainer, Serializable {
-
-    private static final long serialVersionUID = 100L;
-
-    private Map<QName, List<Node<?>>> nodeMap = new HashMap<>();
-
-    private final Map<QName, String> attributes;
-
-
-
-    /**
-     * @param qname
-     * @param parent
-     *            use null to create top composite node (without parent)
-     * @param value
-     */
-    private ImmutableCompositeNode(final QName qname, final Map<QName,String> attributes,final List<Node<?>> value) {
-        super(qname, null, ImmutableList.copyOf(value));
-        if(attributes == null) {
-            this.attributes = ImmutableMap.<QName, String>of();
-        } else {
-            this.attributes = ImmutableMap.copyOf(attributes);
-        }
-        init();
-    }
-
-    /**
-     * @param qname
-     * @param value
-     * @param modifyAction
-     */
-    public ImmutableCompositeNode(final QName qname, final List<Node<?>> value, final ModifyAction modifyAction) {
-        super(qname, null, value, modifyAction);
-        attributes = ImmutableMap.of();
-        init();
-    }
-
-    protected void init() {
-        if (getValue() != null) {
-            nodeMap = NodeUtils.buildNodeMap(getValue());
-        }
-    }
-
-    protected Map<QName, List<Node<?>>> getNodeMap() {
-        return nodeMap;
-    }
-
-    @Override
-    public List<Node<?>> getChildren() {
-        return Collections.unmodifiableList(getValue() == null ? new ArrayList<Node<?>>() : getValue());
-    }
-
-    @Override
-    public SimpleNode<?> getFirstSimpleByName(final QName leafQName) {
-        List<SimpleNode<?>> list = getSimpleNodesByName(leafQName);
-        if (list.isEmpty()) {
-            return null;
-        }
-        return list.get(0);
-    }
-
-    @Override
-    public List<CompositeNode> getCompositesByName(final QName children) {
-        List<Node<?>> toFilter = getNodeMap().get(children);
-        if (toFilter == null) {
-            return Collections.emptyList();
-        }
-        List<CompositeNode> list = new ArrayList<CompositeNode>();
-        for (Node<?> node : toFilter) {
-            if (node instanceof CompositeNode) {
-                list.add((CompositeNode) node);
-            }
-        }
-        return list;
-    }
-
-    @Override
-    public List<SimpleNode<?>> getSimpleNodesByName(final QName children) {
-        List<Node<?>> toFilter = getNodeMap().get(children);
-        if (toFilter == null) {
-            return Collections.emptyList();
-        }
-        List<SimpleNode<?>> list = new ArrayList<SimpleNode<?>>();
-
-        for (Node<?> node : toFilter) {
-            if (node instanceof SimpleNode<?>) {
-                list.add((SimpleNode<?>) node);
-            }
-        }
-        return list;
-    }
-
-    @Override
-    public CompositeNode getFirstCompositeByName(final QName container) {
-        List<CompositeNode> list = getCompositesByName(container);
-        if (list.isEmpty()) {
-            return null;
-        }
-        return list.get(0);
-    }
-
-    @Override
-    public Map<QName, String> getAttributes() {
-        return attributes;
-    }
-
-    @Override
-    public String getAttributeValue(final QName key) {
-        return attributes.get(key);
-    }
-
-    /**
-     * @param leaf
-     * @return TODO:: do we need this method?
-     */
-    public SimpleNode<?> getFirstLeafByName(final QName leaf) {
-        List<SimpleNode<?>> list = getSimpleNodesByName(leaf);
-        if (list.isEmpty()) {
-            return null;
-        }
-        return list.get(0);
-    }
-
-    @Override
-    public List<CompositeNode> getCompositesByName(final String children) {
-        return getCompositesByName(QName.create(getNodeType(), children));
-    }
-
-    @Override
-    public List<SimpleNode<?>> getSimpleNodesByName(final String children) {
-        return getSimpleNodesByName(QName.create(getNodeType(), children));
-    }
-
-    @Override
-    public MutableCompositeNode asMutable() {
-        throw new IllegalAccessError("cast to mutable is not supported - " + getClass().getSimpleName());
-    }
-
-    @Override
-    public String toString() {
-        return super.toString() + ", children.size = " + (!getChildren().isEmpty() ? getChildren().size() : "n/a");
-    }
-
-    @Override
-    public void clear() {
-        nodeMap.clear();
-    }
-
-    @Override
-    public boolean containsKey(final Object key) {
-        return nodeMap.containsKey(key);
-    }
-
-    @Override
-    public boolean containsValue(final Object value) {
-        return nodeMap.containsValue(value);
-    }
-
-    @Override
-    public Set<java.util.Map.Entry<QName, List<Node<?>>>> entrySet() {
-        return nodeMap.entrySet();
-    }
-
-    @Override
-    public int size() {
-        return nodeMap.size();
-    }
-
-    @Override
-    public boolean isEmpty() {
-        return nodeMap.isEmpty();
-    }
-
-    @Override
-    public List<Node<?>> get(final Object key) {
-        return nodeMap.get(key);
-    }
-
-    @Override
-    public List<Node<?>> put(final QName key, final List<Node<?>> value) {
-        return nodeMap.put(key, value);
-    }
-
-    @Override
-    public List<Node<?>> remove(final Object key) {
-        return nodeMap.remove(key);
-    }
-
-    @Override
-    public void putAll(final Map<? extends QName, ? extends List<Node<?>>> m) {
-        nodeMap.putAll(m);
-    }
-
-    @Override
-    public Set<QName> keySet() {
-        return nodeMap.keySet();
-    }
-
-    @Override
-    public Collection<List<Node<?>>> values() {
-        return nodeMap.values();
-    }
-
-    // Serialization related
-
-    private void readObject(final ObjectInputStream aStream) throws IOException, ClassNotFoundException {
-        aStream.defaultReadObject();
-        QName qName = (QName) aStream.readObject();
-        CompositeNode parent = (CompositeNode) aStream.readObject();
-        @SuppressWarnings("unchecked")
-        List<Node<?>> value = (List<Node<?>>) aStream.readObject();
-        ModifyAction modifyAction = (ModifyAction) aStream.readObject();
-
-        init(qName, parent, value, modifyAction);
-    }
-
-    private void writeObject(final ObjectOutputStream aStream) throws IOException {
-        aStream.defaultWriteObject();
-        // manually serialize superclass
-        aStream.writeObject(getQName());
-        aStream.writeObject(getParent());
-        aStream.writeObject(getValue());
-        aStream.writeObject(getModificationAction());
-    }
-
-    public static CompositeNodeBuilder<ImmutableCompositeNode> builder() {
-        return new ImmutableCompositeNodeBuilder();
-    }
-
-    private static class ImmutableCompositeNodeBuilder extends AbstractCompositeNodeBuilder<ImmutableCompositeNode> {
-
-        @Override
-        public AbstractCompositeNodeBuilder<ImmutableCompositeNode> addLeaf(final QName leafName, final Object leafValue) {
-            add(new SimpleNodeTOImpl<Object>(leafName, null, leafValue));
-            return this;
-        }
-
-        @Override
-        public ImmutableCompositeNode build() {
-            return ImmutableCompositeNode.create(this.getQName(), this.getAttributes(), this.getChildNodes());
-        }
-
-        @Deprecated
-        public ImmutableCompositeNode toInstance() {
-            return ImmutableCompositeNode.create(this.getQName(), this.getAttributes(), this.getChildNodes());
-        }
-
-    }
-
-    public static ImmutableCompositeNode create(final QName qName, final List<Node<?>> childNodes) {
-        return new ImmutableCompositeNode(qName, ImmutableMap.<QName, String>of(),childNodes);
-    }
-
-    public static ImmutableCompositeNode create(final QName qName, final Map<QName, String> attributes, final List<Node<?>> childNodes) {
-        return new ImmutableCompositeNode(qName, attributes,childNodes);
-    }
-
-    public static ImmutableCompositeNode create(final QName qName, final List<Node<?>> childNodes, final ModifyAction modifyAction) {
-        return new ImmutableCompositeNode(qName, childNodes, modifyAction);
-    }
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/LazyNodeToNodeMap.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/LazyNodeToNodeMap.java
deleted file mode 100644 (file)
index 4eae564..0000000
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Deque;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableNode;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.NodeModification;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-
-/**
- * @author michal.rehak
- *
- */
-@Deprecated
-public class LazyNodeToNodeMap {
-
-    private final Map<Node<?>, Node<?>> node2node = new HashMap<>();
-    private CompositeNode originalRoot;
-    private MutableCompositeNode mutableRoot;
-
-    /**
-     * @param originalNode
-     * @return mutable twin
-     */
-    public Node<?> getMutableEquivalent(final Node<?> originalNode) {
-        Node<?> mutableNode = node2node.get(originalNode);
-        if (mutableNode == null) {
-            addPathMembers(originalNode);
-            mutableNode = node2node.get(originalNode);
-        }
-
-        return mutableNode;
-    }
-
-    /**
-     * @param originalNode
-     */
-    private void addPathMembers(final Node<?> originalNode) {
-        final Deque<Node<?>> jobQueue = new ArrayDeque<>();
-        jobQueue.push(originalNode);
-        while (!jobQueue.isEmpty()) {
-            Node<?> node2add = jobQueue.pop();
-            boolean fixChildrenRefOnly = false;
-            if (node2node.containsKey(node2add)) {
-                if (node2add instanceof SimpleNode<?>) {
-                    continue;
-                }
-                fixChildrenRefOnly = true;
-            }
-
-            CompositeNode nextParent = node2add.getParent();
-            MutableNode<?> mutableEquivalent = null;
-
-            if (node2add instanceof SimpleNode<?>) {
-                SimpleNode<?> node2addSimple = (SimpleNode<?>) node2add;
-                MutableSimpleNode<?> nodeMutant = NodeFactory.createMutableSimpleNode(
-                        node2add.getNodeType(), null, node2addSimple.getValue(),
-                        node2addSimple.getModificationAction(), node2addSimple);
-                mutableEquivalent = nodeMutant;
-            } else if (node2add instanceof CompositeNode) {
-                MutableCompositeNode nodeMutant = null;
-                if (fixChildrenRefOnly) {
-                    nodeMutant = (MutableCompositeNode) node2node.get(node2add);
-                } else {
-                    CompositeNode node2addComposite = (CompositeNode) node2add;
-                    nodeMutant = NodeFactory.createMutableCompositeNode(node2add.getNodeType(),
-                            null, null,
-                            ((NodeModification) node2add).getModificationAction(), node2addComposite);
-                }
-
-                mutableEquivalent = nodeMutant;
-
-                // tidy up children
-                if (nodeMutant.getValue() == null) {
-                    nodeMutant.setValue(new ArrayList<Node<?>>());
-                }
-                for (Node<?> originalChildNode : ((CompositeNode) node2add).getValue()) {
-                    MutableNode<?> mutableChild = (MutableNode<?>) node2node.get(originalChildNode);
-                    fixChildrenRef(nodeMutant, mutableChild);
-                }
-
-                if (nodeMutant.getValue() != null && !nodeMutant.getValue().isEmpty()) {
-                    nodeMutant.init();
-                }
-
-                // store tree root, if occured
-                if (nextParent == null) {
-                    if (originalRoot == null) {
-                        originalRoot = (CompositeNode) node2add;
-                        mutableRoot = nodeMutant;
-                    } else {
-                        if (!originalRoot.equals(node2add)) {
-                            throw new IllegalStateException("Different tree root node obtained - " +
-                                    "perhaps nodes of different trees are getting mixed up.");
-                        }
-                    }
-                }
-            }
-
-            // feed jobQueue
-            node2node.put(node2add, mutableEquivalent);
-            if (nextParent != null) {
-                jobQueue.push(nextParent);
-            }
-        }
-    }
-
-    /**
-     * @param nodeMutant
-     * @param mutableChild
-     */
-    private static void fixChildrenRef(final MutableCompositeNode nodeMutant,
-            final MutableNode<?> mutableChild) {
-        if (mutableChild != null) {
-            if (!nodeMutant.getValue().contains(mutableChild)) {
-                nodeMutant.getValue().add(mutableChild);
-            }
-            CompositeNode parentOfChild = mutableChild.getParent();
-            if (parentOfChild == null) {
-                mutableChild.setParent(nodeMutant);
-            } else {
-                if (!parentOfChild.equals(nodeMutant)) {
-                    throw new IllegalStateException("Different parent node obtained - " +
-                            "perhaps nodes of different trees are getting mixed up.");
-                }
-            }
-        }
-    }
-
-    /**
-     * @return the mutableRoot
-     */
-    public MutableCompositeNode getMutableRoot() {
-        return mutableRoot;
-    }
-
-    /**
-     * @return set of original nodes, registered in map as keys
-     */
-    public Set<Node<?>> getKeyNodes() {
-        return node2node.keySet();
-    }
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/MutableCompositeNodeTOImpl.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/MutableCompositeNodeTOImpl.java
deleted file mode 100644 (file)
index 45aabc3..0000000
+++ /dev/null
@@ -1,254 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import 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;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
-
-/**
- * @author michal.rehak
- *
- * @deprecated Use one of the {@link NormalizedNodeContainer} implementations instead.
- */
-@Deprecated
-public class MutableCompositeNodeTOImpl extends AbstractNodeTO<List<Node<?>>> implements MutableCompositeNode, Serializable {
-
-    private static final long serialVersionUID = 100L;
-
-    private Map<QName, List<Node<?>>> nodeMap = new HashMap<>();
-    private CompositeNode original;
-
-    public MutableCompositeNodeTOImpl(final QName qname, final CompositeNode parent, final List<Node<?>> value, final ModifyAction modifyAction) {
-        super(qname, parent, value, modifyAction);
-        init();
-    }
-
-    /**
-     * update nodeMap - it should be invoked after children was changed
-     */
-    @Override
-    public void init() {
-        if (!getChildren().isEmpty()) {
-            nodeMap = NodeUtils.buildNodeMap(getChildren());
-        }
-    }
-
-    @Override
-    public List<Node<?>> getChildren() {
-        return getValue() == null ? new ArrayList<Node<?>>() : getValue();
-    }
-
-    @Override
-    public List<Node<?>> setValue(final List<Node<?>> value) {
-        List<Node<?>> oldVal = super.setValue(value);
-        init();
-        return oldVal;
-    }
-
-    @Override
-    public void setModifyAction(final ModifyAction action) {
-        super.setModificationAction(action);
-    }
-
-    protected Map<QName, List<Node<?>>> getNodeMap() {
-        return nodeMap;
-    }
-
-    @Override
-    public MutableCompositeNode asMutable() {
-        return this;
-    }
-
-    @Override
-    public CompositeNode getOriginal() {
-        return original;
-    }
-
-    /**
-     * @param original
-     *            the original to set
-     */
-    public void setOriginal(final CompositeNode original) {
-        this.original = original;
-    }
-
-    @Override
-    public SimpleNode<?> getFirstSimpleByName(final QName leafQName) {
-        List<SimpleNode<?>> list = getSimpleNodesByName(leafQName);
-        if (list.isEmpty()) {
-            return null;
-        }
-        return list.get(0);
-    }
-
-    @Override
-    public List<CompositeNode> getCompositesByName(final QName children) {
-        List<Node<?>> toFilter = getNodeMap().get(children);
-        if (toFilter == null) {
-            return Collections.emptyList();
-        }
-        List<CompositeNode> list = new ArrayList<CompositeNode>();
-        for (Node<?> node : toFilter) {
-            if (node instanceof CompositeNode) {
-                list.add((CompositeNode) node);
-            }
-        }
-        return list;
-    }
-
-    @Override
-    public List<SimpleNode<?>> getSimpleNodesByName(final QName children) {
-        List<Node<?>> toFilter = getNodeMap().get(children);
-        if (toFilter == null) {
-            return Collections.emptyList();
-        }
-        List<SimpleNode<?>> list = new ArrayList<SimpleNode<?>>();
-
-        for (Node<?> node : toFilter) {
-            if (node instanceof SimpleNode<?>) {
-                list.add((SimpleNode<?>) node);
-            }
-        }
-        return list;
-    }
-
-    @Override
-    public CompositeNode getFirstCompositeByName(final QName container) {
-        List<CompositeNode> list = getCompositesByName(container);
-        if (list.isEmpty()) {
-            return null;
-        }
-        return list.get(0);
-    }
-
-    /**
-     * @param leaf
-     * @return TODO:: do we need this method?
-     */
-    public SimpleNode<?> getFirstLeafByName(final QName leaf) {
-        List<SimpleNode<?>> list = getSimpleNodesByName(leaf);
-        if (list.isEmpty()) {
-            return null;
-        }
-        return list.get(0);
-    }
-
-    @Override
-    public List<CompositeNode> getCompositesByName(final String children) {
-        return getCompositesByName(QName.create(getNodeType(), children));
-    }
-
-    @Override
-    public List<SimpleNode<?>> getSimpleNodesByName(final String children) {
-        return getSimpleNodesByName(QName.create(getNodeType(), children));
-    }
-
-    @Override
-    public String toString() {
-        return super.toString() + ", children.size = " + (getChildren() != null ? getChildren().size() : "n/a");
-    }
-
-    @Override
-    public void clear() {
-        nodeMap.clear();
-    }
-
-    @Override
-    public boolean containsKey(final Object key) {
-        return nodeMap.containsKey(key);
-    }
-
-    @Override
-    public boolean containsValue(final Object value) {
-        return nodeMap.containsValue(value);
-    }
-
-    @Override
-    public Set<java.util.Map.Entry<QName, List<Node<?>>>> entrySet() {
-        return nodeMap.entrySet();
-    }
-
-    @Override
-    public int size() {
-        return nodeMap.size();
-    }
-
-    @Override
-    public boolean isEmpty() {
-        return nodeMap.isEmpty();
-    }
-
-    @Override
-    public List<Node<?>> get(final Object key) {
-        return nodeMap.get(key);
-    }
-
-    @Override
-    public List<Node<?>> put(final QName key, final List<Node<?>> value) {
-        return nodeMap.put(key, value);
-    }
-
-    @Override
-    public List<Node<?>> remove(final Object key) {
-        return nodeMap.remove(key);
-    }
-
-    @Override
-    public void putAll(final Map<? extends QName, ? extends List<Node<?>>> m) {
-        nodeMap.putAll(m);
-    }
-
-    @Override
-    public Set<QName> keySet() {
-        return nodeMap.keySet();
-    }
-
-    @Override
-    public Collection<List<Node<?>>> values() {
-        return nodeMap.values();
-    }
-
-    // Serialization related
-
-    private void readObject(final ObjectInputStream aStream) throws IOException, ClassNotFoundException {
-        aStream.defaultReadObject();
-        QName qName = (QName)aStream.readObject();
-        CompositeNode parent = (CompositeNode) aStream.readObject();
-        @SuppressWarnings("unchecked")
-        List<Node<?>> value = (List<Node<?>>) aStream.readObject();
-        ModifyAction modifyAction = (ModifyAction) aStream.readObject();
-
-        init(qName, parent, value, modifyAction);
-    }
-
-    private void writeObject(final ObjectOutputStream aStream) throws IOException {
-        aStream.defaultWriteObject();
-        //manually serialize superclass
-        aStream.writeObject(getQName());
-        aStream.writeObject(getParent());
-        aStream.writeObject(getValue());
-        aStream.writeObject(getModificationAction());
-    }
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/MutableSimpleNodeTOImpl.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/MutableSimpleNodeTOImpl.java
deleted file mode 100644 (file)
index a51b446..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-/**
- * @author michal.rehak
- * @param <T>
- *            type of simple node value
- *
- * @deprecated Use one of the {@link NormalizedNode} implementation packages.
- */
-@Deprecated
-public class MutableSimpleNodeTOImpl<T> extends SimpleNodeTOImpl<T> implements MutableSimpleNode<T> {
-    private static final long serialVersionUID = 1L;
-    private SimpleNode<T> original;
-
-    /**
-     * @param qname
-     * @param parent
-     * @param value
-     * @param modifyAction
-     */
-    public MutableSimpleNodeTOImpl(final QName qname, final CompositeNode parent, final T value, final ModifyAction modifyAction) {
-        super(qname, parent, value, modifyAction);
-    }
-
-    @Override
-    public void setModifyAction(final ModifyAction action) {
-        super.setModificationAction(action);
-    }
-
-    @Override
-    public MutableSimpleNode<T> asMutable() {
-        return this;
-    }
-
-    @Override
-    public SimpleNode<T> getOriginal() {
-        return original;
-    }
-
-    /**
-     * @param original
-     *            the original to set
-     */
-    public void setOriginal(final SimpleNode<T> original) {
-        this.original = original;
-    }
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/NodeFactory.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/NodeFactory.java
deleted file mode 100644 (file)
index ee1dda9..0000000
+++ /dev/null
@@ -1,259 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import java.util.AbstractMap.SimpleEntry;
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Deque;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.NodeModification;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-
-/**
- * @author michal.rehak
- *
- * @deprecated Use {@link Builders} instead.
- */
-@Deprecated
-public abstract class NodeFactory {
-
-    /**
-     * @param qName
-     * @param parent
-     * @param value
-     * @return simple node modification, based on given qname, value and parent
-     */
-    public static <T> SimpleNode<T> createImmutableSimpleNode(final QName qName,
-            final CompositeNode parent, final T value) {
-        return createImmutableSimpleNode(qName, parent, value, null);
-    }
-
-    /**
-     * @param qName
-     * @param parent
-     * @param value
-     * @param modifyAction
-     * @param original originating node, if available
-     * @return simple node modification, based on given qname, value and parent
-     */
-    public static <T> MutableSimpleNode<T> createMutableSimpleNode(final QName qName,
-            final CompositeNode parent, final Object value, final ModifyAction modifyAction, final SimpleNode<T> original) {
-        @SuppressWarnings("unchecked")
-        MutableSimpleNodeTOImpl<T> simpleNodeTOImpl = new MutableSimpleNodeTOImpl<>(qName, parent, (T) value, modifyAction);
-        simpleNodeTOImpl.setOriginal(original);
-        return simpleNodeTOImpl;
-    }
-
-    /**
-     * @param qName
-     * @param parent
-     * @param value
-     * @return composite node modification, based on given qname, value (children), parent and modifyAction
-     */
-    public static CompositeNode createImmutableCompositeNode(final QName qName,
-            final CompositeNode parent, final List<Node<?>> value) {
-        return createImmutableCompositeNode(qName, parent, value, null);
-    }
-
-    /**
-     * @param qName
-     * @param parent
-     * @param valueArg
-     * @param modifyAction
-     * @param original originating node, if available
-     * @return composite node modification, based on given qName, value (children), parent and modifyAction
-     */
-    public static MutableCompositeNode createMutableCompositeNode(final QName qName,
-            final CompositeNode parent, final List<Node<?>> valueArg, final ModifyAction modifyAction, final CompositeNode original) {
-        List<Node<?>> value = valueArg;
-        if (value == null) {
-            value = new ArrayList<>();
-        }
-        MutableCompositeNodeTOImpl compositeNodeTOImpl =
-                new MutableCompositeNodeTOImpl(qName, parent, value, modifyAction);
-        compositeNodeTOImpl.setOriginal(original);
-        return compositeNodeTOImpl;
-    }
-
-
-    /**
-     * @param qName
-     * @param parent
-     * @param value
-     * @param modifyAction
-     * @return simple node modification, based on given qname, value, parent and modifyAction
-     */
-    public static <T> SimpleNode<T> createImmutableSimpleNode(final QName qName,
-            final CompositeNode parent, final T value, final ModifyAction modifyAction) {
-        SimpleNodeTOImpl<T> simpleNodeModTOImpl =
-                new SimpleNodeTOImpl<T>(qName, parent, value, modifyAction);
-        return simpleNodeModTOImpl;
-    }
-
-    /**
-     * @param qName
-     * @param parent
-     * @param value
-     * @param modifyAction
-     * @return composite node modification, based on given qname, value (children), parent and modifyAction
-     */
-    public static CompositeNode createImmutableCompositeNode(final QName qName,
-            final CompositeNode parent, final List<Node<?>> value, final ModifyAction modifyAction) {
-        return new CompositeNodeTOImpl(qName, parent, value, modifyAction);
-    }
-
-    /**
-     * @param node
-     * @return copy of given node, parent and value are the same, but parent
-     * has no reference to this copy
-     */
-    public static <T> SimpleNode<T> copyNode(final SimpleNode<T> node) {
-        return createImmutableSimpleNode(node.getNodeType(), node.getParent(), node.getValue());
-    }
-
-    /**
-     * @param node
-     * @return copy of given node, parent and value are the same, but parent
-     * has no reference to this copy
-     */
-    public static <T> MutableSimpleNode<T> copyNodeAsMutable(final SimpleNode<T> node) {
-        return createMutableSimpleNode(
-                node.getNodeType(), node.getParent(), node.getValue(),
-                node.getModificationAction(), null);
-    }
-
-    /**
-     * @param node
-     * @param children
-     * @return copy of given node, parent and children are the same, but parent and children
-     * have no reference to this copy
-     */
-    public static CompositeNode copyNode(final CompositeNode node, final Node<?>... children) {
-        CompositeNode twinNode = createImmutableCompositeNode(
-                node.getNodeType(), node.getParent(), Arrays.asList(children), node.getModificationAction());
-        return twinNode;
-    }
-
-    /**
-     * @param node
-     * @return copy of given node, parent and children are the same, but parent and children
-     * have no reference to this copy
-     */
-    public static CompositeNode copyNode(final CompositeNode node) {
-        return copyNode(node, node.getValue().toArray(new Node<?>[0]));
-    }
-
-    /**
-     * @param node root of original tree
-     * @param originalToCopyArg (optional) empty map, where binding between original and copy
-     * will be stored
-     * @return copy of given node and all subnodes recursively
-     */
-    public static MutableCompositeNode copyDeepAsMutable(final CompositeNode node,
-            final Map<Node<?>, Node<?>> originalToCopyArg) {
-
-        Map<Node<?>, Node<?>> originalToCopy = originalToCopyArg;
-        if (originalToCopy == null) {
-            originalToCopy = new HashMap<>();
-        }
-
-        MutableCompositeNode mutableRoot = createMutableCompositeNode(node.getNodeType(), null, null,
-                node.getModificationAction(), null);
-        final Deque<SimpleEntry<CompositeNode, MutableCompositeNode>> jobQueue = new ArrayDeque<>();
-        jobQueue.push(new SimpleEntry<CompositeNode, MutableCompositeNode>(node, mutableRoot));
-        originalToCopy.put(node, mutableRoot);
-
-        while (!jobQueue.isEmpty()) {
-            SimpleEntry<CompositeNode, MutableCompositeNode> job = jobQueue.pop();
-            CompositeNode originalNode = job.getKey();
-            MutableCompositeNode mutableNode = job.getValue();
-            mutableNode.setValue(new ArrayList<Node<?>>());
-
-            for (Node<?> child : originalNode.getValue()) {
-                Node<?> mutableAscendant = null;
-                if (child instanceof CompositeNode) {
-                    MutableCompositeNode newMutable =
-                            createMutableCompositeNode(child.getNodeType(), mutableNode, null,
-                                    ((NodeModification) child).getModificationAction(), null);
-                    jobQueue.push(new SimpleEntry<CompositeNode, MutableCompositeNode>(
-                            (CompositeNode) child, newMutable));
-                    mutableAscendant = newMutable;
-                } else if (child instanceof SimpleNode<?>) {
-                    mutableAscendant =
-                            createMutableSimpleNode(child.getNodeType(), mutableNode,
-                                    child.getValue(),
-                                    ((NodeModification) child).getModificationAction(), null);
-                } else {
-                    throw new IllegalStateException("Node class deep copy not supported: "
-                            +child.getClass().getName());
-                }
-
-                mutableNode.getValue().add(mutableAscendant);
-                originalToCopy.put(child, mutableAscendant);
-            }
-            mutableNode.init();
-        }
-
-        return mutableRoot;
-    }
-
-    /**
-     * @param node root of original tree
-     * @param originalToCopyArg (optional) empty map, where binding between original and copy
-     * will be stored
-     * @return copy of given node and all subnodes recursively
-     */
-    public static CompositeNode copyDeepAsImmutable(final CompositeNode node,
-            final Map<Node<?>, Node<?>> originalToCopyArg) {
-        final Deque<CompositeNode> jobQueue = new ArrayDeque<>();
-        jobQueue.push(node);
-
-        Map<Node<?>, Node<?>> originalToCopy = originalToCopyArg;
-        if (originalToCopy == null) {
-            originalToCopy = new HashMap<>();
-        }
-
-        while (!jobQueue.isEmpty()) {
-            CompositeNode jobNode = jobQueue.peek();
-            if (!originalToCopy.isEmpty()
-                    && originalToCopy.keySet().containsAll(jobNode.getValue())) {
-                jobQueue.pop();
-                List<Node<?>> newChildren = NodeUtils.collectMapValues(jobNode.getValue(), originalToCopy);
-                CompositeNode nodeCopy = createImmutableCompositeNode(jobNode.getNodeType(), null,
-                        newChildren, jobNode.getModificationAction());
-                NodeUtils.fixChildrenRelation(nodeCopy);
-                originalToCopy.put(jobNode, nodeCopy);
-            } else {
-                for (Node<?> child : jobNode.getValue()) {
-                    if (child instanceof SimpleNode<?>) {
-                        originalToCopy.put(child, createImmutableSimpleNode(
-                                child.getNodeType(), null, child.getValue(),
-                                ((NodeModification) child).getModificationAction()));
-                    } else if (child instanceof CompositeNode) {
-                        jobQueue.push((CompositeNode) child);
-                    }
-                }
-            }
-        }
-
-        return (CompositeNode) originalToCopy.get(node);
-    }
-
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/NodeModificationBuilderImpl.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/NodeModificationBuilderImpl.java
deleted file mode 100644 (file)
index 2f99ba3..0000000
+++ /dev/null
@@ -1,164 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import java.util.HashSet;
-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;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableNode;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.NodeModificationBuilder;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-
-/**
- * @author michal.rehak
- *
- * @deprecated Use {@link Builders} instead.
- */
-@Deprecated
-public class NodeModificationBuilderImpl implements NodeModificationBuilder {
-
-    private final SchemaContext context;
-
-    private final Set<MutableNode<?>> changeLog;
-    private final LazyNodeToNodeMap originalToMutable;
-
-    /**
-     * @param context
-     */
-    public NodeModificationBuilderImpl(final SchemaContext context) {
-        this.context = context;
-        originalToMutable = new LazyNodeToNodeMap();
-        changeLog = new HashSet<>();
-    }
-
-    /**
-     * @param modNode
-     * @param action
-     */
-    private void addModificationToLog(final MutableNode<?> modNode, final ModifyAction action) {
-        modNode.setModifyAction(action);
-        changeLog.add(modNode);
-    }
-
-    @Override
-    public void addNode(final MutableSimpleNode<?> newNode) {
-        NodeUtils.fixParentRelation(newNode);
-        addModificationToLog(newNode, ModifyAction.CREATE);
-    }
-
-    @Override
-    public void addNode(final MutableCompositeNode newNode) {
-        NodeUtils.fixParentRelation(newNode);
-        addModificationToLog(newNode, ModifyAction.CREATE);
-    }
-
-    @Override
-    public void replaceNode(final MutableSimpleNode<?> replacementNode) {
-        addModificationToLog(replacementNode, ModifyAction.REPLACE);
-    }
-
-    @Override
-    public void replaceNode(final MutableCompositeNode replacementNode) {
-        addModificationToLog(replacementNode, ModifyAction.REPLACE);
-    }
-
-    @Override
-    public void deleteNode(final MutableCompositeNode deadNode) {
-        addModificationToLog(deadNode, ModifyAction.DELETE);
-    }
-
-    @Override
-    public void deleteNode(final MutableSimpleNode<?> deadNode) {
-        addModificationToLog(deadNode, ModifyAction.DELETE);
-    }
-
-    @Override
-    public void removeNode(final MutableSimpleNode<?> deadNode) {
-        addModificationToLog(deadNode, ModifyAction.REMOVE);
-    }
-
-    @Override
-    public void removeNode(final MutableCompositeNode deadNode) {
-        addModificationToLog(deadNode, ModifyAction.REMOVE);
-    }
-
-    @Override
-    public void mergeNode(final MutableCompositeNode alteredNode) {
-        addModificationToLog(alteredNode, ModifyAction.MERGE);
-    }
-
-    /**
-     * @return minimalistic tree containing diffs only
-     */
-    @Override
-    public CompositeNode buildDiffTree() {
-        Set<Node<?>> wanted = new HashSet<>();
-
-        // walk changeLog, collect all required nodes
-        for (MutableNode<?> mutant : changeLog) {
-            wanted.addAll(collectSelfAndAllParents(mutant));
-        }
-
-        // walk wanted and add relevant keys
-        Map<String, ListSchemaNode> mapOfLists = NodeUtils.buildMapOfListNodes(context);
-        for (Node<?> outlaw : wanted) {
-            if (outlaw instanceof CompositeNode) {
-                String path = NodeUtils.buildPath(outlaw);
-                if (mapOfLists.containsKey(path)) {
-                    ListSchemaNode listSchema = mapOfLists.get(path);
-                    if (listSchema.getQName().equals(outlaw.getNodeType())) {
-                        // try to add key subnode to wanted list
-                        List<QName> supportedKeys = listSchema.getKeyDefinition();
-                        CompositeNode outlawOriginal = ((MutableCompositeNode) outlaw).getOriginal();
-                        for (Node<?> outlawOriginalChild : outlawOriginal.getValue()) {
-                            if (supportedKeys.contains(outlawOriginalChild.getNodeType())) {
-                                originalToMutable.getMutableEquivalent(outlawOriginalChild);
-                            }
-                        }
-                    }
-                }
-            }
-        }
-
-        return originalToMutable.getMutableRoot();
-    }
-
-    /**
-     * @param focusedDescendant
-     * @return set of parents and focusedAncestor itself
-     */
-    private static Set<Node<?>> collectSelfAndAllParents(final Node<?> focusedDescendant) {
-        Set<Node<?>> family = new HashSet<>();
-        Node<?> tmpNode = focusedDescendant;
-        while (tmpNode != null) {
-            family.add(tmpNode);
-            tmpNode = tmpNode.getParent();
-        }
-        return family;
-    }
-
-    /**
-     * @param originalNode
-     * @return mutable version of given node
-     */
-    @Override
-    public Node<?> getMutableEquivalent(final Node<?> originalNode) {
-        return originalToMutable.getMutableEquivalent(originalNode);
-    }
-
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/NodeUtils.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/NodeUtils.java
deleted file mode 100644 (file)
index 10e79e2..0000000
+++ /dev/null
@@ -1,262 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import com.google.common.base.Function;
-import com.google.common.base.Joiner;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Maps;
-import java.util.AbstractMap.SimpleEntry;
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Deque;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import javax.annotation.Nonnull;
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.xpath.XPath;
-import javax.xml.xpath.XPathConstants;
-import javax.xml.xpath.XPathExpression;
-import javax.xml.xpath.XPathExpressionException;
-import javax.xml.xpath.XPathFactory;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.NodeModification;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
-import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Element;
-
-/**
- * @author michal.rehak
- *
- * @deprecated Use {@link NormalizedNodes} instead.
- */
-@Deprecated
-public abstract class NodeUtils {
-    private static final Joiner DOT_JOINER = Joiner.on(".");
-    private static final Logger LOG = LoggerFactory.getLogger(NodeUtils.class);
-    private static final Function<QName, String> LOCALNAME_FUNCTION = new Function<QName, String>() {
-        @Override
-        public String apply(final @Nonnull QName input) {
-            Preconditions.checkNotNull(input);
-            return input.getLocalName();
-        }
-    };
-
-    /**
-     *
-     */
-    private static final String USER_KEY_NODE = "node";
-
-    /**
-     * @param node
-     * @return node path up till root node
-     */
-    public static String buildPath(final Node<?> node) {
-        List<String> breadCrumbs = new ArrayList<>();
-        Node<?> tmpNode = node;
-        while (tmpNode != null) {
-            breadCrumbs.add(0, tmpNode.getNodeType().getLocalName());
-            tmpNode = tmpNode.getParent();
-        }
-
-        return DOT_JOINER.join(breadCrumbs);
-    }
-
-    /**
-     * @param treeRootNode
-     * @return dom tree, containing same node structure, yang nodes are
-     *         associated to dom nodes as user data
-     */
-    public static org.w3c.dom.Document buildShadowDomTree(final CompositeNode treeRootNode) {
-        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
-        org.w3c.dom.Document doc = null;
-        try {
-            DocumentBuilder bob = dbf.newDocumentBuilder();
-            doc = bob.newDocument();
-        } catch (ParserConfigurationException e) {
-            LOG.error("documentBuilder problem", e);
-            return null;
-        }
-
-        final Deque<SimpleEntry<org.w3c.dom.Node, Node<?>>> jobQueue = new ArrayDeque<>();
-        jobQueue.push(new SimpleEntry<org.w3c.dom.Node, Node<?>>(doc, treeRootNode));
-
-        while (!jobQueue.isEmpty()) {
-            SimpleEntry<org.w3c.dom.Node, Node<?>> job = jobQueue.pop();
-            org.w3c.dom.Node jointPlace = job.getKey();
-            Node<?> item = job.getValue();
-            QName nodeType = item.getNodeType();
-            Element itemEl = doc.createElementNS(nodeType.getNamespace().toString(), item.getNodeType().getLocalName());
-            itemEl.setUserData(USER_KEY_NODE, item, null);
-            if (item instanceof SimpleNode<?>) {
-                Object value = ((SimpleNode<?>) item).getValue();
-                if(value != null) {
-                    itemEl.setTextContent(String.valueOf(value));
-                }
-            }
-            if (item instanceof NodeModification) {
-                ModifyAction modificationAction = ((NodeModification) item).getModificationAction();
-                if (modificationAction != null) {
-                    itemEl.setAttribute("modifyAction", modificationAction.toString());
-                }
-            }
-
-            jointPlace.appendChild(itemEl);
-
-            if (item instanceof CompositeNode) {
-                for (Node<?> child : ((CompositeNode) item).getValue()) {
-                    jobQueue.push(new SimpleEntry<org.w3c.dom.Node, Node<?>>(itemEl, child));
-                }
-            }
-        }
-
-        return doc;
-    }
-
-    /**
-     * @param doc
-     * @param xpathEx
-     * @return user data value on found node
-     * @throws XPathExpressionException
-     */
-    @SuppressWarnings("unchecked")
-    public static <T> T findNodeByXpath(final org.w3c.dom.Document doc, final String xpathEx) throws XPathExpressionException {
-        T userNode = null;
-        XPathFactory xPathfactory = XPathFactory.newInstance();
-        XPath xpath = xPathfactory.newXPath();
-        XPathExpression expr = xpath.compile(xpathEx);
-
-        org.w3c.dom.Node result = (org.w3c.dom.Node) expr.evaluate(doc, XPathConstants.NODE);
-        if (result != null) {
-            userNode = (T) result.getUserData(USER_KEY_NODE);
-        }
-
-        return userNode;
-    }
-
-    /**
-     * build NodeMap, where key = qName; value = node
-     *
-     * @param value
-     * @return map of children, where key = qName and value is list of children
-     *         groupped by qName
-     */
-    public static Map<QName, List<Node<?>>> buildNodeMap(final List<Node<?>> value) {
-        Map<QName, List<Node<?>>> nodeMapTmp = Maps.newLinkedHashMap();
-        if (value == null) {
-            throw new IllegalStateException("nodeList should not be null or empty");
-        }
-        for (Node<?> node : value) {
-            List<Node<?>> qList = nodeMapTmp.get(node.getNodeType());
-            if (qList == null) {
-                qList = new ArrayList<>();
-                nodeMapTmp.put(node.getNodeType(), qList);
-            }
-            qList.add(node);
-        }
-        return nodeMapTmp;
-    }
-
-    /**
-     * @param context
-     * @return map of lists, where key = path; value = {@link DataSchemaNode}
-     */
-    public static Map<String, ListSchemaNode> buildMapOfListNodes(final SchemaContext context) {
-        Map<String, ListSchemaNode> mapOfLists = new HashMap<>();
-
-        final Deque<DataSchemaNode> jobQueue = new ArrayDeque<>();
-        jobQueue.addAll(context.getDataDefinitions());
-
-        while (!jobQueue.isEmpty()) {
-            DataSchemaNode dataSchema = jobQueue.pop();
-            if (dataSchema instanceof ListSchemaNode) {
-                mapOfLists.put(schemaPathToPath(dataSchema.getPath().getPathFromRoot()), (ListSchemaNode) dataSchema);
-            }
-
-            if (dataSchema instanceof DataNodeContainer) {
-                jobQueue.addAll(((DataNodeContainer) dataSchema).getChildNodes());
-            }
-        }
-
-        return mapOfLists;
-    }
-
-    /**
-     * @param qNamesPath
-     * @return path
-     */
-    private static String schemaPathToPath(final Iterable<QName> qNamesPath) {
-        return DOT_JOINER.join(Iterables.transform(qNamesPath, LOCALNAME_FUNCTION));
-    }
-
-    /**
-     * add given node to it's parent's list of children
-     *
-     * @param newNode
-     */
-    public static void fixParentRelation(final Node<?> newNode) {
-        if (newNode.getParent() != null) {
-            List<Node<?>> siblings = newNode.getParent().getValue();
-            if (!siblings.contains(newNode)) {
-                siblings.add(newNode);
-            }
-        }
-    }
-
-    /**
-     * crawl all children of given node and assign it as their parent
-     *
-     * @param parentNode
-     */
-    public static void fixChildrenRelation(final CompositeNode parentNode) {
-        if (parentNode.getValue() != null) {
-            for (Node<?> child : parentNode.getValue()) {
-                if (child instanceof AbstractNodeTO<?>) {
-                    ((AbstractNodeTO<?>) child).setParent(parentNode);
-                }
-            }
-        }
-    }
-
-    /**
-     * @param keys
-     * @param dataMap
-     * @return list of values of map, found by given keys
-     */
-    public static <T, K> List<K> collectMapValues(final List<T> keys, final Map<T, K> dataMap) {
-        List<K> valueSubList = new ArrayList<>();
-        for (T key : keys) {
-            valueSubList.add(dataMap.get(key));
-        }
-
-        return valueSubList;
-    }
-
-    /**
-     * @param nodes
-     * @return list of children in list of appropriate type
-     */
-    public static List<Node<?>> buildChildrenList(final Node<?>... nodes) {
-        return Lists.newArrayList(nodes);
-    }
-
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/SimpleNodeModificationTOImpl.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/SimpleNodeModificationTOImpl.java
deleted file mode 100644 (file)
index bc98ad5..0000000
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-/**
- * @author michal.rehak
- * @param <T> type of node value
- *
- * @deprecated Use one of the {@link NormalizedNode} implementation packages.
- */
-@Deprecated
-public class SimpleNodeModificationTOImpl<T> extends SimpleNodeTOImpl<T> {
-    private static final long serialVersionUID = 1L;
-
-    /**
-     * @param qname
-     * @param parent
-     * @param value
-     * @param modifyAction
-     */
-    public SimpleNodeModificationTOImpl(final QName qname, final CompositeNode parent,
-            final T value, final ModifyAction modifyAction) {
-        super(qname, parent, value);
-        setModificationAction(modifyAction);
-    }
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/SimpleNodeTOImpl.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/SimpleNodeTOImpl.java
deleted file mode 100644 (file)
index 3b6d371..0000000
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import java.io.IOException;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-/**
- * @author michal.rehak
- * @param <T> type of simple node value
- *
- * @deprecated Use one of the {@link NormalizedNode} implementation packages.
- */
-@Deprecated
-public class SimpleNodeTOImpl<T> extends AbstractNodeTO<T> implements SimpleNode<T>, Serializable {
-
-    private static final long serialVersionUID = 100L;
-
-    /**
-     * @param qname
-     * @param parent
-     * @param value
-     */
-    public SimpleNodeTOImpl(final QName qname, final CompositeNode parent, final T value) {
-        super(qname, parent, value);
-    }
-
-    /**
-     * @param qname
-     * @param parent
-     * @param value
-     * @param modifyAction
-     */
-    public SimpleNodeTOImpl(final QName qname, final CompositeNode parent, final T value, final ModifyAction modifyAction) {
-        super(qname, parent, value, modifyAction);
-    }
-
-    @Override
-    public MutableSimpleNode<T> asMutable() {
-        throw new IllegalAccessError("cast to mutable is not supported - "+getClass().getSimpleName());
-    }
-
-    @Override
-    public String toString() {
-
-        return super.toString() + ", value = "+getValue();
-    }
-
-    // Serialization related
-
-    private void readObject(final ObjectInputStream aStream) throws IOException, ClassNotFoundException {
-        aStream.defaultReadObject();
-        QName qName = (QName)aStream.readObject();
-        CompositeNode parent = (CompositeNode) aStream.readObject();
-        T value = (T) aStream.readObject();
-        ModifyAction modifyAction = (ModifyAction) aStream.readObject();
-
-        init(qName, parent, value, modifyAction);
-    }
-
-    private void writeObject(final ObjectOutputStream aStream) throws IOException {
-        aStream.defaultWriteObject();
-        //manually serialize superclass
-        aStream.writeObject(getQName());
-        aStream.writeObject(getParent());
-        aStream.writeObject(getValue());
-        aStream.writeObject(getModificationAction());
-    }
-
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/XmlTreeBuilder.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/XmlTreeBuilder.java
deleted file mode 100644 (file)
index a93d48a..0000000
+++ /dev/null
@@ -1,248 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import static com.google.common.base.Preconditions.checkArgument;
-
-import java.io.InputStream;
-import java.net.URI;
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Deque;
-
-import javax.xml.stream.XMLEventReader;
-import javax.xml.stream.XMLInputFactory;
-import javax.xml.stream.XMLStreamException;
-import javax.xml.stream.events.Characters;
-import javax.xml.stream.events.StartElement;
-import javax.xml.stream.events.XMLEvent;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-
-/**
- * The XML Tree Builder is builder utility class designed to facilitate of
- * loading, reading and parsing XML documents into YANG DOM represented by
- * yang-data-api. <br>
- * The method {@link #buildDataTree(InputStream)} is designed to take and parse
- * XML as {@link InputStream}. The output of the operation SHOULD be root
- * <code>CompositeNode</code> or <code>SimpleElement</code> depends by which
- * element XML begins. The XML header is omitted by XML parser.
- *
- * @author Lukas Sedlak
- *
- * @see CompositeNode
- * @see SimpleNode
- * @see Node
- */
-public final class XmlTreeBuilder {
-    private final static XMLInputFactory XML_INPUT_FACTORY = XMLInputFactory.newInstance();
-
-    private XmlTreeBuilder() {
-    }
-
-    /**
-     * The method is designed to take and parse XML as {@link InputStream}. The
-     * output of the operation SHOULD be root <code>CompositeNode</code> or
-     * <code>SimpleElement</code> depends on element that XML document begins.
-     * The XML header is omitted by XML parser.
-     *
-     * @param inputStream
-     *            XML Input Stream
-     * @return root <code>Node</code> element conformant to XML start element in
-     *         most cases it will be CompositeNode which contains child Nodes
-     * @throws XMLStreamException
-     */
-    public static Node<?> buildDataTree(final InputStream inputStream) throws XMLStreamException {
-        final XMLEventReader eventReader = XML_INPUT_FACTORY.createXMLEventReader(inputStream);
-
-        final Deque<Node<?>> processingQueue = new ArrayDeque<>();
-        Node<?> parentNode = null;
-        Node<?> root = null;
-        while (eventReader.hasNext()) {
-            final XMLEvent event = eventReader.nextEvent();
-
-            if (event.isStartElement()) {
-                final StartElement startElement = event.asStartElement();
-                if (!processingQueue.isEmpty()) {
-                    parentNode = processingQueue.peek();
-                }
-                MutableCompositeNode compParentNode = null;
-                if (parentNode instanceof MutableCompositeNode) {
-                    compParentNode = (MutableCompositeNode) parentNode;
-                }
-                Node<?> newNode = null;
-                if (isCompositeNodeEvent(eventReader, event)) {
-                    newNode = resolveCompositeNodeFromStartElement(startElement, compParentNode);
-                } else if (isSimpleNodeEvent(eventReader, event)) {
-                    newNode = resolveSimpleNodeFromStartElement(eventReader, startElement, compParentNode);
-                }
-
-                if (newNode != null) {
-                    processingQueue.push(newNode);
-                    if (compParentNode != null) {
-                        compParentNode.getValue().add(newNode);
-                    }
-                }
-            } else if (event.isEndElement()) {
-                root = processingQueue.pop();
-                if (root instanceof MutableCompositeNode) {
-                    ((MutableCompositeNode) root).init();
-                }
-            }
-        }
-        return root;
-    }
-
-    /**
-     * Checks if the XMLEvent is compliant to SimpleNode tag that contains only
-     * characters value. If the SimpleNode is composed only by empty XML tag
-     * (i.e. {@code <emptyTag />} or {@code<emptyTag></emptyTag>}) the result
-     * will be also <code>true</code>.
-     *
-     * @param event
-     *            actual XMLEvent that is processed
-     * @return <code>true</code> only and only if the XMLEvent Start Element is
-     *         Simple element tag and contains character values or is empty XML
-     *         tag.
-     * @throws XMLStreamException
-     *
-     * @see SimpleNode
-     */
-    private static boolean isSimpleNodeEvent(final XMLEventReader eventReader, final XMLEvent event) throws XMLStreamException {
-        checkArgument(event != null, "XML Event cannot be NULL!");
-        if (event.isStartElement()) {
-            if (eventReader.hasNext()) {
-                final XMLEvent innerEvent;
-                innerEvent = eventReader.peek();
-                if (innerEvent.isCharacters()) {
-                    final Characters chars = innerEvent.asCharacters();
-                    if (!chars.isWhiteSpace()) {
-                        return true;
-                    }
-                } else if (innerEvent.isEndElement()) {
-                    return true;
-                }
-            }
-        }
-        return false;
-    }
-
-    /**
-     * Checks if XMLEvent is equivalent to CompositeNode Event. The
-     * CompositeNode Event is XML element that conforms to the XML element that
-     * contains 1..N XML child elements. (i.e. {@code <compositeNode>
-     *         <simpleNode>data</simpleNode>
-     * </compositeNode>})
-     *
-     * @param event
-     *            actual XMLEvent that is processed
-     * @return <code>true</code> only if XML Element contains 1..N child
-     *         elements, otherwise returns <code>false</code>
-     * @throws XMLStreamException
-     *
-     * @see CompositeNode
-     */
-    private static boolean isCompositeNodeEvent(final XMLEventReader eventReader, final XMLEvent event) throws XMLStreamException {
-        checkArgument(event != null, "XML Event cannot be NULL!");
-        if (event.isStartElement()) {
-            if (eventReader.hasNext()) {
-                XMLEvent innerEvent;
-                innerEvent = eventReader.peek();
-                if (innerEvent.isCharacters()) {
-                    Characters chars = innerEvent.asCharacters();
-                    if (chars.isWhiteSpace()) {
-                        eventReader.nextEvent();
-                        innerEvent = eventReader.peek();
-                    }
-                }
-                if (innerEvent.isStartElement()) {
-                    return true;
-                }
-            }
-        }
-        return false;
-    }
-
-    /**
-     * Creates and returns <code>SimpleNode</code> instance from actually
-     * processed XML Start Element.
-     *
-     * @param startElement
-     *            actual XML Start Element that is processed
-     * @param parent
-     *            Parent CompositeNode
-     * @return <code>new SimpleNode</code> instance from actually processed XML
-     *         Start Element
-     * @throws XMLStreamException
-     *
-     * @see SimpleNode
-     */
-    private static SimpleNode<String> resolveSimpleNodeFromStartElement(final XMLEventReader eventReader,
-            final StartElement startElement, final CompositeNode parent) throws XMLStreamException {
-        checkArgument(startElement != null, "Start Element cannot be NULL!");
-        String data = null;
-
-        if (eventReader.hasNext()) {
-            final XMLEvent innerEvent = eventReader.peek();
-            if (innerEvent.isCharacters()) {
-                final Characters chars = innerEvent.asCharacters();
-                if (!chars.isWhiteSpace()) {
-                    data = innerEvent.asCharacters().getData();
-                }
-            } else if (innerEvent.isEndElement()) {
-                data = "";
-            }
-        }
-        return NodeFactory.createImmutableSimpleNode(resolveElementQName(startElement), parent, data);
-    }
-
-    /**
-     * Creates and returns <code>MutableCompositeNode</code> instance from
-     * actually processed XML Start Element.
-     *
-     * @param startElement
-     *            actual XML Start Element that is processed
-     * @param parent
-     *            Parent CompositeNode
-     * @return <code>new MutableCompositeNode</code> instance from actually
-     *         processed XML Start Element
-     *
-     * @see CompositeNode
-     * @see MutableCompositeNode
-     */
-    private static MutableCompositeNode resolveCompositeNodeFromStartElement(final StartElement startElement,
-            final CompositeNode parent) {
-        checkArgument(startElement != null, "Start Element cannot be NULL!");
-
-        return NodeFactory.createMutableCompositeNode(resolveElementQName(startElement), parent,
-                new ArrayList<Node<?>>(), ModifyAction.CREATE, null);
-    }
-
-    /**
-     * Extract and retrieve XML Element QName to OpenDaylight QName.
-     *
-     * @param element
-     *            Start Element
-     * @return QName instance composed of <code>elements</code> Namespace and
-     *         Local Part.
-     *
-     * @see QName
-     */
-    private static QName resolveElementQName(final StartElement element) {
-        checkArgument(element != null, "Start Element cannot be NULL!");
-
-        final String nsURI = element.getName().getNamespaceURI();
-        final String localName = element.getName().getLocalPart();
-        return new QName(URI.create(nsURI), localName);
-    }
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/AugmentationCodec.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/AugmentationCodec.java
deleted file mode 100644 (file)
index 191f080..0000000
+++ /dev/null
@@ -1,35 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.codec;
-
-import org.opendaylight.yangtools.yang.binding.Augmentation;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-public interface AugmentationCodec<A extends Augmentation<?>> extends DomCodec<A> {
-    @Override
-    CompositeNode serialize(ValueWithQName<A> input);
-
-    @Override
-    ValueWithQName<A> deserialize(Node<?> input);
-
-    QName getAugmentationQName();
-
-    /**
-     * Check if this codec was created for augmentation with given target node
-     * path.
-     *
-     * @param path
-     *            identifier of augmentation target node
-     * @return true, if this codec is generated for augmentation pointing node
-     *         with given path, false otherwise
-     */
-    boolean isAcceptable(InstanceIdentifier<?> path);
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/BindingIndependentMappingService.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/BindingIndependentMappingService.java
deleted file mode 100644 (file)
index e4a09a0..0000000
+++ /dev/null
@@ -1,117 +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.yangtools.yang.data.impl.codec;
-
-import java.util.Map.Entry;
-import java.util.Set;
-
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.binding.RpcService;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-
-import com.google.common.base.Optional;
-
-public interface BindingIndependentMappingService {
-
-    /**
-     * Get codec registry.
-     *
-     * @return codec registry
-     */
-    CodecRegistry getCodecRegistry();
-
-    /**
-     * Convert given DataObject data to DOM-like node.
-     *
-     * @param data
-     *            DataObject instance
-     * @return CompositeNode created from DataObject instance
-     */
-    CompositeNode toDataDom(DataObject data);
-
-    /**
-     * Create map entry representing node data (key = data schema node
-     * identifier, value = value is node data representation as Composite node)
-     * from entry representing node class (key = class object identifier, value
-     * = class object).
-     *
-     * @param entry
-     *            map entry, where key is class object identifier and value
-     *            class object
-     * @return data schema node identifier
-     */
-    Entry<org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier, CompositeNode> toDataDom(
-            Entry<InstanceIdentifier<? extends DataObject>, DataObject> entry);
-
-    /**
-     * Create data schema node identifier from class object identifier.
-     *
-     * @param path
-     *            class object identifier
-     * @return data schema node identifier
-     */
-    org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier toDataDom(InstanceIdentifier<? extends DataObject> path);
-
-    /**
-     * Create DataObject instance from CompositeNode data based on given path.
-     *
-     * @param path
-     *            node identifier
-     * @param result
-     *            node data
-     * @return inputClass instance created from composite node input
-     */
-    DataObject dataObjectFromDataDom(InstanceIdentifier<? extends DataObject> path, CompositeNode result)
-            throws DeserializationException;
-
-    /**
-     * Create class object identifier from data schema node identifier.
-     *
-     * @param entry
-     *            data schema node identifier
-     * @return class object identifier
-     */
-    InstanceIdentifier<?> fromDataDom(org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier entry)
-            throws DeserializationException;
-
-    /**
-     * Returns the list of currently-known QNames for instances of a service.
-     *
-     * @param service
-     *            RPC service
-     * @return List of QNames. The user may not modify this list.
-     */
-    Set<QName> getRpcQNamesFor(Class<? extends RpcService> service);
-
-    /**
-     * Get RpcService by namespace and revision.
-     *
-     * @param namespace
-     *            rpc service namespace
-     * @param revision
-     *            rpc service revision
-     * @return Optional reference on RpcServices based on given namespace and
-     *         revision
-     */
-    Optional<Class<? extends RpcService>> getRpcServiceClassFor(String namespace, String revision);
-
-    /**
-     * Create inputClass instance from CompositeNode data.
-     *
-     * @param inputClass
-     *            expected type of resulting object
-     * @param domInput
-     *            node data
-     * @return inputClass instance created from composite node input
-     */
-    DataContainer dataObjectFromDataDom(Class<? extends DataContainer> inputClass, CompositeNode domInput);
-
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/ChoiceCaseCodec.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/ChoiceCaseCodec.java
deleted file mode 100644 (file)
index 0db5728..0000000
+++ /dev/null
@@ -1,22 +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.yangtools.yang.data.impl.codec;
-
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-public interface ChoiceCaseCodec<C extends DataContainer> extends DataContainerCodec<C> {
-    @Override
-    CompositeNode serialize(ValueWithQName<C> input);
-
-    @Override
-    ValueWithQName<C> deserialize(Node<?> input);
-
-    boolean isAcceptable(Node<?> input);
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/ChoiceCodec.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/ChoiceCodec.java
deleted file mode 100644 (file)
index 4355956..0000000
+++ /dev/null
@@ -1,18 +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.yangtools.yang.data.impl.codec;
-
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-public interface ChoiceCodec<C> extends DomCodec<C> {
-    @Override
-    Node<?> serialize(ValueWithQName<C> input);
-
-    @Override
-    ValueWithQName<C> deserialize(Node<?> input);
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/CodecRegistry.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/CodecRegistry.java
deleted file mode 100644 (file)
index 50a40b2..0000000
+++ /dev/null
@@ -1,45 +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.yangtools.yang.data.impl.codec;
-
-import java.util.List;
-
-import org.opendaylight.yangtools.concepts.Identifiable;
-import org.opendaylight.yangtools.yang.binding.Augmentation;
-import org.opendaylight.yangtools.yang.binding.BaseIdentity;
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.opendaylight.yangtools.yang.binding.Identifier;
-import org.opendaylight.yangtools.yang.common.QName;
-
-public interface CodecRegistry {
-
-    InstanceIdentifierCodec getInstanceIdentifierCodec();
-
-    IdentityCodec<?> getIdentityCodec();
-
-    <T extends DataContainer> DataContainerCodec<T> getCodecForDataObject(Class<T> object);
-
-    <T extends Identifiable<?>> IdentifierCodec<?> getIdentifierCodecForIdentifiable(Class<T> object);
-
-    <T extends Identifier<?>> IdentifierCodec<T> getCodecForIdentifier(Class<T> object);
-
-    <T extends Augmentation<?>> AugmentationCodec<T> getCodecForAugmentation(Class<T> object);
-
-    <T extends BaseIdentity> IdentityCodec<T> getCodecForIdentity(Class<T> codec);
-
-    Class<?> getClassForPath(List<QName> names);
-
-    IdentifierCodec<?> getKeyCodecForPath(List<QName> names);
-
-
-    void bindingClassEncountered(Class<?> cls);
-
-    void putPathToClass(List<QName> names, Class<?> cls);
-
-    QName getQNameForAugmentation(Class<?> cls);
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/DataContainerCodec.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/DataContainerCodec.java
deleted file mode 100644 (file)
index aaa51ce..0000000
+++ /dev/null
@@ -1,25 +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.yangtools.yang.data.impl.codec;
-
-import org.opendaylight.yangtools.yang.binding.DataContainer;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-public interface DataContainerCodec<T extends DataContainer> extends DomCodec<T> {
-
-    @Override
-    CompositeNode serialize(ValueWithQName<T> input);
-
-    @Override
-    ValueWithQName<T> deserialize(Node<?> input);
-
-    ValueWithQName<T> deserialize(Node<?> input, InstanceIdentifier<?> bindingIdentifier);
-
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/DomCodec.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/DomCodec.java
deleted file mode 100644 (file)
index 6f6fdf0..0000000
+++ /dev/null
@@ -1,19 +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.yangtools.yang.data.impl.codec;
-
-import org.opendaylight.yangtools.yang.binding.BindingCodec;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-public interface DomCodec<I> extends BindingCodec<Node<?>, ValueWithQName<I>>{
-    @Override
-    Node<?> serialize(ValueWithQName<I> input);
-
-    @Override
-    ValueWithQName<I> deserialize(Node<?> input);
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/IdentifierCodec.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/IdentifierCodec.java
deleted file mode 100644 (file)
index 99645a3..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.codec;
-
-import org.opendaylight.yangtools.yang.binding.Identifier;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-public interface IdentifierCodec<I extends Identifier<?>> extends DomCodec<I> {
-    @Override
-    ValueWithQName<I> deserialize(Node<?> input);
-
-    @Override
-    CompositeNode serialize(ValueWithQName<I> input);
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/InstanceIdentifierCodec.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/codec/InstanceIdentifierCodec.java
deleted file mode 100644 (file)
index de7949b..0000000
+++ /dev/null
@@ -1,20 +0,0 @@
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.codec;
-
-import org.opendaylight.yangtools.yang.binding.BindingCodec;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-
-public interface InstanceIdentifierCodec extends BindingCodec<YangInstanceIdentifier, InstanceIdentifier<?>> {
-    @Override
-    YangInstanceIdentifier serialize(InstanceIdentifier<?> input);
-
-    @Override
-    InstanceIdentifier<?> deserialize(YangInstanceIdentifier input);
-}
index 134557b7c9e544ac1e6706138fc4c88581d95f79..7ff31d693507d5eb04e6da5477c875d4917cd746 100644 (file)
@@ -22,12 +22,11 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdent
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.AugmentationSchemaProxy;
 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
@@ -36,9 +35,11 @@ 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.NotificationDefinition;
+import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -65,16 +66,28 @@ public final class SchemaTracker {
 
                 if(child == null && current instanceof SchemaContext) {
                     child = tryFindNotification((SchemaContext) current, qname)
-                            .orNull();
+                            .or(tryFindRpc(((SchemaContext) current), qname)).orNull();
+                }
+            } else if (current instanceof ChoiceSchemaNode) {
+                child = ((ChoiceSchemaNode) current).getCaseNodeByName(qname);
+            } else if (current instanceof RpcDefinition) {
+                switch (qname.getLocalName()) {
+                    case "input":
+                        child = ((RpcDefinition) current).getInput();
+                        break;
+                    case "output":
+                        child = ((RpcDefinition) current).getOutput();
+                        break;
+                    default:
+                        child = null;
+                        break;
                 }
-            } else if (current instanceof ChoiceNode) {
-                child = ((ChoiceNode) current).getCaseNodeByName(qname);
             } else {
                 throw new IllegalArgumentException(String.format("Schema node %s does not allow children.", current));
             }
             current = child;
         }
-        Preconditions.checkArgument(current instanceof DataNodeContainer,"Schema path must point to container or list. Supplied path %s pointed to: %s",path,current);
+        Preconditions.checkArgument(current instanceof DataNodeContainer,"Schema path must point to container or list or an rpc input/output. Supplied path %s pointed to: %s",path,current);
         root = (DataNodeContainer) current;
     }
 
@@ -82,6 +95,10 @@ public final class SchemaTracker {
         return Optional.<SchemaNode> fromNullable(Iterables.find(ctx.getGroupings(), new SchemaNodePredicate(qname), null));
     }
 
+    private Optional<SchemaNode> tryFindRpc(final SchemaContext ctx, final QName qname) {
+        return Optional.<SchemaNode>fromNullable(Iterables.find(ctx.getOperations(), new SchemaNodePredicate(qname), null));
+    }
+
     private Optional<SchemaNode> tryFindNotification(final SchemaContext ctx, final QName qname) {
         return Optional.<SchemaNode>fromNullable(Iterables.find(ctx.getNotifications(), new SchemaNodePredicate(qname), null));
     }
@@ -129,14 +146,8 @@ public final class SchemaTracker {
             if(schema == null && parent instanceof NotificationDefinition) {
                 schema = ((NotificationDefinition) parent);
             }
-        } else if(parent instanceof ChoiceNode) {
-            for(final ChoiceCaseNode caze : ((ChoiceNode) parent).getCases()) {
-                final DataSchemaNode potential = caze.getDataChildByName(qname);
-                if(potential != null) {
-                    schema = potential;
-                    break;
-                }
-            }
+        } else if(parent instanceof ChoiceSchemaNode) {
+            schema = findChildInCases((ChoiceSchemaNode) parent, qname);
         } else {
             throw new IllegalStateException("Unsupported schema type "+ parent.getClass() +" on stack.");
         }
@@ -144,6 +155,30 @@ public final class SchemaTracker {
         return schema;
     }
 
+    private SchemaNode findChildInCases(final ChoiceSchemaNode parent, final QName qname) {
+        DataSchemaNode schema = null;
+        for(final ChoiceCaseNode caze : parent.getCases()) {
+            final DataSchemaNode potential = caze.getDataChildByName(qname);
+            if(potential != null) {
+                schema = potential;
+                break;
+            }
+        }
+        return schema;
+    }
+
+    private SchemaNode findCaseByChild(final ChoiceSchemaNode parent, final QName qname) {
+        DataSchemaNode schema = null;
+        for(final ChoiceCaseNode caze : parent.getCases()) {
+            final DataSchemaNode potential = caze.getDataChildByName(qname);
+            if(potential != null) {
+                schema = caze;
+                break;
+            }
+        }
+        return schema;
+    }
+
     public void startList(final PathArgument name) {
         final SchemaNode schema = getSchema(name);
         Preconditions.checkArgument(schema instanceof ListSchemaNode, "Node %s is not a list", schema.getPath());
@@ -178,13 +213,13 @@ public final class SchemaTracker {
         return (LeafListSchemaNode) parent;
     }
 
-    public ChoiceNode startChoiceNode(final NodeIdentifier name) {
+    public ChoiceSchemaNode startChoiceNode(final NodeIdentifier name) {
         LOG.debug("Enter choice {}", name);
         final SchemaNode schema = getSchema(name);
 
-        Preconditions.checkArgument(schema instanceof ChoiceNode, "Node %s is not a choice", schema.getPath());
+        Preconditions.checkArgument(schema instanceof ChoiceSchemaNode, "Node %s is not a choice", schema.getPath());
         schemaStack.push(schema);
-        return (ChoiceNode)schema;
+        return (ChoiceSchemaNode)schema;
     }
 
     public SchemaNode startContainerNode(final NodeIdentifier name) {
@@ -201,16 +236,20 @@ public final class SchemaTracker {
 
     public AugmentationSchema startAugmentationNode(final AugmentationIdentifier identifier) {
         LOG.debug("Enter augmentation {}", identifier);
-        final Object parent = getParent();
+        Object parent = getParent();
 
         Preconditions.checkArgument(parent instanceof AugmentationTarget, "Augmentation not allowed under %s", parent);
+        if(parent instanceof ChoiceSchemaNode) {
+            final QName name = Iterables.get(identifier.getPossibleChildNames(), 0);
+            parent = findCaseByChild((ChoiceSchemaNode) parent, name);
+        }
         Preconditions.checkArgument(parent instanceof DataNodeContainer, "Augmentation allowed only in DataNodeContainer",parent);
         final AugmentationSchema schema = SchemaUtils.findSchemaForAugment((AugmentationTarget) parent, identifier.getPossibleChildNames());
         final HashSet<DataSchemaNode> realChildSchemas = new HashSet<>();
         for(final DataSchemaNode child : schema.getChildNodes()) {
             realChildSchemas.add(((DataNodeContainer) parent).getDataChildByName(child.getQName()));
         }
-        final AugmentationSchema resolvedSchema = new AugmentationSchemaProxy(schema, realChildSchemas);
+        final AugmentationSchema resolvedSchema = new EffectiveAugmentationSchema(schema, realChildSchemas);
         schemaStack.push(resolvedSchema);
         return resolvedSchema;
     }
index 11944faad8d136a4a2b0d2eed484abd9aa88195c..150189ae1183f7e9bae2ccbc391860c1808f784e 100644 (file)
@@ -8,11 +8,10 @@
 package org.opendaylight.yangtools.yang.data.impl.codec.xml;
 
 import com.google.common.base.Preconditions;
-
 import java.net.URI;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.util.AbstractStringInstanceIdentifierCodec;
+import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.w3c.dom.Element;
@@ -20,10 +19,12 @@ import org.w3c.dom.Element;
 final class ElementInstanceIdentifierParser extends AbstractStringInstanceIdentifierCodec {
     private final SchemaContext schema;
     private final Element element;
+    private final DataSchemaContextTree dataContextTree;
 
     ElementInstanceIdentifierParser(final SchemaContext schema, final Element element) {
         this.element = Preconditions.checkNotNull(element);
         this.schema = Preconditions.checkNotNull(schema);
+        this.dataContextTree = DataSchemaContextTree.from(schema);
     }
 
     @Override
@@ -42,4 +43,9 @@ final class ElementInstanceIdentifierParser extends AbstractStringInstanceIdenti
         return QName.create(module.getQNameModule(), localName);
     }
 
+    @Override
+    protected DataSchemaContextTree getDataContextTree() {
+        return dataContextTree;
+    }
+
 }
index 563641fd68161f87e7e2cdc401469880ee107100..ce304c82eb74dc878f50ecd45a200df25fd216d2 100644 (file)
@@ -24,8 +24,8 @@ public final class InstanceIdentifierForXmlCodec {
         return codec.deserialize(element.getTextContent().trim());
     }
 
-    public static Element serialize(final YangInstanceIdentifier id, final Element element) {
-        final RandomPrefixInstanceIdentifierSerializer codec = new RandomPrefixInstanceIdentifierSerializer();
+    public static Element serialize(final YangInstanceIdentifier id, final Element element, SchemaContext context) {
+        final RandomPrefixInstanceIdentifierSerializer codec = new RandomPrefixInstanceIdentifierSerializer(context);
         final String str = codec.serialize(id);
 
         for (Entry<URI, String> e : codec.getPrefixes()) {
@@ -35,6 +35,15 @@ public final class InstanceIdentifierForXmlCodec {
         return element;
     }
 
+    /**
+     *
+     * @deprecated USe {@link #serialize(YangInstanceIdentifier, Element, SchemaContext)} instead.
+     */
+    @Deprecated
+    public static Element serialize(final YangInstanceIdentifier id, final Element element) {
+        throw new UnsupportedOperationException("Not supported, due to buggy API contract.");
+    }
+
     private static String getIdAndPrefixAsStr(final String pathPart) {
         int predicateStartIndex = pathPart.indexOf('[');
         return predicateStartIndex == -1 ? pathPart : pathPart.substring(0, predicateStartIndex);
index a6fa1c0c5117604ea9ddf568d7879e48c0cd426c..9c2c613ebfb806a9915fec988c3ad17a8403acd3 100644 (file)
@@ -9,12 +9,19 @@ package org.opendaylight.yangtools.yang.data.impl.codec.xml;
 
 import java.net.URI;
 import java.util.Map;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.util.AbstractStringInstanceIdentifierCodec;
+import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 
 final class RandomPrefixInstanceIdentifierSerializer extends AbstractStringInstanceIdentifierCodec {
     private final RandomPrefix prefixes = new RandomPrefix();
+    private final DataSchemaContextTree schemaTree;
+
+
+    RandomPrefixInstanceIdentifierSerializer(SchemaContext ctx) {
+        schemaTree = DataSchemaContextTree.from(ctx);
+    }
 
     Iterable<Map.Entry<URI, String>> getPrefixes() {
         return prefixes.getPrefixes();
@@ -30,4 +37,9 @@ final class RandomPrefixInstanceIdentifierSerializer extends AbstractStringInsta
         throw new UnsupportedOperationException("Not implemented");
     }
 
+    @Override
+    protected DataSchemaContextTree getDataContextTree() {
+        return schemaTree;
+    }
+
 }
index ddc8076d612cd2b4af752920655b9fed58729a4c..66b36fc71f988e8b6bb379881b4a2b2cb7b1aeda 100644 (file)
@@ -7,18 +7,30 @@
  */
 package org.opendaylight.yangtools.yang.data.impl.codec.xml;
 
-import static javax.xml.XMLConstants.DEFAULT_NS_PREFIX;
-
 import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
 import java.io.IOException;
+import java.io.StringWriter;
+import java.util.Map;
+import javax.xml.XMLConstants;
+import java.io.StringWriter;
+import javax.xml.namespace.NamespaceContext;
 import javax.xml.stream.XMLStreamException;
 import javax.xml.stream.XMLStreamWriter;
+import javax.xml.transform.OutputKeys;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.TransformerFactoryConfigurationError;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stax.StAXResult;
+import javax.xml.transform.stream.StreamResult;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamAttributeWriter;
 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
 import org.opendaylight.yangtools.yang.data.impl.codec.SchemaTracker;
 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
@@ -30,21 +42,26 @@ import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.w3c.dom.Element;
 
 /**
  * A {@link NormalizedNodeStreamWriter} which translates the events into an
  * {@link XMLStreamWriter}, resulting in a RFC 6020 XML encoding.
  */
-public final class XMLStreamNormalizedNodeStreamWriter implements NormalizedNodeStreamWriter {
+public final class XMLStreamNormalizedNodeStreamWriter implements NormalizedNodeStreamAttributeWriter {
+
+    private static final TransformerFactory TRANSFORMER_FACTORY = TransformerFactory.newInstance();
 
     private final XMLStreamWriter writer;
     private final SchemaTracker tracker;
     private final XmlStreamUtils streamUtils;
+    private RandomPrefix randomPrefix;
 
     private XMLStreamNormalizedNodeStreamWriter(final XMLStreamWriter writer, final SchemaContext context, final SchemaPath path) {
         this.writer = Preconditions.checkNotNull(writer);
         this.tracker = SchemaTracker.create(context, path);
         this.streamUtils = XmlStreamUtils.create(XmlUtils.DEFAULT_XML_CODEC_PROVIDER, context);
+        randomPrefix = new RandomPrefix();
     }
 
     /**
@@ -72,9 +89,9 @@ public final class XMLStreamNormalizedNodeStreamWriter implements NormalizedNode
 
     private void writeStartElement( QName qname) throws XMLStreamException {
         String ns = qname.getNamespace().toString();
-        writer.writeStartElement(DEFAULT_NS_PREFIX, qname.getLocalName(), ns);
+        writer.writeStartElement(XMLConstants.DEFAULT_NS_PREFIX, qname.getLocalName(), ns);
         if(writer.getNamespaceContext() != null) {
-            String parentNs = writer.getNamespaceContext().getNamespaceURI(DEFAULT_NS_PREFIX);
+            String parentNs = writer.getNamespaceContext().getNamespaceURI(XMLConstants.DEFAULT_NS_PREFIX);
             if (!ns.equals(parentNs)) {
                 writer.writeDefaultNamespace(ns);
             }
@@ -105,6 +122,19 @@ public final class XMLStreamNormalizedNodeStreamWriter implements NormalizedNode
         }
     }
 
+    private void writeElement(final QName qname, final SchemaNode schemaNode, final Object value, final Map<QName, String> attributes) throws IOException {
+        try {
+            writeStartElement(qname);
+            writeAttributes(attributes);
+            if (value != null) {
+                streamUtils.writeValue(writer, schemaNode, value);
+            }
+            writer.writeEndElement();
+        } catch (XMLStreamException e) {
+            throw new IOException("Failed to emit element", e);
+        }
+    }
+
     private void startElement(final QName qname) throws IOException {
         try {
             writeStartElement(qname);
@@ -128,6 +158,52 @@ public final class XMLStreamNormalizedNodeStreamWriter implements NormalizedNode
         writeElement(schema.getQName(), schema, value);
     }
 
+    @Override
+    public void leafNode(final NodeIdentifier name, final Object value, final Map<QName, String> attributes) throws IOException {
+        final LeafSchemaNode schema = tracker.leafNode(name);
+        writeElement(schema.getQName(), schema, value, attributes);
+    }
+
+    @Override
+    public void leafSetEntryNode(final Object value, final Map<QName, String> attributes) throws IOException, IllegalArgumentException {
+        final LeafListSchemaNode schema = tracker.leafSetEntryNode();
+        writeElement(schema.getQName(), schema, value, attributes);
+    }
+
+    @Override
+    public void startContainerNode(final NodeIdentifier name, final int childSizeHint, final Map<QName, String> attributes) throws IOException, IllegalArgumentException {
+        startContainerNode(name, childSizeHint);
+        writeAttributes(attributes);
+    }
+
+    @Override
+    public void startUnkeyedListItem(final NodeIdentifier name, final int childSizeHint, final Map<QName, String> attributes) throws IOException, IllegalStateException {
+        startUnkeyedListItem(name, childSizeHint);
+        writeAttributes(attributes);
+    }
+
+    @Override
+    public void startMapEntryNode(final NodeIdentifierWithPredicates identifier, final int childSizeHint, final Map<QName, String> attributes) throws IOException, IllegalArgumentException {
+        startMapEntryNode(identifier, childSizeHint);
+        writeAttributes(attributes);
+    }
+
+    private void writeAttributes(final Map<QName, String> attributes) throws IOException {
+        for (final Map.Entry<QName, String> qNameStringEntry : attributes.entrySet()) {
+            try {
+                final String namespace = qNameStringEntry.getKey().getNamespace().toString();
+                if(Strings.isNullOrEmpty(namespace)) {
+                    writer.writeAttribute(qNameStringEntry.getKey().getLocalName(), qNameStringEntry.getValue());
+                } else {
+                    final String prefix = randomPrefix.encodePrefix(qNameStringEntry.getKey().getNamespace());
+                    writer.writeAttribute(prefix, namespace, qNameStringEntry.getKey().getLocalName(), qNameStringEntry.getValue());
+                }
+            } catch (final XMLStreamException e) {
+                throw new IOException("Unable to emit attribute " + qNameStringEntry, e);
+            }
+        }
+    }
+
     @Override
     public void startLeafSet(final NodeIdentifier name, final int childSizeHint) {
         tracker.startLeafSet(name);
@@ -183,15 +259,37 @@ public final class XMLStreamNormalizedNodeStreamWriter implements NormalizedNode
     @Override
     public void anyxmlNode(final NodeIdentifier name, final Object value) throws IOException {
         final AnyXmlSchemaNode schema = tracker.anyxmlNode(name);
-        final QName qname = schema.getQName();
-        try {
-            writeStartElement(qname);
-            if (value != null) {
-                streamUtils.writeValue(writer, (Node<?>)value, schema);
+        if (value != null) {
+            Preconditions.checkArgument(value instanceof DOMSource, "AnyXML value must be DOMSource, not %s", value);
+            final QName qname = schema.getQName();
+            final DOMSource domSource = (DOMSource) value;
+            Preconditions.checkNotNull(domSource.getNode());
+            Preconditions.checkArgument(domSource.getNode().getNodeName().equals(qname.getLocalName()));
+            Preconditions.checkArgument(domSource.getNode().getNamespaceURI().equals(qname.getNamespace().toString()));
+            try {
+                // TODO can the transformer be a constant ? is it thread safe ?
+                final Transformer transformer = TRANSFORMER_FACTORY.newTransformer();
+                // Writer has to be wrapped in a wrapper that ignores endDocument event
+                // EndDocument event forbids any other modification to the writer so a nested anyXml breaks serialization
+                transformer.transform(domSource, new StAXResult(new DelegateWriterNoEndDoc(writer)));
+            } catch (final TransformerException e) {
+                throw new IOException("Unable to transform anyXml(" + name + ") value: " + value, e);
             }
-            writer.writeEndElement();
-        } catch (XMLStreamException e) {
-            throw new IOException("Failed to emit element", e);
+        }
+    }
+
+    public static String toString(final Element xml) {
+        try {
+            final Transformer transformer = TransformerFactory.newInstance().newTransformer();
+            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
+
+            final StreamResult result = new StreamResult(new StringWriter());
+            final DOMSource source = new DOMSource(xml);
+            transformer.transform(source, result);
+
+            return result.getWriter().toString();
+        } catch (IllegalArgumentException | TransformerFactoryConfigurationError | TransformerException e) {
+            throw new RuntimeException("Unable to serialize xml element " + xml, e);
         }
     }
 
@@ -232,4 +330,181 @@ public final class XMLStreamNormalizedNodeStreamWriter implements NormalizedNode
             throw new IOException("Failed to flush writer", e);
         }
     }
+
+    /**
+     * Delegate writer that ignores writeEndDocument event. Used for AnyXml serialization.
+     */
+    private static final class DelegateWriterNoEndDoc implements XMLStreamWriter {
+        private final XMLStreamWriter writer;
+
+        public DelegateWriterNoEndDoc(final XMLStreamWriter writer) {
+            this.writer = writer;
+        }
+
+        @Override
+        public void writeStartElement(final String localName) throws XMLStreamException {
+            writer.writeStartElement(localName);
+        }
+
+        @Override
+        public void writeStartElement(final String namespaceURI, final String localName) throws XMLStreamException {
+            writer.writeStartElement(namespaceURI, localName);
+        }
+
+        @Override
+        public void writeStartElement(final String prefix, final String localName, final String namespaceURI) throws XMLStreamException {
+            writer.writeStartElement(prefix, localName, namespaceURI);
+        }
+
+        @Override
+        public void writeEmptyElement(final String namespaceURI, final String localName) throws XMLStreamException {
+            writer.writeEmptyElement(namespaceURI, localName);
+        }
+
+        @Override
+        public void writeEmptyElement(final String prefix, final String localName, final String namespaceURI) throws XMLStreamException {
+            writer.writeEmptyElement(prefix, localName, namespaceURI);
+        }
+
+        @Override
+        public void writeEmptyElement(final String localName) throws XMLStreamException {
+            writer.writeEmptyElement(localName);
+        }
+
+        @Override
+        public void writeEndElement() throws XMLStreamException {
+            writer.writeEndElement();
+
+        }
+
+        @Override
+        public void writeEndDocument() throws XMLStreamException {
+            // End document is disabled
+        }
+
+        @Override
+        public void close() throws XMLStreamException {
+            writer.close();
+        }
+
+        @Override
+        public void flush() throws XMLStreamException {
+            writer.flush();
+        }
+
+        @Override
+        public void writeAttribute(final String localName, final String value) throws XMLStreamException {
+            writer.writeAttribute(localName, value);
+        }
+
+        @Override
+        public void writeAttribute(final String prefix, final String namespaceURI, final String localName, final String value) throws XMLStreamException {
+            writer.writeAttribute(prefix, namespaceURI, localName, value);
+        }
+
+        @Override
+        public void writeAttribute(final String namespaceURI, final String localName, final String value) throws XMLStreamException {
+            writer.writeAttribute(namespaceURI, localName, value);
+        }
+
+        @Override
+        public void writeNamespace(final String prefix, final String namespaceURI) throws XMLStreamException {
+            // Workaround for default namespace
+            // If a namespace is not prefixed, it is is still treated as prefix namespace. This results in the NamespaceSupport class ignoring the namespace since xmlns is not a valid prefix
+            // Write the namespace at least as an attribute
+            // TODO this is a hotfix, the transformer itself should write namespaces passing the namespace in writeStartElement method
+            if (prefix.equals("xml") || prefix.equals("xmlns")) {
+                writer.writeAttribute(prefix, namespaceURI);
+            } else {
+                writer.writeNamespace(prefix, namespaceURI);
+            }
+        }
+
+        @Override
+        public void writeDefaultNamespace(final String namespaceURI) throws XMLStreamException {
+            writer.writeDefaultNamespace(namespaceURI);
+        }
+
+        @Override
+        public void writeComment(final String data) throws XMLStreamException {
+            writer.writeComment(data);
+        }
+
+        @Override
+        public void writeProcessingInstruction(final String target) throws XMLStreamException {
+            writer.writeProcessingInstruction(target);
+        }
+
+        @Override
+        public void writeProcessingInstruction(final String target, final String data) throws XMLStreamException {
+            writer.writeProcessingInstruction(target, data);
+        }
+
+        @Override
+        public void writeCData(final String data) throws XMLStreamException {
+            writer.writeCData(data);
+        }
+
+        @Override
+        public void writeDTD(final String dtd) throws XMLStreamException {
+            writer.writeDTD(dtd);
+        }
+
+        @Override
+        public void writeEntityRef(final String name) throws XMLStreamException {
+            writer.writeEntityRef(name);
+        }
+
+        @Override
+        public void writeStartDocument() throws XMLStreamException {
+        }
+
+        @Override
+        public void writeStartDocument(final String version) throws XMLStreamException {
+        }
+
+        @Override
+        public void writeStartDocument(final String encoding, final String version) throws XMLStreamException {
+        }
+
+        @Override
+        public void writeCharacters(final String text) throws XMLStreamException {
+            writer.writeCharacters(text);
+        }
+
+        @Override
+        public void writeCharacters(final char[] text, final int start, final int len) throws XMLStreamException {
+            writer.writeCharacters(text, start, len);
+        }
+
+        @Override
+        public String getPrefix(final String uri) throws XMLStreamException {
+            return writer.getPrefix(uri);
+        }
+
+        @Override
+        public void setPrefix(final String prefix, final String uri) throws XMLStreamException {
+            // Disabled since it causes exceptions in the underlying writer
+        }
+
+        @Override
+        public void setDefaultNamespace(final String uri) throws XMLStreamException {
+            writer.setDefaultNamespace(uri);
+        }
+
+        @Override
+        public void setNamespaceContext(final NamespaceContext context) throws XMLStreamException {
+            writer.setNamespaceContext(context);
+        }
+
+        @Override
+        public NamespaceContext getNamespaceContext() {
+            return writer.getNamespaceContext();
+        }
+
+        @Override
+        public Object getProperty(final String name) throws IllegalArgumentException {
+            return writer.getProperty(name);
+        }
+    }
 }
index 0301f699abe7a9ecfdc18727bb3d575601004a8e..24abc3507143ae36bc8c566d50035ce078d94ee4 100644 (file)
@@ -7,63 +7,27 @@
  */
 package org.opendaylight.yangtools.yang.data.impl.codec.xml;
 
-import static com.google.common.base.Preconditions.checkState;
-import com.google.common.base.Function;
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
-import com.google.common.base.Strings;
-import com.google.common.collect.ImmutableList;
 import java.net.URI;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
-import java.util.Objects;
-import java.util.Set;
-import javax.activation.UnsupportedDataTypeException;
-import javax.annotation.Nonnull;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.stream.XMLOutputFactory;
-import javax.xml.stream.XMLStreamException;
-import javax.xml.stream.XMLStreamWriter;
-import javax.xml.transform.dom.DOMResult;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.Node;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.impl.SimpleNodeTOImpl;
-import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
-import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
-import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
-import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaNode;
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
-import org.opendaylight.yangtools.yang.model.util.InstanceIdentifierType;
-import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
-import org.w3c.dom.NodeList;
 
 public final class XmlDocumentUtils {
 
@@ -71,86 +35,8 @@ public final class XmlDocumentUtils {
         throw new UnsupportedOperationException("Utility class should not be instantiated");
     }
 
-    private static class ElementWithSchemaContext {
-        Element element;
-        SchemaContext schemaContext;
-
-        ElementWithSchemaContext(final Element element,final SchemaContext schemaContext) {
-            this.schemaContext = schemaContext;
-            this.element = element;
-        }
-
-        Element getElement() {
-            return element;
-        }
-
-        SchemaContext getSchemaContext() {
-            return schemaContext;
-        }
-    }
-
     public static final QName OPERATION_ATTRIBUTE_QNAME = QName.create(SchemaContext.NAME, "operation");
-    private static final QName RPC_REPLY_QNAME = QName.create(SchemaContext.NAME, "rpc-reply");
     private static final Logger LOG = LoggerFactory.getLogger(XmlDocumentUtils.class);
-    private static final XMLOutputFactory FACTORY = XMLOutputFactory.newFactory();
-
-    /**
-     * Converts Data DOM structure to XML Document for specified XML Codec Provider and corresponding
-     * Data Node Container schema. The CompositeNode data parameter enters as root of Data DOM tree and will
-     * be transformed to root in XML Document. Each element of Data DOM tree is compared against specified Data
-     * Node Container Schema and transformed accordingly.
-     *
-     * @param data Data DOM root element
-     * @param schemaNode Data Node Container Schema
-     * @param codecProvider XML Codec Provider
-     * @return new instance of XML Document
-     * @throws UnsupportedDataTypeException
-     *
-     * @deprecated Use {@link #toDocument(org.opendaylight.yangtools.yang.data.api.CompositeNode, com.google.common.base.Optional, org.opendaylight.yangtools.yang.model.api.DataNodeContainer, XmlCodecProvider)} instead.
-     * The whole schema context allows for proper serialization of leafrefs.
-     */
-    @Deprecated
-    public static Document toDocument(final CompositeNode data, final DataNodeContainer schemaNode, final XmlCodecProvider codecProvider)
-            throws UnsupportedDataTypeException {
-        return toDocument(data, Optional.<SchemaContext>absent(), schemaNode, codecProvider);
-    }
-
-    /**
-     * Serializes data DOM node into a w3c DOM document. Whole schema context is used to resolve leafref elements.
-     *
-     * @param data Data DOM root element
-     * @param schemaContext Entire schema context for correct leafref resolution
-     * @param schemaNode Data Node Container Schema
-     * @param codecProvider XML Codec Provider
-     * @return serialized w3c DOM document
-     * @throws UnsupportedDataTypeException
-     */
-    public static Document toDocument(final CompositeNode data, final SchemaContext schemaContext, final DataNodeContainer schemaNode, final XmlCodecProvider codecProvider)
-            throws UnsupportedDataTypeException {
-        return toDocument(data, Optional.of(schemaContext), schemaNode, codecProvider);
-    }
-
-    private static Document toDocument(final CompositeNode data, final Optional<SchemaContext> schemaContext, final DataNodeContainer schema, final XmlCodecProvider codecProvider)
-            throws UnsupportedDataTypeException {
-        Preconditions.checkNotNull(data);
-        Preconditions.checkNotNull(schema);
-
-        if (!(schema instanceof ContainerSchemaNode || schema instanceof ListSchemaNode)) {
-            throw new UnsupportedDataTypeException("Schema can be ContainerSchemaNode or ListSchemaNode. Other types are not supported yet.");
-        }
-
-        final DOMResult result = new DOMResult(getDocument());
-        try {
-            final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
-            XmlStreamUtils xmlStreamUtils = schemaContext.isPresent() ? XmlStreamUtils.create(codecProvider, schemaContext.get()) : XmlStreamUtils.create(codecProvider);
-            xmlStreamUtils.writeDocument(writer, data, (SchemaNode) schema);
-            writer.close();
-            return (Document)result.getNode();
-        } catch (XMLStreamException e) {
-            LOG.error("Failed to serialize data {}", data, e);
-            return null;
-        }
-    }
 
     public static Document getDocument() {
         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
@@ -164,28 +50,6 @@ public final class XmlDocumentUtils {
         return doc;
     }
 
-    /**
-     * Converts Data DOM structure to XML Document for specified XML Codec Provider. The CompositeNode
-     * data parameter enters as root of Data DOM tree and will be transformed to root in XML Document. The child
-     * nodes of Data Tree are transformed accordingly.
-     *
-     * @param data Data DOM root element
-     * @param codecProvider XML Codec Provider
-     * @return new instance of XML Document
-     */
-    public static Document toDocument(final CompositeNode data, final XmlCodecProvider codecProvider) {
-        final DOMResult result = new DOMResult(getDocument());
-        try {
-            final XMLStreamWriter writer = FACTORY.createXMLStreamWriter(result);
-            XmlStreamUtils.create(codecProvider).writeDocument(writer, data);
-            writer.close();
-            return (Document)result.getNode();
-        } catch (XMLStreamException e) {
-            LOG.error("Failed to serialize data {}", data, e);
-            return null;
-        }
-    }
-
     private static final Element createElementFor(final Document doc, final QName qname, final Object obj) {
         final Element ret;
         if (qname.getNamespace() != null) {
@@ -208,103 +72,17 @@ public final class XmlDocumentUtils {
         return ret;
     }
 
-    public static Element createElementFor(final Document doc, final Node<?> data) {
-        return createElementFor(doc, data.getNodeType(), data);
-    }
-
     public static Element createElementFor(final Document doc, final NormalizedNode<?, ?> data) {
         return createElementFor(doc, data.getNodeType(), data);
     }
 
-    public static Node<?> toDomNode(final Element xmlElement, final Optional<DataSchemaNode> schema,
-            final Optional<XmlCodecProvider> codecProvider) {
-        return toDomNode(xmlElement, schema, codecProvider, Optional.<SchemaContext>absent());
-    }
-
-    public static Node<?> toDomNode(final Element xmlElement, final Optional<DataSchemaNode> schema,
-            final Optional<XmlCodecProvider> codecProvider, final Optional<SchemaContext> schemaContext) {
-        if (schema.isPresent()) {
-            if(schemaContext.isPresent()) {
-                return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(XmlUtils.DEFAULT_XML_CODEC_PROVIDER), schemaContext.get());
-            } else {
-                return toNodeWithSchema(xmlElement, schema.get(), codecProvider.or(XmlUtils.DEFAULT_XML_CODEC_PROVIDER));
-            }
-        }
-        return toDomNode(xmlElement);
-    }
-
     public static QName qNameFromElement(final Element xmlElement) {
         String namespace = xmlElement.getNamespaceURI();
         String localName = xmlElement.getLocalName();
         return QName.create(namespace != null ? URI.create(namespace) : null, null, localName);
     }
 
-    private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
-        checkQName(xmlElement, schema.getQName());
-        if (schema instanceof DataNodeContainer) {
-            return toCompositeNodeWithSchema(xmlElement, schema.getQName(), (DataNodeContainer) schema, codecProvider,schemaCtx);
-        } else if (schema instanceof LeafSchemaNode) {
-            return toSimpleNodeWithType(xmlElement, (LeafSchemaNode) schema, codecProvider,schemaCtx);
-        } else if (schema instanceof LeafListSchemaNode) {
-            return toSimpleNodeWithType(xmlElement, (LeafListSchemaNode) schema, codecProvider,schemaCtx);
-        } else if (schema instanceof AnyXmlSchemaNode) {
-            return toDomNode(xmlElement);
-        }
-        return null;
-    }
-
-    private static Node<?> toNodeWithSchema(final Element xmlElement, final DataSchemaNode schema, final XmlCodecProvider codecProvider) {
-        return toNodeWithSchema(xmlElement, schema, codecProvider, null);
-    }
 
-    protected static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafSchemaNode schema,
-            final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
-        final Object value = resolveValueFromSchemaType(xmlElement, schema, schema.getType(), codecProvider, schemaCtx);
-        Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
-        return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
-    }
-
-    private static Node<?> toSimpleNodeWithType(final Element xmlElement, final LeafListSchemaNode schema,
-            final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
-        final Object value = resolveValueFromSchemaType(xmlElement, schema, schema.getType(), codecProvider, schemaCtx);
-        Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
-        return new SimpleNodeTOImpl<>(schema.getQName(), null, value, modifyAction.orNull());
-    }
-
-    private static Object resolveValueFromSchemaType(final Element xmlElement, final DataSchemaNode schema, final TypeDefinition<?> type,
-        final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
-
-        TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
-        if (baseType instanceof LeafrefTypeDefinition) {
-            final LeafrefTypeDefinition leafrefTypeDefinition = (LeafrefTypeDefinition) baseType;
-            baseType = SchemaContextUtil.getBaseTypeForLeafRef(leafrefTypeDefinition, schemaCtx, schema);
-        }
-
-        final String text = xmlElement.getTextContent();
-        final Object value;
-
-        if (baseType instanceof InstanceIdentifierType) {
-            value = InstanceIdentifierForXmlCodec.deserialize(xmlElement, schemaCtx);
-        } else if (baseType instanceof IdentityrefTypeDefinition) {
-            value = InstanceIdentifierForXmlCodec.toIdentity(text, xmlElement, schemaCtx);
-        } else {
-            final TypeDefinitionAwareCodec<?, ?> codec = codecProvider.codecFor(baseType);
-            if (codec == null) {
-                LOG.info("No codec for schema {}, falling back to text", schema);
-                value = text;
-            } else {
-                value = codec.deserialize(text);
-            }
-        }
-        return value;
-    }
-
-    private static Node<?> toCompositeNodeWithSchema(final Element xmlElement, final QName qName, final DataNodeContainer schema,
-            final XmlCodecProvider codecProvider,final SchemaContext schemaCtx) {
-        List<Node<?>> values = toDomNodes(xmlElement, Optional.fromNullable(schema.getChildNodes()),schemaCtx);
-        Optional<ModifyAction> modifyAction = getModifyOperationFromAttributes(xmlElement);
-        return ImmutableCompositeNode.create(qName, values, modifyAction.orNull());
-    }
 
     public static Optional<ModifyAction> getModifyOperationFromAttributes(final Element xmlElement) {
         Attr attributeNodeNS = xmlElement.getAttributeNodeNS(OPERATION_ATTRIBUTE_QNAME.getNamespace().toString(), OPERATION_ATTRIBUTE_QNAME.getLocalName());
@@ -318,18 +96,14 @@ public final class XmlDocumentUtils {
         return Optional.of(action);
     }
 
-    private static void checkQName(final Element xmlElement, final QName qName) {
-        checkState(Objects.equals(xmlElement.getNamespaceURI(), qName.getNamespace().toString()),  "Not equal: %s to: %s for: %s and: %s", qName.getNamespace(), xmlElement.getNamespaceURI(), qName, xmlElement);
-        checkState(qName.getLocalName().equals(xmlElement.getLocalName()), "Not equal: %s to: %s for: %s and: %s", qName.getLocalName(), xmlElement.getLocalName(), qName, xmlElement);
-    }
 
     public static final Optional<DataSchemaNode> findFirstSchema(final QName qname, final Iterable<DataSchemaNode> dataSchemaNode) {
         if (dataSchemaNode != null && qname != null) {
             for (DataSchemaNode dsn : dataSchemaNode) {
                 if (qname.isEqualWithoutRevision(dsn.getQName())) {
                     return Optional.<DataSchemaNode> of(dsn);
-                } else if (dsn instanceof ChoiceNode) {
-                    for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
+                } else if (dsn instanceof ChoiceSchemaNode) {
+                    for (ChoiceCaseNode choiceCase : ((ChoiceSchemaNode) dsn).getCases()) {
                         Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
                         if (foundDsn != null && foundDsn.isPresent()) {
                             return foundDsn;
@@ -341,195 +115,6 @@ public final class XmlDocumentUtils {
         return Optional.absent();
     }
 
-    public static Node<?> toDomNode(final Document doc) {
-        return toDomNode(doc.getDocumentElement());
-    }
-
-    private static Node<?> toDomNode(final Element element) {
-        QName qname = qNameFromElement(element);
-
-        ImmutableList.Builder<Node<?>> values = ImmutableList.<Node<?>> builder();
-        NodeList nodes = element.getChildNodes();
-        boolean isSimpleObject = true;
-        String value = null;
-        for (int i = 0; i < nodes.getLength(); i++) {
-            org.w3c.dom.Node child = nodes.item(i);
-            if (child instanceof Element) {
-                isSimpleObject = false;
-                values.add(toDomNode((Element) child));
-            }
-            if (isSimpleObject && child instanceof org.w3c.dom.Text) {
-                value = element.getTextContent();
-                if (!Strings.isNullOrEmpty(value)) {
-                    isSimpleObject = true;
-                }
-            }
-        }
-        if (isSimpleObject) {
-            return new SimpleNodeTOImpl<>(qname, null, value);
-        }
-        return ImmutableCompositeNode.create(qname, values.build());
-    }
-
-    public static List<Node<?>> toDomNodes(final Element element, final Optional<? extends Iterable<DataSchemaNode>> context, final SchemaContext schemaCtx) {
-        return forEachChild(element.getChildNodes(), schemaCtx, new Function<ElementWithSchemaContext, Optional<Node<?>>>() {
-
-            @Override
-            public Optional<Node<?>> apply(final @Nonnull ElementWithSchemaContext input) {
-                if (context.isPresent()) {
-                    Preconditions.checkNotNull(input);
-                    QName partialQName = qNameFromElement(input.getElement());
-                    Optional<DataSchemaNode> schemaNode = findFirstSchema(partialQName, context.get());
-                    if (schemaNode.isPresent()) {
-                        return Optional.<Node<?>> fromNullable(
-                                toNodeWithSchema(input.getElement(), schemaNode.get(), XmlUtils.DEFAULT_XML_CODEC_PROVIDER, input.getSchemaContext()));
-                    }
-                }
-                return Optional.<Node<?>> fromNullable(toDomNode(input.getElement()));
-            }
-
-        });
-    }
-
-    public static List<Node<?>> toDomNodes(final Element element, final Optional<? extends Iterable<DataSchemaNode>> context) {
-        return toDomNodes(element, context, null);
-    }
-
-    /**
-     * Converts XML Document containing notification data from Netconf device to
-     * Data DOM Nodes. <br>
-     * By specification defined in <a
-     * href="http://tools.ietf.org/search/rfc6020#section-7.14">RFC 6020</a>
-     * there are xml elements containing notifications metadata, like eventTime
-     * or root notification element which specifies namespace for which is
-     * notification defined in yang model. Those elements MUST be stripped off
-     * notifications body. This method returns pure notification body which
-     * begins in element which is equal to notifications name defined in
-     * corresponding yang model. Rest of notification metadata are obfuscated,
-     * thus Data DOM contains only pure notification body.
-     *
-     * @param document
-     *            XML Document containing notification body
-     * @param notifications
-     *            Notifications Definition Schema
-     * @return Data DOM Nodes containing xml notification body definition or
-     *         <code>null</code> if there is no NotificationDefinition with
-     *         Element with equal notification QName defined in XML Document.
-     */
-    public static CompositeNode notificationToDomNodes(final Document document,
-            final Optional<Set<NotificationDefinition>> notifications, final SchemaContext schemaCtx) {
-        if (notifications.isPresent() && (document != null) && (document.getDocumentElement() != null)) {
-            final NodeList originChildNodes = document.getDocumentElement().getChildNodes();
-            for (int i = 0; i < originChildNodes.getLength(); i++) {
-                org.w3c.dom.Node child = originChildNodes.item(i);
-                if (child instanceof Element) {
-                    final Element childElement = (Element) child;
-                    final QName partialQName = qNameFromElement(childElement);
-                    final Optional<NotificationDefinition> notificationDef = findNotification(partialQName,
-                            notifications.get());
-                    if (notificationDef.isPresent()) {
-                        final Iterable<DataSchemaNode> dataNodes = notificationDef.get().getChildNodes();
-                        final List<Node<?>> domNodes = toDomNodes(childElement,
-                                Optional.<Iterable<DataSchemaNode>> fromNullable(dataNodes),schemaCtx);
-                        return ImmutableCompositeNode.create(notificationDef.get().getQName(), domNodes);
-                    }
-                }
-            }
-        }
-        return null;
-    }
-
-    /**
-     * Transforms XML Document representing Rpc output body into Composite Node structure based on Rpc definition
-     * within given Schema Context. The transformation is based on Rpc Definition which is defined in provided Schema Context.
-     * If Rpc Definition is missing from given Schema Context the method will return <code>null</code>
-     *
-     * @param document XML Document containing Output RPC message
-     * @param rpcName Rpc QName
-     * @param context Schema Context
-     * @return Rpc message in Composite Node data structures if Rpc definition is present within provided Schema Context, otherwise
-     * returns <code>null</code>
-     */
-    public static CompositeNode rpcReplyToDomNodes(final Document document, final QName rpcName,
-            final SchemaContext context) {
-        Preconditions.checkNotNull(document);
-        Preconditions.checkNotNull(rpcName);
-        Preconditions.checkNotNull(context);
-
-        Optional<RpcDefinition> rpcDefinition = findRpc(rpcName, context);
-        if (rpcDefinition.isPresent()) {
-            RpcDefinition rpc = rpcDefinition.get();
-
-            final Collection<DataSchemaNode> outputNode = rpc.getOutput() != null ? rpc.getOutput().getChildNodes() : null;
-            final Element rpcReplyElement = document.getDocumentElement();
-            final QName partialQName = qNameFromElement(rpcReplyElement);
-
-            if (RPC_REPLY_QNAME.equals(partialQName)) {
-                final List<Node<?>> domNodes = toDomNodes(rpcReplyElement, Optional.fromNullable(outputNode), context);
-                QName qName = rpc.getOutput() != null ? rpc.getOutput().getQName() : QName.cachedReference(QName.create(rpcName, "output"));
-                List<Node<?>> rpcOutNodes = Collections.<Node<?>>singletonList(ImmutableCompositeNode.create(
-                        qName, domNodes));
-                return ImmutableCompositeNode.create(rpcName, rpcOutNodes);
-            }
-        }
-        return null;
-    }
-
-    /**
-     * Method searches given schema context for Rpc Definition with given QName.
-     * Returns Rpc Definition if is present within given Schema Context, otherwise returns Optional.absent().
-     *
-     * @param rpc Rpc QName
-     * @param context Schema Context
-     * @return Rpc Definition if is present within given Schema Context, otherwise returns Optional.absent().
-     */
-    private static Optional<RpcDefinition> findRpc(final QName rpc, final SchemaContext context) {
-        Preconditions.checkNotNull(rpc);
-        Preconditions.checkNotNull(context);
-        for (final RpcDefinition rpcDefinition : context.getOperations()) {
-            if ((rpcDefinition != null) && rpc.equals(rpcDefinition.getQName())) {
-                return Optional.of(rpcDefinition);
-            }
-        }
-        return Optional.absent();
-    }
-
-    public static CompositeNode notificationToDomNodes(final Document document,
-            final Optional<Set<NotificationDefinition>> notifications) {
-        return notificationToDomNodes(document, notifications,null);
-    }
-
-    private static Optional<NotificationDefinition> findNotification(final QName notifName,
-            final Set<NotificationDefinition> notifications) {
-        if ((notifName != null) && (notifications != null)) {
-            for (final NotificationDefinition notification : notifications) {
-                if ((notification != null) && notifName.isEqualWithoutRevision(notification.getQName())) {
-                    return Optional.<NotificationDefinition>fromNullable(notification);
-                }
-            }
-        }
-        return Optional.<NotificationDefinition>absent();
-    }
-
-    private static final <T> List<T> forEachChild(final NodeList nodes, final SchemaContext schemaContext, final Function<ElementWithSchemaContext, Optional<T>> forBody) {
-        final int l = nodes.getLength();
-        if (l == 0) {
-            return ImmutableList.of();
-        }
-
-        final List<T> list = new ArrayList<>(l);
-        for (int i = 0; i < l; i++) {
-            org.w3c.dom.Node child = nodes.item(i);
-            if (child instanceof Element) {
-                Optional<T> result = forBody.apply(new ElementWithSchemaContext((Element) child,schemaContext));
-                if (result.isPresent()) {
-                    list.add(result.get());
-                }
-            }
-        }
-        return ImmutableList.copyOf(list);
-    }
-
     public static final XmlCodecProvider defaultValueCodecProvider() {
         return XmlUtils.DEFAULT_XML_CODEC_PROVIDER;
     }
index f9f6a70ac2c7f88945d5aa63fbcd103b4a14b1eb..aa72a64645d76bec2707d4bdef0b1f1ef32c4e86 100644 (file)
@@ -5,27 +5,15 @@ import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import java.net.URI;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Map;
 import java.util.Map.Entry;
 import javax.annotation.Nonnull;
-import javax.annotation.Nullable;
 import javax.xml.stream.XMLStreamException;
 import javax.xml.stream.XMLStreamWriter;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.AttributesContainer;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
-import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
-import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
-import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
@@ -65,29 +53,6 @@ public class XmlStreamUtils {
         return new XmlStreamUtils(codecProvider);
     }
 
-    /**
-     * Check if a particular data element can be emitted as an empty element, bypassing value encoding. This
-     * functionality is optional, as valid XML stream is produced even if start/end element is produced unconditionally.
-     *
-     * @param data Data node
-     * @return True if the data node will result in empty element body.
-     */
-    public static boolean isEmptyElement(final Node<?> data) {
-        if (data == null) {
-            return true;
-        }
-
-        if (data instanceof CompositeNode) {
-            return ((CompositeNode) data).getValue().isEmpty();
-        }
-        if (data instanceof SimpleNode) {
-            return data.getValue() == null;
-        }
-
-        // Safe default
-        return false;
-    }
-
     /**
      * Write an InstanceIdentifier into the output stream. Calling corresponding {@link XMLStreamWriter#writeStartElement(String)}
      * and {@link XMLStreamWriter#writeEndElement()} is the responsibility of the caller.
@@ -95,169 +60,20 @@ public class XmlStreamUtils {
      * @param writer XML Stream writer
      * @param id InstanceIdentifier
      * @throws XMLStreamException
+     *
+     * @deprecated Use {@link #writeInstanceIdentifier(XMLStreamWriter, YangInstanceIdentifier)} instead.
      */
+    @Deprecated
     public static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull YangInstanceIdentifier id) throws XMLStreamException {
         Preconditions.checkNotNull(writer, "Writer may not be null");
         Preconditions.checkNotNull(id, "Variable should contain instance of instance identifier and can't be null");
 
         final RandomPrefix prefixes = new RandomPrefix();
         final String str = XmlUtils.encodeIdentifier(prefixes, id);
-
-        for (Entry<URI, String> e: prefixes.getPrefixes()) {
-            final String ns = e.getKey().toString();
-            final String p = e.getValue();
-
-            writer.writeNamespace(p, ns);
-        }
+        writeNamespaceDeclarations(writer,prefixes.getPrefixes());
         writer.writeCharacters(str);
     }
 
-    /**
-     * Write a full XML document corresponding to a CompositeNode into an XML stream writer.
-     *
-     * @param writer XML Stream writer
-     * @param data data node
-     * @param schema corresponding schema node, may be null
-     * @throws XMLStreamException if an encoding problem occurs
-     */
-    public void writeDocument(final @Nonnull XMLStreamWriter writer, final @Nonnull CompositeNode data, final @Nullable SchemaNode schema) throws XMLStreamException {
-        // final Boolean repairing = (Boolean) writer.getProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES);
-        // Preconditions.checkArgument(repairing == true, "XML Stream Writer has to be repairing namespaces");
-
-        writer.writeStartDocument();
-        writeElement(writer, data, schema);
-        writer.writeEndDocument();
-        writer.flush();
-    }
-
-    /**
-     * Short-hand for {@link #writeDocument(XMLStreamWriter, CompositeNode, SchemaNode)})} with
-     * null SchemaNode.
-     *
-     * @param writer XML Stream writer
-     * @param data data node
-     * @throws XMLStreamException if an encoding problem occurs
-     */
-    public void writeDocument(final XMLStreamWriter writer, final CompositeNode data) throws XMLStreamException {
-        writeDocument(writer, data, null);
-    }
-
-    /**
-     * Write an element into a XML stream writer. This includes the element start/end tags and
-     * the value of the element.
-     *
-     * @param writer XML Stream writer
-     * @param data data node
-     * @param schema Schema node
-     * @throws XMLStreamException if an encoding problem occurs
-     */
-    public void writeElement(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
-        final QName qname = data.getNodeType();
-        final String ns = qname.getNamespace() != null ? qname.getNamespace().toString() : "";
-        final String pfx = "";
-
-        if (isEmptyElement(data)) {
-            if (hasAttributes(data)) {
-                writer.writeStartElement(pfx, qname.getLocalName(), ns);
-                final RandomPrefix randomPrefix = new RandomPrefix();
-                writeAttributes(writer, (AttributesContainer) data, randomPrefix);
-                writer.writeEndElement();
-            } else {
-                writer.writeEmptyElement(pfx, qname.getLocalName(), ns);
-            }
-            return;
-        }
-
-        writer.writeStartElement(pfx, qname.getLocalName(), ns);
-        writeValue(writer, data, schema);
-        writer.writeEndElement();
-    }
-
-    /**
-     * Write a value into a XML stream writer. This method assumes the start and end of element is
-     * emitted by the caller.
-     *
-     * @param writer XML Stream writer
-     * @param data data node
-     * @param schema Schema node
-     * @throws XMLStreamException if an encoding problem occurs
-     */
-    public void writeValue(final XMLStreamWriter writer, final @Nonnull Node<?> data, final SchemaNode schema) throws XMLStreamException {
-        if (hasAttributes(data)) {
-            RandomPrefix randomPrefix = new RandomPrefix();
-            writeAttributes(writer, (AttributesContainer) data, randomPrefix);
-        }
-
-        if (data instanceof SimpleNode<?>) {
-            // Simple node
-            if (schema instanceof LeafListSchemaNode || schema instanceof LeafSchemaNode) {
-                writeValue(writer, schema, data.getValue());
-            } else {
-                Object value = data.getValue();
-                if (value != null) {
-                    writer.writeCharacters(String.valueOf(value));
-                }
-            }
-        } else {
-            // CompositeNode
-            final CompositeNode castedData = ((CompositeNode) data);
-            final DataNodeContainer castedSchema;
-            if (schema instanceof DataNodeContainer) {
-                castedSchema = (DataNodeContainer) schema;
-            } else {
-                castedSchema = null;
-            }
-            final Collection<QName> keyLeaves;
-            if (schema instanceof ListSchemaNode) {
-                keyLeaves = ((ListSchemaNode) schema).getKeyDefinition();
-
-            } else {
-                keyLeaves = Collections.emptyList();
-
-            }
-            for (QName key : keyLeaves) {
-                SimpleNode<?> keyLeaf = castedData.getFirstSimpleByName(key);
-                if(keyLeaf != null) {
-                    writeChildElement(writer,keyLeaf,castedSchema);
-                }
-            }
-
-            for (Node<?> child : castedData.getValue()) {
-                if(keyLeaves.contains(child.getNodeType())) {
-                    // Skip key leaf which was written by previous for loop.
-                    continue;
-                }
-                writeChildElement(writer,child,castedSchema);
-            }
-        }
-    }
-
-    private void writeChildElement(final XMLStreamWriter writer, final Node<?> child, final DataNodeContainer parentSchema) throws XMLStreamException {
-        DataSchemaNode childSchema = null;
-        if (parentSchema != null) {
-            childSchema = SchemaUtils.findFirstSchema(child.getNodeType(), parentSchema.getChildNodes()).orNull();
-            if ((childSchema == null) && LOG.isDebugEnabled()) {
-                LOG.debug("Probably the data node \"{}\" does not conform to schema", child == null ? "" : child.getNodeType().getLocalName());
-            }
-        }
-        writeElement(writer, child, childSchema);
-    }
-
-    private static void writeAttributes(final XMLStreamWriter writer, final AttributesContainer data, final RandomPrefix randomPrefix) throws XMLStreamException {
-        for (Entry<QName, String> attribute : data.getAttributes().entrySet()) {
-            writeAttribute(writer, attribute, randomPrefix);
-        }
-    }
-
-    private static boolean hasAttributes(final Node<?> data) {
-        if (data instanceof AttributesContainer) {
-            final Map<QName, String> c = ((AttributesContainer) data).getAttributes();
-            return c != null && !c.isEmpty();
-        } else {
-            return false;
-        }
-    }
-
     @VisibleForTesting
     static void writeAttribute(final XMLStreamWriter writer, final Entry<QName, String> attribute, final RandomPrefix randomPrefix)
             throws XMLStreamException {
@@ -351,15 +167,35 @@ public class XmlStreamUtils {
         }
     }
 
-    private static void write(final @Nonnull XMLStreamWriter writer, final @Nonnull InstanceIdentifierTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
+    private void write(final @Nonnull XMLStreamWriter writer, final @Nonnull InstanceIdentifierTypeDefinition type, final @Nonnull Object value) throws XMLStreamException {
         if (value instanceof YangInstanceIdentifier) {
-            write(writer, (YangInstanceIdentifier)value);
+            writeInstanceIdentifier(writer, (YangInstanceIdentifier)value);
         } else {
             LOG.warn("Value of {}:{} is not an InstanceIdentifier but {}", type.getQName().getNamespace(), type.getQName().getLocalName(), value.getClass());
             writer.writeCharacters(String.valueOf(value));
         }
     }
 
+    public void writeInstanceIdentifier(XMLStreamWriter writer, YangInstanceIdentifier value) throws XMLStreamException {
+        if(schemaContext.isPresent()) {
+            RandomPrefixInstanceIdentifierSerializer iiCodec = new RandomPrefixInstanceIdentifierSerializer(schemaContext.get());
+            String serializedValue = iiCodec.serialize(value);
+            writeNamespaceDeclarations(writer,iiCodec.getPrefixes());
+            writer.writeCharacters(serializedValue);
+        } else {
+            LOG.warn("Schema context not present in {}, serializing {} without schema.",this,value);
+            write(writer,value);
+        }
+    }
+
+    private static void writeNamespaceDeclarations(XMLStreamWriter writer, Iterable<Entry<URI, String>> prefixes) throws XMLStreamException {
+        for (Entry<URI, String> e: prefixes) {
+            final String ns = e.getKey().toString();
+            final String p = e.getValue();
+            writer.writeNamespace(p, ns);
+        }
+    }
+
     public static XmlStreamUtils create(final XmlCodecProvider codecProvider, final SchemaContext schemaContext) {
         return new XmlStreamUtils(codecProvider, schemaContext);
     }
index e6cfd58e7ddb7b4b43105190646fbcf62c2dd321..cfb8fc0897cd5b2f620f940bd8358b1ed94a2524 100644 (file)
@@ -8,9 +8,7 @@
 package org.opendaylight.yangtools.yang.data.impl.codec.xml;
 
 import java.util.Map;
-
 import javax.annotation.Nonnull;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
@@ -42,6 +40,11 @@ public final class XmlUtils {
         return superType;
     }
 
+    /**
+     *
+     * @deprecated Use {@link RandomPrefixInstanceIdentifierSerializer} instead.
+     */
+    @Deprecated
     static String encodeIdentifier(final RandomPrefix prefixes, final YangInstanceIdentifier id) {
         StringBuilder textContent = new StringBuilder();
         for (PathArgument pathArgument : id.getPathArguments()) {
index c2081f37de9875f78e6c4ba2495f9c1bfadf3b50..7277f281016003dafe18fefe58251e1ba4e8af42 100644 (file)
@@ -7,7 +7,7 @@
  */
 package org.opendaylight.yangtools.yang.data.impl.schema;
 
-import org.opendaylight.yangtools.yang.data.api.Node;
+import javax.xml.transform.dom.DOMSource;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
@@ -52,6 +52,7 @@ import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableUn
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableUnkeyedListNodeBuilder;
 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
@@ -81,11 +82,11 @@ public final class Builders {
         return ImmutableLeafSetEntryNodeSchemaAwareBuilder.create(schema);
     }
 
-    public static <T> NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, Node<?>, AnyXmlNode> anyXmlBuilder() {
+    public static <T> NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder() {
         return ImmutableAnyXmlNodeBuilder.create();
     }
 
-    public static <T> NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, Node<?>, AnyXmlNode> anyXmlBuilder(
+    public static <T> NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder(
             final AnyXmlSchemaNode schema) {
         return ImmutableAnyXmlNodeSchemaAwareBuilder.create(schema);
     }
@@ -181,7 +182,7 @@ public final class Builders {
         return ImmutableChoiceNodeBuilder.create();
     }
 
-    public static DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ChoiceNode> choiceBuilder(final org.opendaylight.yangtools.yang.model.api.ChoiceNode schema) {
+    public static DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ChoiceNode> choiceBuilder(final ChoiceSchemaNode schema) {
         return ImmutableChoiceNodeSchemaAwareBuilder.create(schema);
     }
 
index 433212bfc46f9a6df118bf30a7bc06eef33247c1..0fd44f478068ab4415afdc656cc04e89776a1b33 100644 (file)
@@ -10,12 +10,14 @@ package org.opendaylight.yangtools.yang.data.impl.schema;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
+import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableChoiceNodeBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableLeafNodeBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
@@ -74,8 +76,11 @@ public final class ImmutableNodes {
         return ImmutableMapEntryNodeBuilder.create();
     }
 
-    public static NormalizedNode<?, ?> containerNode(final QName name) {
+    public static ContainerNode containerNode(final QName name) {
         return ImmutableContainerNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(name)).build();
     }
 
+    public static ChoiceNode choiceNode(final QName name) {
+        return ImmutableChoiceNodeBuilder.create().withNodeIdentifier(new NodeIdentifier(name)).build();
+    }
 }
index 3ac6f32b0871a27a5982e77c25af8c83eb8ae642..c97819bb381c6b355b9ad8fd0662eedca27e1ca2 100644 (file)
@@ -8,10 +8,9 @@
 package org.opendaylight.yangtools.yang.data.impl.schema;
 
 import com.google.common.base.Preconditions;
-import java.io.IOException;
 import java.util.ArrayDeque;
+import java.util.Collection;
 import java.util.Deque;
-import java.util.List;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
@@ -263,7 +262,7 @@ public class ImmutableNormalizedNodeStreamWriter implements NormalizedNodeStream
         }
 
         @Override
-        public NormalizedNodeContainerBuilder withValue(final List value) {
+        public NormalizedNodeContainerBuilder withValue(final Collection value) {
             throw new UnsupportedOperationException();
         }
 
@@ -286,9 +285,7 @@ public class ImmutableNormalizedNodeStreamWriter implements NormalizedNodeStream
     }
 
     @Override
-    public void close() throws IOException {
-        // TODO Auto-generated method stub
-
+    public void close() {
+        // no-op
     }
-
 }
index 175969cc614425c1a9246f0e069aec80abb8daa5..365148cc609f96b58648357009082e25448c41d6 100644 (file)
@@ -7,7 +7,6 @@
  */
 package org.opendaylight.yangtools.yang.data.impl.schema;
 
-
 import com.google.common.base.Function;
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
@@ -26,7 +25,7 @@ import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 
@@ -40,8 +39,8 @@ public final class SchemaUtils {
             for (DataSchemaNode dsn : dataSchemaNode) {
                 if (qname.isEqualWithoutRevision(dsn.getQName())) {
                     return Optional.<DataSchemaNode> of(dsn);
-                } else if (dsn instanceof ChoiceNode) {
-                    for (ChoiceCaseNode choiceCase : ((ChoiceNode) dsn).getCases()) {
+                } else if (dsn instanceof ChoiceSchemaNode) {
+                    for (ChoiceCaseNode choiceCase : ((ChoiceSchemaNode) dsn).getCases()) {
                         Optional<DataSchemaNode> foundDsn = findFirstSchema(qname, choiceCase.getChildNodes());
                         if (foundDsn != null && foundDsn.isPresent()) {
                             return foundDsn;
@@ -71,7 +70,7 @@ public final class SchemaUtils {
         return schemaForAugment.get();
     }
 
-    public static AugmentationSchema findSchemaForAugment(final ChoiceNode schema, final Set<QName> qNames) {
+    public static AugmentationSchema findSchemaForAugment(final ChoiceSchemaNode schema, final Set<QName> qNames) {
         Optional<AugmentationSchema> schemaForAugment = Optional.absent();
 
         for (ChoiceCaseNode choiceCaseNode : schema.getCases()) {
@@ -105,7 +104,7 @@ public final class SchemaUtils {
         return Optional.absent();
     }
 
-    public static DataSchemaNode findSchemaForChild(final ChoiceNode schema, final QName childPartialQName) {
+    public static DataSchemaNode findSchemaForChild(final ChoiceSchemaNode schema, final QName childPartialQName) {
         for (ChoiceCaseNode choiceCaseNode : schema.getCases()) {
             Optional<DataSchemaNode> childSchema = findFirstSchema(childPartialQName, choiceCaseNode.getChildNodes());
             if (childSchema.isPresent()) {
@@ -123,24 +122,24 @@ public final class SchemaUtils {
      *
      * @return Map with all child nodes, to their most top augmentation
      */
-    public static Map<QName, ChoiceNode> mapChildElementsFromChoices(final DataNodeContainer schema) {
+    public static Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final DataNodeContainer schema) {
         return mapChildElementsFromChoices(schema, schema.getChildNodes());
     }
 
-    private static Map<QName, ChoiceNode> mapChildElementsFromChoices(final DataNodeContainer schema, final Iterable<DataSchemaNode> childNodes) {
-        Map<QName, ChoiceNode> mappedChoices = Maps.newLinkedHashMap();
+    private static Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final DataNodeContainer schema, final Iterable<DataSchemaNode> childNodes) {
+        Map<QName, ChoiceSchemaNode> mappedChoices = Maps.newLinkedHashMap();
 
         for (final DataSchemaNode childSchema : childNodes) {
-            if(childSchema instanceof ChoiceNode) {
+            if (childSchema instanceof ChoiceSchemaNode) {
 
-                if(isFromAugment(schema, childSchema)) {
+                if (isFromAugment(schema, childSchema)) {
                     continue;
                 }
 
-                for (ChoiceCaseNode choiceCaseNode : ((ChoiceNode) childSchema).getCases()) {
+                for (ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) childSchema).getCases()) {
 
                     for (QName qName : getChildNodesRecursive(choiceCaseNode)) {
-                        mappedChoices.put(qName, (ChoiceNode) childSchema);
+                        mappedChoices.put(qName, (ChoiceSchemaNode) childSchema);
                     }
                 }
             }
@@ -197,8 +196,8 @@ public final class SchemaUtils {
                     for (QName qName : getChildNodesRecursive((DataNodeContainer) child)) {
                         childNodesToAugmentation.put(qName, mostTopAugmentation);
                     }
-                } else if (child instanceof ChoiceNode) {
-                    for (ChoiceCaseNode choiceCaseNode : ((ChoiceNode) child).getCases()) {
+                } else if (child instanceof ChoiceSchemaNode) {
+                    for (ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) child).getCases()) {
                         for (QName qName : getChildNodesRecursive(choiceCaseNode)) {
                             childNodesToAugmentation.put(qName, mostTopAugmentation);
                         }
@@ -210,8 +209,8 @@ public final class SchemaUtils {
         }
 
         // Choice Node has to map child nodes from all its cases
-        if (schema instanceof ChoiceNode) {
-            for (ChoiceCaseNode choiceCaseNode : ((ChoiceNode) schema).getCases()) {
+        if (schema instanceof ChoiceSchemaNode) {
+            for (ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) schema).getCases()) {
                 if (!(augments.containsKey(choiceCaseNode.getQName()))) {
                     continue;
                 }
@@ -234,8 +233,8 @@ public final class SchemaUtils {
         Set<QName> allChildNodes = Sets.newHashSet();
 
         for (DataSchemaNode childSchema : nodeContainer.getChildNodes()) {
-            if(childSchema instanceof ChoiceNode) {
-                for (ChoiceCaseNode choiceCaseNode : ((ChoiceNode) childSchema).getCases()) {
+            if(childSchema instanceof ChoiceSchemaNode) {
+                for (ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) childSchema).getCases()) {
                     allChildNodes.addAll(getChildNodesRecursive(choiceCaseNode));
                 }
             } else if(childSchema instanceof AugmentationSchema || childSchema instanceof ChoiceCaseNode) {
@@ -265,9 +264,9 @@ public final class SchemaUtils {
 
         if(targetSchema instanceof DataNodeContainer) {
             realChildNodes = getRealSchemasForAugment((DataNodeContainer)targetSchema, augmentSchema);
-        } else if(targetSchema instanceof ChoiceNode) {
+        } else if(targetSchema instanceof ChoiceSchemaNode) {
             for (DataSchemaNode dataSchemaNode : augmentSchema.getChildNodes()) {
-                for (ChoiceCaseNode choiceCaseNode : ((ChoiceNode) targetSchema).getCases()) {
+                for (ChoiceCaseNode choiceCaseNode : ((ChoiceSchemaNode) targetSchema).getCases()) {
                     if(getChildNodesRecursive(choiceCaseNode).contains(dataSchemaNode.getQName())) {
                         realChildNodes.add(choiceCaseNode.getDataChildByName(dataSchemaNode.getQName()));
                     }
@@ -288,7 +287,7 @@ public final class SchemaUtils {
         return realChildNodes;
     }
 
-    public static Optional<ChoiceCaseNode> detectCase(final ChoiceNode schema, final DataContainerChild<?, ?> child) {
+    public static Optional<ChoiceCaseNode> detectCase(final ChoiceSchemaNode schema, final DataContainerChild<?, ?> child) {
         for (ChoiceCaseNode choiceCaseNode : schema.getCases()) {
             if (child instanceof AugmentationNode
                     && belongsToCaseAugment(choiceCaseNode,
index 1fa9650212a3c13286ca577977c81bb6b19a69e3..7e42a3e045f9ebc92198ab40bef19ac3e7656bb8 100644 (file)
@@ -7,8 +7,7 @@
  */
 package org.opendaylight.yangtools.yang.data.impl.schema.builder.api;
 
-import java.util.List;
-
+import java.util.Collection;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
@@ -18,7 +17,7 @@ public interface CollectionNodeBuilder<V extends NormalizedNode<?, ?>, R extends
         extends NormalizedNodeContainerBuilder<NodeIdentifier,PathArgument, V, R> {
 
     @Override
-    CollectionNodeBuilder<V, R> withValue(List<V> value);
+    CollectionNodeBuilder<V, R> withValue(Collection<V> value);
 
     @Override
     CollectionNodeBuilder<V, R> withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier nodeIdentifier);
index dd950564a323dbf045fd72dcf0bc3625515d1eb6..019f8634e3f9194cb8294862c6d4bf76b68ec3a3 100644 (file)
@@ -7,8 +7,7 @@
  */
 package org.opendaylight.yangtools.yang.data.impl.schema.builder.api;
 
-import java.util.List;
-
+import java.util.Collection;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
@@ -18,10 +17,11 @@ public interface DataContainerNodeAttrBuilder<I extends YangInstanceIdentifier.P
         AttributesBuilder<DataContainerNodeAttrBuilder<I, R>> {
 
     @Override
-    DataContainerNodeAttrBuilder<I, R> withValue(List<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> value);
+    DataContainerNodeAttrBuilder<I, R> withValue(Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> value);
 
     @Override
     DataContainerNodeAttrBuilder<I, R> withNodeIdentifier(I nodeIdentifier);
 
+    @Override
     DataContainerNodeAttrBuilder<I, R> withChild(DataContainerChild<?, ?> child);
 }
index a7eb3742f4f9a29bb58bd13eff3d1edae3254459..fd33b498df6a3d07b4b2e83f9a88dcc9ee1bf3c3 100644 (file)
@@ -7,8 +7,7 @@
  */
 package org.opendaylight.yangtools.yang.data.impl.schema.builder.api;
 
-import java.util.List;
-
+import java.util.Collection;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
@@ -18,7 +17,7 @@ public interface DataContainerNodeBuilder<I extends YangInstanceIdentifier.PathA
         extends NormalizedNodeContainerBuilder<I, PathArgument, DataContainerChild<? extends PathArgument, ?>, R> {
 
     @Override
-    DataContainerNodeBuilder<I, R> withValue(List<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> value);
+    DataContainerNodeBuilder<I, R> withValue(Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> value);
 
     @Override
     DataContainerNodeBuilder<I, R> withNodeIdentifier(I nodeIdentifier);
index 5844f2ee30b94d4f83af696e10fe60e421121089..51041f1e578010a967239fb83d590660d48c9f8e 100644 (file)
@@ -7,9 +7,8 @@
  */
 package org.opendaylight.yangtools.yang.data.impl.schema.builder.api;
 
-import java.util.List;
+import java.util.Collection;
 import java.util.Map;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
@@ -22,7 +21,7 @@ public interface ListNodeBuilder<T, V>
     ListNodeBuilder<T, V> withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier nodeIdentifier);
 
     @Override
-    ListNodeBuilder<T, V> withValue(List<LeafSetEntryNode<T>> value);
+    ListNodeBuilder<T, V> withValue(Collection<LeafSetEntryNode<T>> value);
 
     @Override
     ListNodeBuilder<T, V> withChild(LeafSetEntryNode<T> child);
index 2409011f670d353376832d1b81130a69a5ffacd2..4adcee1add6131990a543b90f90115b728f57594 100644 (file)
@@ -1,18 +1,23 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
 package org.opendaylight.yangtools.yang.data.impl.schema.builder.api;
 
-import java.util.List;
-
+import java.util.Collection;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 
-public interface NormalizedNodeContainerBuilder<K extends PathArgument,CK extends PathArgument,CV extends NormalizedNode<? extends CK, ?>,P extends NormalizedNode<K, ?>>
-extends NormalizedNodeBuilder<K,List<CV>,P>{
+public interface NormalizedNodeContainerBuilder<K extends PathArgument,CK extends PathArgument,CV extends NormalizedNode<? extends CK, ?>,P extends NormalizedNode<K, ?>> extends NormalizedNodeBuilder<K,Collection<CV>,P>{
 
     @Override
     NormalizedNodeContainerBuilder<K,CK,CV,P> withNodeIdentifier(K nodeIdentifier);
 
     @Override
-    NormalizedNodeContainerBuilder<K,CK,CV,P> withValue(List<CV> value);
+    NormalizedNodeContainerBuilder<K,CK,CV,P> withValue(Collection<CV> value);
 
     NormalizedNodeContainerBuilder<K,CK,CV,P> addChild(CV child);
     NormalizedNodeContainerBuilder<K,CK,CV,P> removeChild(CK key);
index e6f081b3d6251d438d941e658c52c3a16b454c8f..218b3a3f4eb9a0310a897e5f959984976f678613 100644 (file)
@@ -7,10 +7,9 @@
  */
 package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
 
+import java.util.Collection;
 import java.util.Collections;
-import java.util.List;
 import java.util.Map;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
@@ -46,7 +45,7 @@ abstract class AbstractImmutableDataContainerNodeAttrBuilder<I extends YangInsta
     }
 
     @Override
-    public DataContainerNodeAttrBuilder<I, R> withValue(final List<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> value) {
+    public DataContainerNodeAttrBuilder<I, R> withValue(final Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> value) {
         return (DataContainerNodeAttrBuilder<I, R>) super.withValue(value);
     }
 
index cb50fefc8df70e7da24a5d83e48c1dec08774646..ec2f5ee7bdfbb48e316fa63b45c3ccfc1e24a67d 100644 (file)
@@ -7,8 +7,8 @@
  */
 package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
 
+import java.util.Collection;
 import java.util.HashMap;
-import java.util.List;
 import java.util.Map;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
@@ -86,7 +86,7 @@ abstract class AbstractImmutableDataContainerNodeBuilder<I extends YangInstanceI
     }
 
     @Override
-    public DataContainerNodeBuilder<I, R> withValue(final List<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> value) {
+    public DataContainerNodeBuilder<I, R> withValue(final Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> value) {
         // TODO Replace or putAll ?
         for (final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild : value) {
             withChild(dataContainerChild);
index 0d0ff1878d29a0aa1dbcacc34cd4bfce8aed80b2..49921ec7e4189cc13b7df193d5827f9ab2b5be05 100644 (file)
@@ -8,16 +8,16 @@
 package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
 
 import java.util.Map;
+import javax.xml.transform.dom.DOMSource;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.Node;
 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.nodes.AbstractImmutableNormalizedValueAttrNode;
 
-public class ImmutableAnyXmlNodeBuilder extends AbstractImmutableNormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier, Node<?>, AnyXmlNode> {
+public class ImmutableAnyXmlNodeBuilder extends AbstractImmutableNormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier, DOMSource, AnyXmlNode> {
 
-    public static NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, Node<?>, AnyXmlNode> create() {
+    public static NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, DOMSource, AnyXmlNode> create() {
         return new ImmutableAnyXmlNodeBuilder();
     }
 
@@ -26,9 +26,9 @@ public class ImmutableAnyXmlNodeBuilder extends AbstractImmutableNormalizedNodeB
         return new ImmutableXmlNode(getNodeIdentifier(), getValue(), getAttributes());
     }
 
-    private static final class ImmutableXmlNode extends AbstractImmutableNormalizedValueAttrNode<YangInstanceIdentifier.NodeIdentifier, Node<?>> implements AnyXmlNode {
+    private static final class ImmutableXmlNode extends AbstractImmutableNormalizedValueAttrNode<YangInstanceIdentifier.NodeIdentifier, DOMSource> implements AnyXmlNode {
 
-        ImmutableXmlNode(final YangInstanceIdentifier.NodeIdentifier nodeIdentifier, final Node<?> value, final Map<QName, String> attributes) {
+        ImmutableXmlNode(final YangInstanceIdentifier.NodeIdentifier nodeIdentifier, final DOMSource value, final Map<QName, String> attributes) {
             super(nodeIdentifier, value, attributes);
         }
     }
index 41b9b822a9c1aab87f158cb9afbb9b46554ca7e9..30ad8189e9e7cb352bfd34ed2c6e9d8d3f220253 100644 (file)
@@ -7,8 +7,8 @@
  */
 package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
 
+import javax.xml.transform.dom.DOMSource;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.Node;
 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
@@ -19,17 +19,17 @@ public final class ImmutableAnyXmlNodeSchemaAwareBuilder extends ImmutableAnyXml
         super.withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(schema.getQName()));
     }
 
-    public static NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, Node<?>, AnyXmlNode> create(AnyXmlSchemaNode schema) {
+    public static NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, DOMSource, AnyXmlNode> create(AnyXmlSchemaNode schema) {
         return new ImmutableAnyXmlNodeSchemaAwareBuilder(schema);
     }
 
     @Override
-    public NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, Node<?>, AnyXmlNode> withValue(Node<?> value) {
+    public NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, DOMSource, AnyXmlNode> withValue(DOMSource value) {
         return super.withValue(value);
     }
 
     @Override
-    public NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, Node<?>, AnyXmlNode> withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier nodeIdentifier) {
+    public NormalizedNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifier, DOMSource, AnyXmlNode> withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier nodeIdentifier) {
         throw new UnsupportedOperationException("Node identifier created from schema");
     }
 }
index 2769ddb99e30896896ee10e9a5ee3d7159c33748..8ca39e9ccd83495d562090ff75fdf238672469b6 100644 (file)
@@ -8,29 +8,29 @@
 package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
 
 import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
+import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.valid.DataNodeContainerValidator;
-import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.valid.DataValidationException;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-
-import com.google.common.base.Preconditions;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 
 public class ImmutableChoiceNodeSchemaAwareBuilder extends ImmutableChoiceNodeBuilder {
 
-    private final org.opendaylight.yangtools.yang.model.api.ChoiceNode schema;
+    private final ChoiceSchemaNode schema;
     private DataNodeContainerValidator validator;
 
-    protected ImmutableChoiceNodeSchemaAwareBuilder(org.opendaylight.yangtools.yang.model.api.ChoiceNode schema) {
+    protected ImmutableChoiceNodeSchemaAwareBuilder(final ChoiceSchemaNode schema) {
         this.schema = Preconditions.checkNotNull(schema, "Schema was null");
         super.withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(schema.getQName()));
     }
 
     @Override
-    public DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ChoiceNode> withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier nodeIdentifier) {
+    public DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ChoiceNode> withNodeIdentifier(final YangInstanceIdentifier.NodeIdentifier nodeIdentifier) {
         throw new UnsupportedOperationException("Node identifier created from schema");
     }
 
@@ -51,7 +51,7 @@ public class ImmutableChoiceNodeSchemaAwareBuilder extends ImmutableChoiceNodeBu
         return super.build();
     }
 
-    public static DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ChoiceNode> create(org.opendaylight.yangtools.yang.model.api.ChoiceNode schema) {
+    public static DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ChoiceNode> create(final ChoiceSchemaNode schema) {
         return new ImmutableChoiceNodeSchemaAwareBuilder(schema);
     }
 }
index 71b4bbc7606433dd53ee85ecbf709f21a99939dc..82e8dabafc97b91e7baa6965b2ba5f9953e3f235 100644 (file)
@@ -8,13 +8,13 @@
 package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
 
 import com.google.common.base.Optional;
-import com.google.common.collect.Iterables;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
-import java.util.List;
 import java.util.Map;
 import org.opendaylight.yangtools.concepts.Immutable;
 import org.opendaylight.yangtools.util.MapAdaptor;
+import org.opendaylight.yangtools.util.UnmodifiableCollection;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
@@ -85,7 +85,7 @@ public class ImmutableLeafSetNodeBuilder<T> implements ListNodeBuilder<T, LeafSe
     }
 
     @Override
-    public ListNodeBuilder<T, LeafSetEntryNode<T>> withValue(final List<LeafSetEntryNode<T>> value) {
+    public ListNodeBuilder<T, LeafSetEntryNode<T>> withValue(final Collection<LeafSetEntryNode<T>> value) {
         for (final LeafSetEntryNode<T> leafSetEntry : value) {
             withChild(leafSetEntry);
         }
@@ -108,14 +108,14 @@ public class ImmutableLeafSetNodeBuilder<T> implements ListNodeBuilder<T, LeafSe
     }
 
     protected final static class ImmutableLeafSetNode<T> extends
-            AbstractImmutableNormalizedValueNode<YangInstanceIdentifier.NodeIdentifier, Iterable<LeafSetEntryNode<T>>> implements
+            AbstractImmutableNormalizedValueNode<YangInstanceIdentifier.NodeIdentifier, Collection<LeafSetEntryNode<T>>> implements
             Immutable, LeafSetNode<T> {
 
         private final Map<YangInstanceIdentifier.NodeWithValue, LeafSetEntryNode<T>> children;
 
         ImmutableLeafSetNode(final YangInstanceIdentifier.NodeIdentifier nodeIdentifier,
                 final Map<YangInstanceIdentifier.NodeWithValue, LeafSetEntryNode<T>> children) {
-            super(nodeIdentifier, Iterables.unmodifiableIterable(children.values()));
+            super(nodeIdentifier, UnmodifiableCollection.create(children.values()));
             this.children = children;
         }
 
index 0b1f58cd028d30d3128bfe71cc427c4adb5e5537..12f26a39bed8237aa6d6b133232073b7dea26992 100644 (file)
@@ -7,8 +7,8 @@
  */
 package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
 
+import java.util.Collection;
 import java.util.LinkedHashMap;
-import java.util.List;
 import java.util.Map;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
@@ -70,7 +70,7 @@ public class ImmutableMapEntryNodeBuilder extends AbstractImmutableDataContainer
 
 
     @Override
-    public DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> withValue(final List<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> value) {
+    public DataContainerNodeAttrBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> withValue(final Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> value) {
         fillQnames(value, childrenQNamesToPaths);
         return super.withValue(value);
     }
index 95d9aa2b81a1945168c78e209dd570fde77ac644..dc7b5500c8e514ce3e3644acbdbec388222018b1 100644 (file)
@@ -8,12 +8,12 @@
 package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
 
 import com.google.common.base.Optional;
-import com.google.common.collect.Iterables;
+import java.util.Collection;
 import java.util.HashMap;
-import java.util.List;
 import java.util.Map;
 import org.opendaylight.yangtools.concepts.Immutable;
 import org.opendaylight.yangtools.util.MapAdaptor;
+import org.opendaylight.yangtools.util.UnmodifiableCollection;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
@@ -70,7 +70,7 @@ public class ImmutableMapNodeBuilder implements CollectionNodeBuilder<MapEntryNo
     }
 
     @Override
-    public CollectionNodeBuilder<MapEntryNode, MapNode> withValue(final List<MapEntryNode> value) {
+    public CollectionNodeBuilder<MapEntryNode, MapNode> withValue(final Collection<MapEntryNode> value) {
         // TODO replace or putAll ?
         for (final MapEntryNode mapEntryNode : value) {
             withChild(mapEntryNode);
@@ -103,7 +103,7 @@ public class ImmutableMapNodeBuilder implements CollectionNodeBuilder<MapEntryNo
         return withoutChild(key);
     }
 
-    protected static final class ImmutableMapNode extends AbstractImmutableNormalizedNode<YangInstanceIdentifier.NodeIdentifier, Iterable<MapEntryNode>> implements Immutable,MapNode {
+    protected static final class ImmutableMapNode extends AbstractImmutableNormalizedNode<YangInstanceIdentifier.NodeIdentifier, Collection<MapEntryNode>> implements Immutable,MapNode {
 
         private final Map<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> children;
 
@@ -119,8 +119,8 @@ public class ImmutableMapNodeBuilder implements CollectionNodeBuilder<MapEntryNo
         }
 
         @Override
-        public Iterable<MapEntryNode> getValue() {
-            return Iterables.unmodifiableIterable(children.values());
+        public Collection<MapEntryNode> getValue() {
+            return UnmodifiableCollection.create(children.values());
         }
 
         @Override
index 9876bbe341dd4c0bba8095df7a1f405696b940e3..67eb342fabaf1ae5e31073d068bace381a555b13 100644 (file)
@@ -7,12 +7,14 @@
  */
 package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
 
+import com.google.common.base.Optional;
+import com.google.common.collect.Iterables;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.LinkedHashMap;
-import java.util.List;
 import java.util.Map;
-
 import org.opendaylight.yangtools.concepts.Immutable;
+import org.opendaylight.yangtools.util.UnmodifiableCollection;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
@@ -24,9 +26,6 @@ import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.ListNodeBuil
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.nodes.AbstractImmutableNormalizedNode;
 
-import com.google.common.base.Optional;
-import com.google.common.collect.Iterables;
-
 public class ImmutableOrderedLeafSetNodeBuilder<T> implements ListNodeBuilder<T, LeafSetEntryNode<T>> {
 
     private Map<YangInstanceIdentifier.NodeWithValue, LeafSetEntryNode<T>> value;
@@ -91,7 +90,7 @@ public class ImmutableOrderedLeafSetNodeBuilder<T> implements ListNodeBuilder<T,
     }
 
     @Override
-    public ListNodeBuilder<T, LeafSetEntryNode<T>> withValue(final List<LeafSetEntryNode<T>> value) {
+    public ListNodeBuilder<T, LeafSetEntryNode<T>> withValue(final Collection<LeafSetEntryNode<T>> value) {
         checkDirty();
         for (final LeafSetEntryNode<T> leafSetEntry : value) {
             withChild(leafSetEntry);
@@ -99,7 +98,6 @@ public class ImmutableOrderedLeafSetNodeBuilder<T> implements ListNodeBuilder<T,
         return this;
     }
 
-
     @Override
     public ListNodeBuilder<T, LeafSetEntryNode<T>> withChildValue(final T value, final Map<QName, String> attributes) {
         final ImmutableLeafSetEntryNodeBuilder<T> b = ImmutableLeafSetEntryNodeBuilder.create();
@@ -114,8 +112,8 @@ public class ImmutableOrderedLeafSetNodeBuilder<T> implements ListNodeBuilder<T,
         return withChildValue(value, Collections.<QName,String>emptyMap());
     }
 
-    protected final static class ImmutableOrderedLeafSetNode<T> extends
-            AbstractImmutableNormalizedNode<YangInstanceIdentifier.NodeIdentifier, Iterable<LeafSetEntryNode<T>>> implements
+    protected static final class ImmutableOrderedLeafSetNode<T> extends
+            AbstractImmutableNormalizedNode<YangInstanceIdentifier.NodeIdentifier, Collection<LeafSetEntryNode<T>>> implements
             Immutable, OrderedLeafSetNode<T> {
 
         private final Map<YangInstanceIdentifier.NodeWithValue, LeafSetEntryNode<T>> children;
@@ -147,19 +145,18 @@ public class ImmutableOrderedLeafSetNodeBuilder<T> implements ListNodeBuilder<T,
 
         @Override
         public LeafSetEntryNode<T> getChild(final int position) {
-            return Iterables.get(getValue(), position);
+            return Iterables.get(children.values(), position);
         }
 
         @Override
         public int getSize() {
-            // TODO Auto-generated method stub
-            return 0;
+            return children.size();
         }
 
-               @Override
-               public Iterable<LeafSetEntryNode<T>> getValue() {
-                       return Iterables.unmodifiableIterable(children.values());
-               }
+        @Override
+        public Collection<LeafSetEntryNode<T>> getValue() {
+            return UnmodifiableCollection.create(children.values());
+        }
     }
 
     @Override
index 523ad51817a5b27af9ffa6865f33a0c9d17074da..a7bd82a7e927140fdf2c08d5ebb60648164bdfd4 100644 (file)
@@ -9,10 +9,11 @@ package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
 
 import com.google.common.base.Optional;
 import com.google.common.collect.Iterables;
+import java.util.Collection;
 import java.util.LinkedHashMap;
-import java.util.List;
 import java.util.Map;
 import org.opendaylight.yangtools.concepts.Immutable;
+import org.opendaylight.yangtools.util.UnmodifiableCollection;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
@@ -83,7 +84,7 @@ public class ImmutableOrderedMapNodeBuilder implements CollectionNodeBuilder<Map
     }
 
     @Override
-    public CollectionNodeBuilder<MapEntryNode, OrderedMapNode> withValue(final List<MapEntryNode> value) {
+    public CollectionNodeBuilder<MapEntryNode, OrderedMapNode> withValue(final Collection<MapEntryNode> value) {
         // TODO replace or putAll ?
         for (final MapEntryNode mapEntryNode : value) {
             withChild(mapEntryNode);
@@ -117,7 +118,7 @@ public class ImmutableOrderedMapNodeBuilder implements CollectionNodeBuilder<Map
         return withoutChild(key);
     }
 
-    protected static final class ImmutableOrderedMapNode extends AbstractImmutableNormalizedNode<YangInstanceIdentifier.NodeIdentifier, Iterable<MapEntryNode>> implements Immutable,OrderedMapNode {
+    protected static final class ImmutableOrderedMapNode extends AbstractImmutableNormalizedNode<YangInstanceIdentifier.NodeIdentifier, Collection<MapEntryNode>> implements Immutable,OrderedMapNode {
 
         private final Map<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> children;
 
@@ -144,7 +145,7 @@ public class ImmutableOrderedMapNodeBuilder implements CollectionNodeBuilder<Map
 
         @Override
         public MapEntryNode getChild(final int position) {
-            return Iterables.get(getValue(), position);
+            return Iterables.get(children.values(), position);
         }
 
         @Override
@@ -153,8 +154,8 @@ public class ImmutableOrderedMapNodeBuilder implements CollectionNodeBuilder<Map
         }
 
         @Override
-        public Iterable<MapEntryNode> getValue() {
-            return Iterables.unmodifiableIterable(children.values());
+        public Collection<MapEntryNode> getValue() {
+            return UnmodifiableCollection.create(children.values());
         }
     }
 }
index 9eab2ba09816bd45d76faca4344d4b06273767f8..eb2d3884bbc4dfda6a0e8f2a4a8e9eb39ae73a81 100644 (file)
@@ -9,6 +9,7 @@ package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl;
 
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.LinkedList;
 import java.util.List;
@@ -78,7 +79,7 @@ public class ImmutableUnkeyedListNodeBuilder implements CollectionNodeBuilder<Un
     }
 
     @Override
-    public CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> withValue(final List<UnkeyedListEntryNode> value) {
+    public CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> withValue(final Collection<UnkeyedListEntryNode> value) {
         // TODO replace or putAll ?
         for (final UnkeyedListEntryNode UnkeyedListEntryNode : value) {
             withChild(UnkeyedListEntryNode);
@@ -115,19 +116,19 @@ public class ImmutableUnkeyedListNodeBuilder implements CollectionNodeBuilder<Un
         return withoutChild(key);
     }
 
-    protected static final class EmptyImmutableUnkeyedListNode extends AbstractImmutableNormalizedNode<YangInstanceIdentifier.NodeIdentifier, Iterable<UnkeyedListEntryNode>> implements Immutable, UnkeyedListNode {
+    protected static final class EmptyImmutableUnkeyedListNode extends AbstractImmutableNormalizedNode<YangInstanceIdentifier.NodeIdentifier, Collection<UnkeyedListEntryNode>> implements Immutable, UnkeyedListNode {
         protected EmptyImmutableUnkeyedListNode(final NodeIdentifier nodeIdentifier) {
             super(nodeIdentifier);
         }
 
         @Override
-        public Iterable<UnkeyedListEntryNode> getValue() {
-            return Collections.emptyList();
+        public Collection<UnkeyedListEntryNode> getValue() {
+            return Collections.emptySet();
         }
 
         @Override
         public UnkeyedListEntryNode getChild(final int position) {
-            return null;
+            throw new IndexOutOfBoundsException();
         }
 
         @Override
@@ -147,7 +148,7 @@ public class ImmutableUnkeyedListNodeBuilder implements CollectionNodeBuilder<Un
     }
 
     protected static final class ImmutableUnkeyedListNode extends
-            AbstractImmutableNormalizedValueNode<YangInstanceIdentifier.NodeIdentifier, Iterable<UnkeyedListEntryNode>>
+            AbstractImmutableNormalizedValueNode<YangInstanceIdentifier.NodeIdentifier, Collection<UnkeyedListEntryNode>>
             implements Immutable, UnkeyedListNode {
 
         private final ImmutableList<UnkeyedListEntryNode> children;
index 7a6627eb5e444dddfd9dd385def15f2fcd8cbc24..e370c131d73f1f87683f311263c65496b28c29ec 100644 (file)
@@ -8,11 +8,13 @@
 package org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.valid;
 
 import java.util.Map;
+import java.util.Objects;
 import java.util.Set;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 
@@ -37,7 +39,7 @@ public class DataValidationException extends RuntimeException {
         }
     }
 
-    public static void checkLegalChild(final boolean isLegal, final YangInstanceIdentifier.PathArgument child, final ChoiceNode schema) {
+    public static void checkLegalChild(final boolean isLegal, final YangInstanceIdentifier.PathArgument child, final ChoiceSchemaNode schema) {
         if (!isLegal) {
             throw new IllegalChildException(child, schema);
         }
@@ -50,46 +52,51 @@ public class DataValidationException extends RuntimeException {
     }
 
     public static void checkListKey(final DataContainerChild<?, ?> childNode, final Map<QName, Object> keyValues, final QName keyQName,
-            final YangInstanceIdentifier.NodeIdentifierWithPredicates nodeId) {
+            final NodeIdentifierWithPredicates nodeId) {
         checkListKey(childNode, keyQName, nodeId);
 
-        Object expectedValue = nodeId.getKeyValues().get(keyQName);
-        Object actualValue = childNode.getValue();
+        final Object expected = nodeId.getKeyValues().get(keyQName);
+        final Object actual = childNode.getValue();
+
+        // Objects.equals() does not deal with arrays, but is faster
+        if (!Objects.equals(expected, actual) && !Objects.deepEquals(expected, actual)) {
+            throw new IllegalListKeyException(keyQName, nodeId, actual, expected);
+        }
     }
 
-    public static void checkListKey(final DataContainerChild<?, ?> childNode, final QName keyQName, final YangInstanceIdentifier.NodeIdentifierWithPredicates nodeId) {
+    public static void checkListKey(final DataContainerChild<?, ?> childNode, final QName keyQName, final NodeIdentifierWithPredicates nodeId) {
         if (childNode == null) {
             throw new IllegalListKeyException(keyQName, nodeId);
         }
     }
 
-    static final class IllegalChildException extends DataValidationException {
+    private static final class IllegalChildException extends DataValidationException {
         private static final long serialVersionUID = 1L;
 
-        public IllegalChildException(final YangInstanceIdentifier.PathArgument child, final DataNodeContainer schema,
+        private IllegalChildException(final YangInstanceIdentifier.PathArgument child, final DataNodeContainer schema,
                 final Set<QName> childNodes, final Set<YangInstanceIdentifier.AugmentationIdentifier> augments) {
             super(String.format("Unknown child node: %s, does not belong to: %s as a direct child. "
                     + "Direct child nodes: %s, augmented child nodes: %s", child, schema, childNodes, augments));
         }
 
-        public IllegalChildException(final YangInstanceIdentifier.PathArgument child, final ChoiceNode schema) {
+        private IllegalChildException(final YangInstanceIdentifier.PathArgument child, final ChoiceSchemaNode schema) {
             super(String.format("Unknown child node: %s, not detected in choice: %s", child, schema));
         }
 
-        public IllegalChildException(final YangInstanceIdentifier.PathArgument child, final DataSchemaNode schema, final Set<QName> childNodes) {
+        private IllegalChildException(final YangInstanceIdentifier.PathArgument child, final DataSchemaNode schema, final Set<QName> childNodes) {
             super(String.format("Unknown child node: %s, does not belong to: %s as a child. "
                     + "Child nodes: %s", child, schema, childNodes));
         }
     }
 
-    static final class IllegalListKeyException extends DataValidationException {
+    private static final class IllegalListKeyException extends DataValidationException {
         private static final long serialVersionUID = 1L;
 
-        public IllegalListKeyException(final QName keyQName, final YangInstanceIdentifier.NodeIdentifierWithPredicates id) {
+        private IllegalListKeyException(final QName keyQName, final NodeIdentifierWithPredicates id) {
             super(String.format("Key value not present for key: %s, in: %s", keyQName, id));
         }
 
-        public IllegalListKeyException(final QName keyQName, final YangInstanceIdentifier.NodeIdentifierWithPredicates id, final Object actualValue, final Object expectedValue) {
+        private IllegalListKeyException(final QName keyQName, final NodeIdentifierWithPredicates id, final Object actualValue, final Object expectedValue) {
             super(String.format("Illegal value for key: %s, in: %s, actual value: %s, expected value from key: %s", keyQName, id, actualValue, expectedValue));
         }
     }
index b6ac22617abcb44feb63367c750a764c5ef9a23c..1b53f7c66da682ac4f33cfba8d8f2e1a4e0c1d16 100644 (file)
@@ -8,13 +8,14 @@
 package org.opendaylight.yangtools.yang.data.impl.schema.nodes;
 
 import com.google.common.base.Optional;
+import java.util.Collection;
 import java.util.Map;
 import org.opendaylight.yangtools.concepts.Immutable;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
 
-public abstract class AbstractImmutableDataContainerNode<K extends PathArgument> extends AbstractImmutableNormalizedNode<K, Iterable<DataContainerChild<? extends PathArgument, ?>>> implements Immutable, DataContainerNode<K> {
+public abstract class AbstractImmutableDataContainerNode<K extends PathArgument> extends AbstractImmutableNormalizedNode<K, Collection<DataContainerChild<? extends PathArgument, ?>>> implements Immutable, DataContainerNode<K> {
     private final Map<PathArgument, DataContainerChild<? extends PathArgument, ?>> children;
 
     public AbstractImmutableDataContainerNode(
@@ -30,7 +31,7 @@ public abstract class AbstractImmutableDataContainerNode<K extends PathArgument>
     }
 
     @Override
-    public final Iterable<DataContainerChild<? extends PathArgument, ?>> getValue() {
+    public final Collection<DataContainerChild<? extends PathArgument, ?>> getValue() {
         return children.values();
     }
 
index 319752d282bf61a3b8ae43ef6e42eb8701b7d37e..abb4e240810e9ab264f2dd99595fbc861fe9277a 100644 (file)
@@ -16,8 +16,10 @@ import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
@@ -30,13 +32,14 @@ import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
  *            type of resulting/serialized element from NormalizedNode
  */
 public interface FromNormalizedNodeSerializerFactory<E> {
-       FromNormalizedNodeSerializer<E, AugmentationNode, AugmentationSchema> getAugmentationNodeSerializer();
-       FromNormalizedNodeSerializer<E, ChoiceNode, org.opendaylight.yangtools.yang.model.api.ChoiceNode> getChoiceNodeSerializer();
-       FromNormalizedNodeSerializer<E, ContainerNode, ContainerSchemaNode> getContainerNodeSerializer();
-       FromNormalizedNodeSerializer<E, LeafNode<?>, LeafSchemaNode> getLeafNodeSerializer();
-       FromNormalizedNodeSerializer<E, LeafSetEntryNode<?>, LeafListSchemaNode> getLeafSetEntryNodeSerializer();
-       FromNormalizedNodeSerializer<E, LeafSetNode<?>, LeafListSchemaNode> getLeafSetNodeSerializer();
-       FromNormalizedNodeSerializer<E, MapEntryNode, ListSchemaNode> getMapEntryNodeSerializer();
-       FromNormalizedNodeSerializer<E, MapNode, ListSchemaNode> getMapNodeSerializer();
-       FromNormalizedNodeSerializer<E, AnyXmlNode, AnyXmlSchemaNode> getAnyXmlNodeSerializer();
+    FromNormalizedNodeSerializer<E, AugmentationNode, AugmentationSchema> getAugmentationNodeSerializer();
+    FromNormalizedNodeSerializer<E, ChoiceNode, ChoiceSchemaNode> getChoiceNodeSerializer();
+    FromNormalizedNodeSerializer<E, ContainerNode, ContainerSchemaNode> getContainerNodeSerializer();
+    FromNormalizedNodeSerializer<E, LeafNode<?>, LeafSchemaNode> getLeafNodeSerializer();
+    FromNormalizedNodeSerializer<E, LeafSetEntryNode<?>, LeafListSchemaNode> getLeafSetEntryNodeSerializer();
+    FromNormalizedNodeSerializer<E, LeafSetNode<?>, LeafListSchemaNode> getLeafSetNodeSerializer();
+    FromNormalizedNodeSerializer<E, MapEntryNode, ListSchemaNode> getMapEntryNodeSerializer();
+    FromNormalizedNodeSerializer<E, MapNode, ListSchemaNode> getMapNodeSerializer();
+    FromNormalizedNodeSerializer<E, UnkeyedListNode, ListSchemaNode> getUnkeyedListNodeSerializer();
+    FromNormalizedNodeSerializer<E, AnyXmlNode, AnyXmlSchemaNode> getAnyXmlNodeSerializer();
 }
index 7c2700f7c4139f83208845e570c194b1d445a5aa..f34ca9bc13ab32ae6f31a4daf3779055885b4fdc 100644 (file)
@@ -16,8 +16,12 @@ import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
+import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
@@ -30,13 +34,16 @@ import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
  *            type of element to be parsed into NormalizedNode
  */
 public interface ToNormalizedNodeParserFactory<E> {
-       ToNormalizedNodeParser<E, AugmentationNode, AugmentationSchema> getAugmentationNodeParser();
-       ToNormalizedNodeParser<E, ChoiceNode, org.opendaylight.yangtools.yang.model.api.ChoiceNode> getChoiceNodeParser();
-       ToNormalizedNodeParser<E, ContainerNode, ContainerSchemaNode> getContainerNodeParser();
-       ToNormalizedNodeParser<E, LeafNode<?>, LeafSchemaNode> getLeafNodeParser();
-       ToNormalizedNodeParser<E, LeafSetEntryNode<?>, LeafListSchemaNode> getLeafSetEntryNodeParser();
-       ToNormalizedNodeParser<E, LeafSetNode<?>, LeafListSchemaNode> getLeafSetNodeParser();
-       ToNormalizedNodeParser<E, MapEntryNode, ListSchemaNode> getMapEntryNodeParser();
-       ToNormalizedNodeParser<E, MapNode, ListSchemaNode> getMapNodeParser();
-        ToNormalizedNodeParser<E, AnyXmlNode, AnyXmlSchemaNode> getAnyXmlNodeParser();
+    ToNormalizedNodeParser<E, AugmentationNode, AugmentationSchema> getAugmentationNodeParser();
+    ToNormalizedNodeParser<E, ChoiceNode, ChoiceSchemaNode> getChoiceNodeParser();
+    ToNormalizedNodeParser<E, ContainerNode, ContainerSchemaNode> getContainerNodeParser();
+    ToNormalizedNodeParser<E, LeafNode<?>, LeafSchemaNode> getLeafNodeParser();
+    ToNormalizedNodeParser<E, LeafSetEntryNode<?>, LeafListSchemaNode> getLeafSetEntryNodeParser();
+    ToNormalizedNodeParser<E, LeafSetNode<?>, LeafListSchemaNode> getLeafSetNodeParser();
+    ToNormalizedNodeParser<E, MapEntryNode, ListSchemaNode> getMapEntryNodeParser();
+    ToNormalizedNodeParser<E, MapNode, ListSchemaNode> getMapNodeParser();
+    ToNormalizedNodeParser<E, UnkeyedListNode, ListSchemaNode> getUnkeyedListNodeParser();
+    ToNormalizedNodeParser<E, UnkeyedListEntryNode, ListSchemaNode> getUnkeyedListEntryNodeParser();
+    ToNormalizedNodeParser<E, AnyXmlNode, AnyXmlSchemaNode> getAnyXmlNodeParser();
+    ToNormalizedNodeParser<E, OrderedMapNode, ListSchemaNode> getOrderedListNodeParser();
 }
index 7fec679d1d7033fe63a6e7fc701b1f9a44b0e400..4a75a3faa3a2191e9bb9390e4e8f1ccbde9bb776 100644 (file)
  */
 package org.opendaylight.yangtools.yang.data.impl.schema.transform.base;
 
-import com.google.common.base.Optional;
-import com.google.common.collect.ImmutableMap;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
 import java.util.Set;
-
-import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
-import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-import org.opendaylight.yangtools.yang.model.api.Status;
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.UsesNode;
+import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
 
 /**
  * Proxy for AugmentationSchema. Child node schemas are replaced with actual schemas from parent.
+ *
+ * @deprecated Replaced with {@link EffectiveAugmentationSchema}.
  */
-public final class AugmentationSchemaProxy implements AugmentationSchema {
-    private final AugmentationSchema delegate;
-    private final Set<DataSchemaNode> realChildSchemas;
-    private final Map<QName, DataSchemaNode> mappedChildSchemas;
-
-    public AugmentationSchemaProxy(final AugmentationSchema augmentSchema, final Set<DataSchemaNode> realChildSchemas) {
-        this.delegate = augmentSchema;
-        this.realChildSchemas = realChildSchemas;
-
-        final Map<QName, DataSchemaNode> m = new HashMap<>(realChildSchemas.size());
-        for (DataSchemaNode realChildSchema : realChildSchemas) {
-            m.put(realChildSchema.getQName(), realChildSchema);
-        }
-
-        this.mappedChildSchemas = ImmutableMap.copyOf(m);
-    }
+@Deprecated
+public final class AugmentationSchemaProxy extends EffectiveAugmentationSchema {
 
-    @Override
-    public RevisionAwareXPath getWhenCondition() {
-        return delegate.getWhenCondition();
-    }
-
-    @Override
-    public String getDescription() {
-        return delegate.getDescription();
-    }
-
-    @Override
-    public String getReference() {
-        return delegate.getReference();
-    }
-
-    @Override
-    public Status getStatus() {
-        return delegate.getStatus();
-    }
 
-    @Override
-    public SchemaPath getTargetPath() {
-        return delegate.getTargetPath();
-    }
-
-    @Override
-    public List<UnknownSchemaNode> getUnknownSchemaNodes() {
-        return delegate.getUnknownSchemaNodes();
-    }
-
-    @Override
-    public Set<TypeDefinition<?>> getTypeDefinitions() {
-        return delegate.getTypeDefinitions();
-    }
-
-    @Override
-    public Set<DataSchemaNode> getChildNodes() {
-        return realChildSchemas;
-    }
-
-    @Override
-    public Set<GroupingDefinition> getGroupings() {
-        return delegate.getGroupings();
-    }
-
-    @Override
-    public DataSchemaNode getDataChildByName(final QName name) {
-        return mappedChildSchemas.get(name);
-    }
-
-    @Override
-    public DataSchemaNode getDataChildByName(final String name) {
-        // Unused
-        throw new UnsupportedOperationException("Unable to retrieve child node by name");
-    }
-
-    @Override
-    public Set<UsesNode> getUses() {
-        return delegate.getUses();
+    public AugmentationSchemaProxy(final AugmentationSchema augmentSchema, final Set<DataSchemaNode> realChildSchemas) {
+       super(augmentSchema,realChildSchemas);
     }
 
-    @Override
-    public Optional<AugmentationSchema> getOriginalDefinition() {
-        return delegate.getOriginalDefinition();
-    }
 }
index 27303670b3650868ec3092525c49988074b369cd..7ad460dc1918758ebe7f396c6f502ca6714023b2 100644 (file)
@@ -9,7 +9,7 @@ package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser;
 
 import com.google.common.base.Preconditions;
 import com.google.common.collect.Iterables;
-import org.opendaylight.yangtools.yang.data.api.Node;
+import javax.xml.transform.dom.DOMSource;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.AnyXmlNode;
 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
@@ -31,9 +31,9 @@ public abstract class AnyXmlNodeBaseParser<E> implements
         Preconditions.checkArgument(size == 1, "Elements mapped to any-xml node illegal count: %s", size);
 
         final E e = elements.iterator().next();
-        Node<?> value = parseAnyXml(e, schema);
+        DOMSource value = parseAnyXml(e, schema);
 
-        NormalizedNodeAttrBuilder<NodeIdentifier, Node<?>, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder(schema);
+        NormalizedNodeAttrBuilder<NodeIdentifier, DOMSource, AnyXmlNode> anyXmlBuilder = Builders.anyXmlBuilder(schema);
 
         return anyXmlBuilder.withValue(value).build();
     }
@@ -46,6 +46,6 @@ public abstract class AnyXmlNodeBaseParser<E> implements
      * @param schema schema for leaf
      * @return parsed element as an Object
      */
-    protected abstract Node<?> parseAnyXml(E element, AnyXmlSchemaNode schema);
+    protected abstract DOMSource parseAnyXml(E element, AnyXmlSchemaNode schema);
 
 }
index 310ef838bd5c3e8dae3017968565e0a89d28ae67..83fdc123cd14fabfa88378ea829ceb283589892e 100644 (file)
@@ -10,15 +10,14 @@ package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser;
 import java.util.Collections;
 import java.util.Map;
 import java.util.Set;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 
 /**
@@ -30,28 +29,28 @@ public abstract class AugmentationNodeBaseParser<E> extends
         BaseDispatcherParser<E,AugmentationNode, AugmentationSchema> {
 
     @Override
-    protected final DataContainerNodeBuilder<YangInstanceIdentifier.AugmentationIdentifier, AugmentationNode> getBuilder(AugmentationSchema schema) {
+    protected final DataContainerNodeBuilder<YangInstanceIdentifier.AugmentationIdentifier, AugmentationNode> getBuilder(final AugmentationSchema schema) {
         return Builders.augmentationBuilder(schema);
     }
 
     @Override
-    protected final Set<DataSchemaNode> getRealSchemasForAugment(AugmentationSchema schema, AugmentationSchema augmentSchema) {
+    protected final Set<DataSchemaNode> getRealSchemasForAugment(final AugmentationSchema schema, final AugmentationSchema augmentSchema) {
         return SchemaUtils.getRealSchemasForAugment(schema, augmentSchema);
     }
 
 
     @Override
-    protected final DataSchemaNode getSchemaForChild(AugmentationSchema schema, QName childQName) {
+    protected final DataSchemaNode getSchemaForChild(final AugmentationSchema schema, final QName childQName) {
         return SchemaUtils.findSchemaForChild(schema, childQName);
     }
 
     @Override
-    protected final Map<QName, ChoiceNode> mapChildElementsFromChoices(AugmentationSchema schema) {
+    protected final Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final AugmentationSchema schema) {
         return SchemaUtils.mapChildElementsFromChoices(schema);
     }
 
     @Override
-    protected final Map<QName, AugmentationSchema> mapChildElementsFromAugments(AugmentationSchema schema) {
+    protected final Map<QName, AugmentationSchema> mapChildElementsFromAugments(final AugmentationSchema schema) {
         return Collections.emptyMap();
     }
 }
index ed458c6c65c07ab4281098b6ecbde32a50e01f9c..fba872d2f7fc1d29049549447669b9c73a30a14f 100644 (file)
@@ -21,10 +21,10 @@ import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.AttributesBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParser;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.AugmentationSchemaProxy;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
 
 /**
  * Abstract(base) Parser for DataContainerNodes e.g. ContainerNode, AugmentationNode.
@@ -60,7 +60,7 @@ public abstract class BaseDispatcherParser<E, N extends DataContainerNode<?>, S>
      * @return map from QName to ChoiceNode schema of child nodes that are
      *         contained within a choice statement under current schema.
      */
-    protected abstract Map<QName, ChoiceNode> mapChildElementsFromChoices(S schema);
+    protected abstract Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(S schema);
 
     /**
      *
@@ -89,7 +89,7 @@ public abstract class BaseDispatcherParser<E, N extends DataContainerNode<?>, S>
     protected abstract NodeParserDispatcher<E> getDispatcher();
 
     @Override
-    public N parse(Iterable<E> elements, S schema) {
+    public N parse(final Iterable<E> elements, final S schema) {
 
         checkAtLeastOneNode(schema, elements);
 
@@ -103,8 +103,8 @@ public abstract class BaseDispatcherParser<E, N extends DataContainerNode<?>, S>
         LinkedListMultimap<AugmentationSchema, E> augmentsToElements = LinkedListMultimap.create();
 
         // Map child nodes from choices
-        Map<QName, ChoiceNode> mappedChoiceChildNodes = mapChildElementsFromChoices(schema);
-        LinkedListMultimap<ChoiceNode, E> choicesToElements = LinkedListMultimap.create();
+        Map<QName, ChoiceSchemaNode> mappedChoiceChildNodes = mapChildElementsFromChoices(schema);
+        LinkedListMultimap<ChoiceSchemaNode, E> choicesToElements = LinkedListMultimap.create();
 
         // process Child nodes
         for (QName childPartialQName : mappedChildElements.keySet()) {
@@ -117,7 +117,7 @@ public abstract class BaseDispatcherParser<E, N extends DataContainerNode<?>, S>
                 augmentsToElements.putAll(augmentationSchema, childrenForQName);
                 // Choices
             } else if (isMarkedAs(mappedChoiceChildNodes, childSchema.getQName())) {
-                ChoiceNode choiceSchema = mappedChoiceChildNodes.get(childSchema.getQName());
+                ChoiceSchemaNode choiceSchema = mappedChoiceChildNodes.get(childSchema.getQName());
                 choicesToElements.putAll(choiceSchema, childrenForQName);
                 // Regular child nodes
             } else {
@@ -128,14 +128,14 @@ public abstract class BaseDispatcherParser<E, N extends DataContainerNode<?>, S>
         }
 
         // TODO ordering is not preserved for choice and augment elements
-        for (ChoiceNode choiceSchema : choicesToElements.keySet()) {
+        for (ChoiceSchemaNode choiceSchema : choicesToElements.keySet()) {
             containerBuilder.withChild(getDispatcher().dispatchChildElement(choiceSchema,
                     choicesToElements.get(choiceSchema)));
         }
 
         for (AugmentationSchema augmentSchema : augmentsToElements.keySet()) {
             Set<DataSchemaNode> realChildSchemas = getRealSchemasForAugment(schema, augmentSchema);
-            AugmentationSchemaProxy augSchemaProxy = new AugmentationSchemaProxy(augmentSchema, realChildSchemas);
+            EffectiveAugmentationSchema augSchemaProxy = new EffectiveAugmentationSchema(augmentSchema, realChildSchemas);
             containerBuilder.withChild(getDispatcher().dispatchChildElement(augSchemaProxy, augmentsToElements.get(augmentSchema)));
         }
 
@@ -149,21 +149,21 @@ public abstract class BaseDispatcherParser<E, N extends DataContainerNode<?>, S>
         return containerBuilder.build();
     }
 
-    protected Map<QName, String> getAttributes(E e) {
+    protected Map<QName, String> getAttributes(final E e) {
         return Collections.emptyMap();
     }
 
-    private boolean isMarkedAs(Map<QName, ?> mappedAugmentChildNodes, QName qName) {
+    private boolean isMarkedAs(final Map<QName, ?> mappedAugmentChildNodes, final QName qName) {
         return mappedAugmentChildNodes.containsKey(qName);
     }
 
-    protected void checkOnlyOneNode(S schema, Iterable<E> childNodes) {
+    protected void checkOnlyOneNode(final S schema, final Iterable<E> childNodes) {
         final int size = Iterables.size(childNodes);
         Preconditions.checkArgument(size == 1,
                 "Node detected multiple times, should be 1, identified by: %s, found: %s", schema, childNodes);
     }
 
-    private void checkAtLeastOneNode(S schema, Iterable<E> childNodes) {
+    private void checkAtLeastOneNode(final S schema, final Iterable<E> childNodes) {
         Preconditions.checkArgument(!Iterables.isEmpty(childNodes),
                 "Node detected 0 times, should be at least 1, identified by: %s, found: %s", schema, childNodes);
     }
index c003ed5e5f54f483652718ff9ce8eb2011c9531d..a82f71685ad642e578b54fdc6d846a5409e9dbe0 100644 (file)
@@ -7,40 +7,37 @@
  */
 package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser;
 
+import com.google.common.collect.Sets;
+import java.util.LinkedHashMap;
 import java.util.Map;
 import java.util.Set;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 
-import com.google.common.collect.Maps;
-import com.google.common.collect.Sets;
-
 /**
  * Abstract(base) parser for ChoiceNodes, parses elements of type E.
  *
  * @param <E> type of elements to be parsed
  */
-public abstract class ChoiceNodeBaseParser<E> extends
-        BaseDispatcherParser<E, ChoiceNode, org.opendaylight.yangtools.yang.model.api.ChoiceNode> {
+public abstract class ChoiceNodeBaseParser<E> extends BaseDispatcherParser<E, ChoiceNode, ChoiceSchemaNode> {
 
     @Override
     protected final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ChoiceNode> getBuilder(
-            org.opendaylight.yangtools.yang.model.api.ChoiceNode schema) {
+            final ChoiceSchemaNode schema) {
         return Builders.choiceBuilder(schema);
     }
 
     @Override
-    protected final Set<DataSchemaNode> getRealSchemasForAugment(org.opendaylight.yangtools.yang.model.api.ChoiceNode schema,
-            AugmentationSchema augmentSchema) {
+    protected final Set<DataSchemaNode> getRealSchemasForAugment(final ChoiceSchemaNode schema, final AugmentationSchema augmentSchema) {
         Set<DataSchemaNode> fromAllCases = Sets.newHashSet();
 
         fromAllCases.addAll(SchemaUtils.getRealSchemasForAugment(schema, augmentSchema));
@@ -53,15 +50,14 @@ public abstract class ChoiceNodeBaseParser<E> extends
     }
 
     @Override
-    protected final DataSchemaNode getSchemaForChild(org.opendaylight.yangtools.yang.model.api.ChoiceNode schema,
-            QName childQName) {
+    protected final DataSchemaNode getSchemaForChild(final ChoiceSchemaNode schema,
+            final QName childQName) {
         return SchemaUtils.findSchemaForChild(schema, childQName);
     }
 
     @Override
-    protected final Map<QName, org.opendaylight.yangtools.yang.model.api.ChoiceNode> mapChildElementsFromChoices(
-            org.opendaylight.yangtools.yang.model.api.ChoiceNode schema) {
-        Map<QName, org.opendaylight.yangtools.yang.model.api.ChoiceNode> mappedChoices = Maps.newLinkedHashMap();
+    protected final Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final ChoiceSchemaNode schema) {
+        Map<QName, ChoiceSchemaNode> mappedChoices = new LinkedHashMap<>();
 
         for (ChoiceCaseNode choiceCaseNode : schema.getCases()) {
             mappedChoices.putAll(SchemaUtils.mapChildElementsFromChoices(choiceCaseNode));
@@ -71,9 +67,8 @@ public abstract class ChoiceNodeBaseParser<E> extends
     }
 
     @Override
-    protected final Map<QName, AugmentationSchema> mapChildElementsFromAugments(
-            org.opendaylight.yangtools.yang.model.api.ChoiceNode schema) {
-        Map<QName, AugmentationSchema> mappedAugments = Maps.newLinkedHashMap();
+    protected final Map<QName, AugmentationSchema> mapChildElementsFromAugments(final ChoiceSchemaNode schema) {
+        Map<QName, AugmentationSchema> mappedAugments = new LinkedHashMap<>();
 
         for (ChoiceCaseNode choiceCaseNode : schema.getCases()) {
             mappedAugments.putAll(SchemaUtils.mapChildElementsFromAugments(choiceCaseNode));
index 05213f9e3696177f54ce977803103634e124a983..5fff36d5499e48d0bb8a3026cf6217bc256756c8 100644 (file)
@@ -9,16 +9,15 @@ package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser;
 
 import java.util.Map;
 import java.util.Set;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 
@@ -32,33 +31,33 @@ public abstract class ContainerNodeBaseParser<E> extends
 
     @Override
     protected final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> getBuilder(
-            ContainerSchemaNode schema) {
+            final ContainerSchemaNode schema) {
         return Builders.containerBuilder(schema);
     }
 
     @Override
-    public final ContainerNode parse(Iterable<E> elements, ContainerSchemaNode schema) {
+    public final ContainerNode parse(final Iterable<E> elements, final ContainerSchemaNode schema) {
         checkOnlyOneNode(schema, elements);
         return super.parse(elements, schema);
     }
 
     @Override
-    protected final Set<DataSchemaNode> getRealSchemasForAugment(ContainerSchemaNode schema, AugmentationSchema augmentSchema) {
+    protected final Set<DataSchemaNode> getRealSchemasForAugment(final ContainerSchemaNode schema, final AugmentationSchema augmentSchema) {
         return SchemaUtils.getRealSchemasForAugment((AugmentationTarget) schema, augmentSchema);
     }
 
     @Override
-    protected final DataSchemaNode getSchemaForChild(ContainerSchemaNode schema, QName childQName) {
+    protected final DataSchemaNode getSchemaForChild(final ContainerSchemaNode schema, final QName childQName) {
         return SchemaUtils.findSchemaForChild(schema, childQName);
     }
 
     @Override
-    protected final Map<QName, ChoiceNode> mapChildElementsFromChoices(ContainerSchemaNode schema) {
+    protected final Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final ContainerSchemaNode schema) {
         return SchemaUtils.mapChildElementsFromChoices(schema);
     }
 
     @Override
-    protected final Map<QName, AugmentationSchema> mapChildElementsFromAugments(ContainerSchemaNode schema) {
+    protected final Map<QName, AugmentationSchema> mapChildElementsFromAugments(final ContainerSchemaNode schema) {
         return SchemaUtils.mapChildElementsFromAugments(schema);
     }
 
@@ -9,58 +9,50 @@ package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser;
 
 import java.util.Map;
 import java.util.Set;
-
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
+import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 
 /**
- * Abstract(base) parser for MapEntryNodes, parses elements of type E.
+ * Abstract(base) parser for ListNodes (MapNode, UnkeyedListNode), parses elements of type E.
  *
- * @param <E> type of elements to be parsed
+ * @param <E>
+ *            type of elements to be parsed
  */
-public abstract class MapEntryNodeBaseParser<E> extends BaseDispatcherParser<E, MapEntryNode, ListSchemaNode> {
-
-    @Override
-    protected final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> getBuilder(
-            ListSchemaNode schema) {
-        return Builders.mapEntryBuilder(schema);
-    }
-
-    @Override
-    public final MapEntryNode parse(Iterable<E> elements, ListSchemaNode schema) {
-        checkOnlyOneNode(schema, elements);
-        return super.parse(elements, schema);
-    }
+public abstract class ListEntryNodeBaseParser<E, N extends DataContainerNode<?>> extends
+        BaseDispatcherParser<E, N, ListSchemaNode> {
 
     @Override
-    protected final Set<DataSchemaNode> getRealSchemasForAugment(ListSchemaNode schema, AugmentationSchema augmentSchema) {
+    protected final Set<DataSchemaNode> getRealSchemasForAugment(final ListSchemaNode schema, final AugmentationSchema augmentSchema) {
         return SchemaUtils.getRealSchemasForAugment((AugmentationTarget) schema, augmentSchema);
     }
 
     @Override
-    protected final DataSchemaNode getSchemaForChild(ListSchemaNode schema, QName childQName) {
+    protected final DataSchemaNode getSchemaForChild(final ListSchemaNode schema, final QName childQName) {
         return SchemaUtils.findSchemaForChild(schema, childQName);
     }
 
     @Override
-    protected final Map<QName, ChoiceNode> mapChildElementsFromChoices(ListSchemaNode schema) {
+    protected final Map<QName, ChoiceSchemaNode> mapChildElementsFromChoices(final ListSchemaNode schema) {
         return SchemaUtils.mapChildElementsFromChoices(schema);
     }
 
     @Override
-    protected final Map<QName, AugmentationSchema> mapChildElementsFromAugments(ListSchemaNode schema) {
+    protected final Map<QName, AugmentationSchema> mapChildElementsFromAugments(final ListSchemaNode schema) {
         return SchemaUtils.mapChildElementsFromAugments(schema);
     }
 
+    @Override
+    public final N parse(final Iterable<E> elements, final ListSchemaNode schema) {
+        checkOnlyOneNode(schema, elements);
+        return super.parse(elements, schema);
+    }
+
     @Override
     protected abstract Map<QName, String> getAttributes(E e);
-}
+}
\ No newline at end of file
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/parser/ListNodeBaseParser.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/parser/ListNodeBaseParser.java
new file mode 100644 (file)
index 0000000..67c97a7
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser;
+
+import java.util.Collections;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParser;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+/**
+ * Abstract(base) parser for ListNodes (MapNode, UnkeyedListNode), parses elements of type E.
+ *
+ * @param <E>
+ *            type of elements to be parsed
+ */
+public abstract class ListNodeBaseParser<E, N extends NormalizedNode<?, ?>, O extends NormalizedNode<YangInstanceIdentifier.NodeIdentifier, ?>, S extends ListSchemaNode>
+        implements ToNormalizedNodeParser<E, O, S> {
+
+    @Override
+    public final O parse(Iterable<E> childNodes, S schema) {
+        CollectionNodeBuilder<N, O> listBuilder = provideBuilder(schema);
+        for (E childNode : childNodes) {
+            N listChild = getListEntryNodeParser().parse(Collections.singletonList(childNode), schema);
+            listBuilder.withChild(listChild);
+        }
+
+        return listBuilder.build();
+    }
+
+    /**
+     *
+     * @return parser for inner ListEntryNodes used to parse every entry of ListNode, might be the same instance in case
+     *         its immutable
+     */
+    protected abstract ToNormalizedNodeParser<E, N, S> getListEntryNodeParser();
+
+    /**
+     *
+     * @return prepares builder which will contain entries of list according to concrete list type
+     */
+    protected abstract CollectionNodeBuilder<N, O> provideBuilder(S schema);
+}
index 581d5f4b781633d4f0da8509d25a38781fbcc6cb..a57a694e126668684bf9310804aa0f50aea7f062 100644 (file)
@@ -9,48 +9,20 @@ package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser;
 
 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
-import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParser;
 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 
-import java.util.Collections;
-
 /**
  * Abstract(base) parser for MapNodes, parses elements of type E.
  *
- * @param <E> type of elements to be parsed
+ * @param <E>
+ *            type of elements to be parsed
  */
-public abstract class MapNodeBaseParser<E> implements ToNormalizedNodeParser<E, MapNode, ListSchemaNode> {
-
-    @Override
-    public final MapNode parse(Iterable<E> childNodes, ListSchemaNode schema) {
-        if (schema.isUserOrdered()) {
-            CollectionNodeBuilder<MapEntryNode, OrderedMapNode> listBuilder = Builders.orderedMapBuilder(schema);
-
-            for (E childNode : childNodes) {
-                MapEntryNode listChild = getMapEntryNodeParser().parse(Collections.singletonList(childNode), schema);
-                listBuilder.withChild(listChild);
-            }
+public abstract class MapNodeBaseParser<E> extends ListNodeBaseParser<E, MapEntryNode, MapNode, ListSchemaNode> {
 
-            return listBuilder.build();
-        } else {
-            CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = Builders.mapBuilder(schema);
-
-            for (E childNode : childNodes) {
-                MapEntryNode listChild = getMapEntryNodeParser().parse(Collections.singletonList(childNode), schema);
-                listBuilder.withChild(listChild);
-            }
-
-            return listBuilder.build();
-        }
+    protected CollectionNodeBuilder<MapEntryNode, MapNode> provideBuilder(ListSchemaNode schema) {
+        return Builders.mapBuilder(schema);
     }
 
-    /**
-     *
-     * @return parser for inner MapEntryNodes used to parse every entry of MapNode, might be the same instance in case its immutable
-     */
-    protected abstract ToNormalizedNodeParser<E, MapEntryNode, ListSchemaNode> getMapEntryNodeParser();
-
-}
+}
\ No newline at end of file
index 220b2cb04d4058e081bee585bc516bc0e9608319..3d79451b75b403ccecc482d608753dc4b8254d16 100644 (file)
@@ -13,7 +13,7 @@ import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
 import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParserFactory;
 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
@@ -41,7 +41,7 @@ public interface NodeParserDispatcher<E> {
         }
 
         @Override
-        public final DataContainerChild<?, ?> dispatchChildElement(Object schema, List<E> childNodes) {
+        public final DataContainerChild<?, ?> dispatchChildElement(final Object schema, final List<E> childNodes) {
             Preconditions.checkArgument(!childNodes.isEmpty());
 
             if (schema instanceof ContainerSchemaNode) {
@@ -51,9 +51,16 @@ public interface NodeParserDispatcher<E> {
             } else if (schema instanceof LeafListSchemaNode) {
                 return factory.getLeafSetNodeParser().parse(childNodes, (LeafListSchemaNode) schema);
             } else if (schema instanceof ListSchemaNode) {
-                return factory.getMapNodeParser().parse(childNodes, (ListSchemaNode) schema);
-            } else if (schema instanceof ChoiceNode) {
-                return factory.getChoiceNodeParser().parse(childNodes, (ChoiceNode) schema);
+                final ListSchemaNode listSchemaNode = (ListSchemaNode)schema;
+                if (listSchemaNode.isUserOrdered()) {
+                    return factory.getOrderedListNodeParser().parse(childNodes, listSchemaNode);
+                } else if (listSchemaNode.getKeyDefinition().isEmpty()) {
+                    return factory.getUnkeyedListNodeParser().parse(childNodes, listSchemaNode);
+                } else {
+                    return factory.getMapNodeParser().parse(childNodes, listSchemaNode);
+                }
+            } else if (schema instanceof ChoiceSchemaNode) {
+                return factory.getChoiceNodeParser().parse(childNodes, (ChoiceSchemaNode) schema);
             } else if (schema instanceof AugmentationSchema) {
                 return factory.getAugmentationNodeParser().parse(childNodes, (AugmentationSchema) schema);
             } else if (schema instanceof AnyXmlSchemaNode) {
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/parser/OrderedListNodeBaseParser.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/parser/OrderedListNodeBaseParser.java
new file mode 100644 (file)
index 0000000..6278acc
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser;
+
+import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+/**
+ * Abstract(base) parser for OrderedListNodes, parses elements of type E.
+ *
+ * @param <E>
+ *            type of elements to be parsed
+ */
+public abstract class OrderedListNodeBaseParser<E> extends
+        ListNodeBaseParser<E, MapEntryNode, OrderedMapNode, ListSchemaNode> {
+    @Override
+    protected CollectionNodeBuilder<MapEntryNode, OrderedMapNode> provideBuilder(ListSchemaNode schema) {
+        return Builders.orderedMapBuilder(schema);
+    }
+}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/parser/UnkeyedListNodeBaseParser.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/parser/UnkeyedListNodeBaseParser.java
new file mode 100644 (file)
index 0000000..14d4789
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser;
+
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+/**
+ * Abstract(base) parser for UnkeyedListNodes, parses elements of type E.
+ *
+ * @param <E>
+ *            type of elements to be parsed
+ */
+public abstract class UnkeyedListNodeBaseParser<E> extends
+        ListNodeBaseParser<E, UnkeyedListEntryNode, UnkeyedListNode, ListSchemaNode> {
+    @Override
+    protected CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> provideBuilder(ListSchemaNode schema) {
+        CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> listBuilder = Builders.unkeyedListBuilder();
+        return listBuilder.withNodeIdentifier(new NodeIdentifier(schema.getQName()));
+    }
+}
index d356508da477a498f0753f11a11b560f0e4cd626..a58ecc5a616c369a8cfbf4271b4d128da8124a3a 100644 (file)
@@ -7,21 +7,19 @@
  */
 package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer;
 
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Lists;
 import java.util.List;
 import java.util.Set;
-
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
 import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializer;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.AugmentationSchemaProxy;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
-
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Lists;
+import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
 
 /**
  * Abstract(base) Serializer for DataContainerNodes e.g. ContainerNode, AugmentationNode.
@@ -78,7 +76,7 @@ public abstract class BaseDispatcherSerializer<E, N extends DataContainerNode<?>
 
                 AugmentationSchema augSchema = getAugmentedCase(schema, (AugmentationNode) choiceChild);
                 Set<DataSchemaNode> realChildSchemas = getRealSchemasForAugment(schema, augSchema);
-                childSchema = new AugmentationSchemaProxy(augSchema, realChildSchemas);
+                childSchema = new EffectiveAugmentationSchema(augSchema, realChildSchemas);
 
             } else {
                 childSchema = getSchemaForChild(schema, choiceChild);
index fdff1aa1f296e73ef17ad872e56331c0e93a1f0b..0de18388e346428c54bf8793d2ff02d4493881e7 100644 (file)
@@ -9,7 +9,6 @@ package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializ
 
 import java.util.HashSet;
 import java.util.Set;
-
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
@@ -18,6 +17,7 @@ import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 
 /**
@@ -25,24 +25,22 @@ import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
  *
  * @param <E> type of serialized elements
  */
-public abstract class ChoiceNodeBaseSerializer<E>
-        extends
-        BaseDispatcherSerializer<E, ChoiceNode, org.opendaylight.yangtools.yang.model.api.ChoiceNode> {
+public abstract class ChoiceNodeBaseSerializer<E> extends BaseDispatcherSerializer<E, ChoiceNode, ChoiceSchemaNode> {
 
     @Override
-    protected final DataSchemaNode getSchemaForChild(final org.opendaylight.yangtools.yang.model.api.ChoiceNode schema,
+    protected final DataSchemaNode getSchemaForChild(final ChoiceSchemaNode schema,
             final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> childNode) {
         return SchemaUtils.findSchemaForChild(schema, childNode.getNodeType());
     }
 
     @Override
-    protected final AugmentationSchema getAugmentedCase(final org.opendaylight.yangtools.yang.model.api.ChoiceNode schema,
+    protected final AugmentationSchema getAugmentedCase(final ChoiceSchemaNode schema,
             final AugmentationNode augmentationNode) {
         return SchemaUtils.findSchemaForAugment(schema, augmentationNode.getIdentifier().getPossibleChildNames());
     }
 
     @Override
-    protected final Set<DataSchemaNode> getRealSchemasForAugment(final org.opendaylight.yangtools.yang.model.api.ChoiceNode schema, final AugmentationSchema augmentationSchema) {
+    protected final Set<DataSchemaNode> getRealSchemasForAugment(final ChoiceSchemaNode schema, final AugmentationSchema augmentationSchema) {
         Set<DataSchemaNode> aggregatedSchemas = new HashSet<>(SchemaUtils.getRealSchemasForAugment(schema, augmentationSchema));
 
         for (ChoiceCaseNode choiceCaseNode : schema.getCases()) {
@@ -8,11 +8,10 @@
 package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer;
 
 import java.util.Set;
-
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
-import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
@@ -20,16 +19,17 @@ import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 
 /**
- * Abstract(base) serializer for MapEntryNodes, serializes elements of type E.
+ * Abstract(base) serializer for ListEntryNodes (MapEntryNode, UnkeyedListEntryNode), serializes elements of type E.
  *
- * @param <E> type of serialized elements
+ * @param <E>
+ *            type of serialized elements
  */
-public abstract class MapEntryNodeBaseSerializer<E> extends
-        BaseDispatcherSerializer<E, MapEntryNode, ListSchemaNode> {
+public abstract class ListEntryNodeBaseSerializer<E, N extends DataContainerNode<?>> extends
+        BaseDispatcherSerializer<E, N, ListSchemaNode> {
 
     @Override
     protected final DataSchemaNode getSchemaForChild(ListSchemaNode schema,
-                                               DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> childNode) {
+            DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> childNode) {
         return SchemaUtils.findSchemaForChild(schema, childNode.getNodeType());
     }
 
@@ -39,7 +39,8 @@ public abstract class MapEntryNodeBaseSerializer<E> extends
     }
 
     @Override
-    protected final Set<DataSchemaNode> getRealSchemasForAugment(ListSchemaNode schema, AugmentationSchema augmentationSchema) {
+    protected final Set<DataSchemaNode> getRealSchemasForAugment(ListSchemaNode schema,
+            AugmentationSchema augmentationSchema) {
         return SchemaUtils.getRealSchemasForAugment((AugmentationTarget) schema, augmentationSchema);
     }
 
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/serializer/ListNodeBaseSerializer.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/serializer/ListNodeBaseSerializer.java
new file mode 100644 (file)
index 0000000..42413be
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer;
+
+import com.google.common.base.Function;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Iterables;
+import java.util.Collection;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
+import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializer;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+/**
+ * Abstract(base) serializer for ListNodes (MapNode, UnkeyedListNode), serializes elements of type E.
+ *
+ * @param <E>
+ *            type of serialized elements
+ * @param <N>
+ *            containing node type
+ * @param <O>
+ *            entry node type which is inside containing (N) type
+ */
+public abstract class ListNodeBaseSerializer<E, N extends DataContainerChild<NodeIdentifier, Collection<O>>, O extends DataContainerNode<?>>
+        implements FromNormalizedNodeSerializer<E, N, ListSchemaNode> {
+
+    @Override
+    public final Iterable<E> serialize(final ListSchemaNode schema, final N node) {
+        return Iterables.concat(Iterables.transform(node.getValue(), new Function<O, Iterable<E>>() {
+            @Override
+            public Iterable<E> apply(final O input) {
+                final Iterable<E> serializedChild = getListEntryNodeSerializer().serialize(schema, input);
+                final int size = Iterables.size(serializedChild);
+
+                Preconditions.checkState(size == 1,
+                        "Unexpected count of entries  for list serialized from: %s, should be 1, was: %s", input, size);
+                return serializedChild;
+            }
+        }));
+    }
+
+    /**
+     *
+     * @return serializer for inner ListEntryNodes (MapEntryNode, UnkeyedListEntryNode) used to serialize every entry of
+     *         ListNode, might be the same instance in case its immutable
+     */
+    protected abstract FromNormalizedNodeSerializer<E, O, ListSchemaNode> getListEntryNodeSerializer();
+}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/serializer/MapNodeBaseSerializer.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/base/serializer/MapNodeBaseSerializer.java
deleted file mode 100644 (file)
index dba2c5d..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer;
-
-import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
-import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializer;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-
-import com.google.common.base.Function;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Iterables;
-
-/**
- * Abstract(base) serializer for MapNodes, serializes elements of type E.
- *
- * @param <E> type of serialized elements
- */
-public abstract class MapNodeBaseSerializer<E> implements FromNormalizedNodeSerializer<E, MapNode, ListSchemaNode> {
-
-    @Override
-    public final Iterable<E> serialize(final ListSchemaNode schema, final MapNode node) {
-        return Iterables.concat(Iterables.transform(node.getValue(), new Function<MapEntryNode, Iterable<E>>() {
-            @Override
-            public Iterable<E> apply(MapEntryNode input) {
-                final Iterable<E> serializedChild = getMapEntryNodeDomSerializer().serialize(schema, input);
-                final int size = Iterables.size(serializedChild);
-
-                Preconditions.checkState(size == 1,
-                        "Unexpected count of entries  for list serialized from: %s, should be 1, was: %s",
-                        input, size);
-                return serializedChild;
-            }
-        }));
-    }
-
-    /**
-     *
-     * @return serializer for inner MapEntryNodes used to serialize every entry of MapNode, might be the same instance in case its immutable
-     */
-    protected abstract FromNormalizedNodeSerializer<E, MapEntryNode, ListSchemaNode> getMapEntryNodeDomSerializer();
-}
index c686c31cba4871577c415937262c62b00c5046fd..7f034e0169252177e899bf08acec0572b1b8331e 100644 (file)
@@ -19,9 +19,11 @@ import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
 import org.opendaylight.yangtools.yang.data.api.schema.MixinNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
 import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializerFactory;
 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
@@ -53,8 +55,8 @@ public interface NodeSerializerDispatcher<E> {
         }
 
         @Override
-        public final Iterable<E> dispatchChildElement(Object childSchema,
-                DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+        public final Iterable<E> dispatchChildElement(final Object childSchema,
+                final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
             if (dataContainerChild instanceof ContainerNode) {
                 return onContainerNode(childSchema, dataContainerChild);
             } else if (dataContainerChild instanceof LeafNode<?>) {
@@ -65,7 +67,9 @@ public interface NodeSerializerDispatcher<E> {
                 if (dataContainerChild instanceof LeafSetNode<?>) {
                     return onLeafListNode(childSchema, dataContainerChild);
                 } else if (dataContainerChild instanceof MapNode) {
-                    return onListNode(childSchema, dataContainerChild);
+                    return onMapNode(childSchema, dataContainerChild);
+                } else if (dataContainerChild instanceof  UnkeyedListNode) {
+                    return onUnkeyedListNode(childSchema, dataContainerChild);
                 } else if (dataContainerChild instanceof ChoiceNode) {
                     return onChoiceNode(childSchema, dataContainerChild);
                 } else if (dataContainerChild instanceof AugmentationNode) {
@@ -75,37 +79,42 @@ public interface NodeSerializerDispatcher<E> {
             throw new IllegalArgumentException("Unable to serialize " + childSchema);
         }
 
-        private Iterable<E> onAugmentationSchema(Object childSchema,
-                DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+        private Iterable<E> onAugmentationSchema(final Object childSchema,
+                final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
             checkSchemaCompatibility(childSchema, AugmentationSchema.class, dataContainerChild);
             return factory.getAugmentationNodeSerializer().serialize((AugmentationSchema) childSchema,
                     (AugmentationNode) dataContainerChild);
         }
 
-        private Iterable<E> onChoiceNode(Object childSchema,
-                DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
-            checkSchemaCompatibility(childSchema, org.opendaylight.yangtools.yang.model.api.ChoiceNode.class,
+        private Iterable<E> onChoiceNode(final Object childSchema,
+                final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+            checkSchemaCompatibility(childSchema, ChoiceSchemaNode.class,
                     dataContainerChild);
             return factory.getChoiceNodeSerializer()
-                    .serialize((org.opendaylight.yangtools.yang.model.api.ChoiceNode) childSchema,
-                            (ChoiceNode) dataContainerChild);
+                    .serialize((ChoiceSchemaNode) childSchema, (ChoiceNode) dataContainerChild);
         }
 
-        private Iterable<E> onListNode(Object childSchema,
-                DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+        private Iterable<E> onMapNode(final Object childSchema,
+                final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
             checkSchemaCompatibility(childSchema, ListSchemaNode.class, dataContainerChild);
             return factory.getMapNodeSerializer().serialize((ListSchemaNode) childSchema, (MapNode) dataContainerChild);
         }
 
-        private Iterable<E> onLeafListNode(Object childSchema,
-                DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+        private Iterable<E> onUnkeyedListNode(final Object childSchema,
+                final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+            checkSchemaCompatibility(childSchema, ListSchemaNode.class, dataContainerChild);
+            return factory.getUnkeyedListNodeSerializer().serialize((ListSchemaNode) childSchema, (UnkeyedListNode) dataContainerChild);
+        }
+
+        private Iterable<E> onLeafListNode(final Object childSchema,
+                final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
             checkSchemaCompatibility(childSchema, LeafListSchemaNode.class, dataContainerChild);
             return factory.getLeafSetNodeSerializer().serialize((LeafListSchemaNode) childSchema,
                     (LeafSetNode<?>) dataContainerChild);
         }
 
-        private Iterable<E> onLeafNode(Object childSchema,
-                DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+        private Iterable<E> onLeafNode(final Object childSchema,
+                final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
             checkSchemaCompatibility(childSchema, LeafSchemaNode.class, dataContainerChild);
             Iterable<E> elements = factory.getLeafNodeSerializer().serialize((LeafSchemaNode) childSchema,
                     (LeafNode<?>) dataContainerChild);
@@ -113,8 +122,8 @@ public interface NodeSerializerDispatcher<E> {
             return elements;
         }
 
-        private Iterable<E> onAnyXmlNode(Object childSchema,
-                DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+        private Iterable<E> onAnyXmlNode(final Object childSchema,
+                final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
             checkSchemaCompatibility(childSchema, AnyXmlSchemaNode.class, dataContainerChild);
             Iterable<E> elements = factory.getAnyXmlNodeSerializer().serialize((AnyXmlSchemaNode) childSchema,
                     (AnyXmlNode) dataContainerChild);
@@ -122,16 +131,16 @@ public interface NodeSerializerDispatcher<E> {
             return elements;
         }
 
-        private static void checkOnlyOneSerializedElement(Iterable<?> elements,
-                DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+        private static void checkOnlyOneSerializedElement(final Iterable<?> elements,
+                final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
             final int size = Iterables.size(elements);
             Preconditions.checkArgument(size == 1,
                     "Unexpected count of elements for entry serialized from: %s, should be 1, was: %s",
                     dataContainerChild, size);
         }
 
-        private Iterable<E> onContainerNode(Object childSchema,
-                DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+        private Iterable<E> onContainerNode(final Object childSchema,
+                final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
             checkSchemaCompatibility(childSchema, ContainerSchemaNode.class, dataContainerChild);
 
             Iterable<E> elements = factory.getContainerNodeSerializer().serialize((ContainerSchemaNode) childSchema,
@@ -140,8 +149,8 @@ public interface NodeSerializerDispatcher<E> {
             return elements;
         }
 
-        private static void checkSchemaCompatibility(Object childSchema, Class<?> containerSchemaNodeClass,
-                DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
+        private static void checkSchemaCompatibility(final Object childSchema, final Class<?> containerSchemaNodeClass,
+                final DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> dataContainerChild) {
             Preconditions.checkArgument(containerSchemaNodeClass.isAssignableFrom(childSchema.getClass()),
                     "Incompatible schema: %s with node: %s, expected: %s", childSchema, dataContainerChild,
                     containerSchemaNodeClass);
index eb1939604a237054c825da4e78ad9428f24e430e..6b65c05a9e375ef0934f74b1e4a8d34f8e24c704 100644 (file)
@@ -9,25 +9,29 @@ package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom;
 
 import com.google.common.collect.LinkedListMultimap;
 import com.google.common.collect.Lists;
-
 import java.net.URI;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-
 import javax.xml.XMLConstants;
 import javax.xml.stream.XMLOutputFactory;
 import javax.xml.stream.XMLStreamException;
 import javax.xml.stream.XMLStreamWriter;
 import javax.xml.transform.dom.DOMResult;
-
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.impl.codec.TypeDefinitionAwareCodec;
+import org.opendaylight.yangtools.yang.data.impl.codec.xml.InstanceIdentifierForXmlCodec;
 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlCodecProvider;
 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlStreamUtils;
 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlUtils;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
+import org.opendaylight.yangtools.yang.model.util.InstanceIdentifierType;
+import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
 import org.w3c.dom.Element;
 import org.w3c.dom.NamedNodeMap;
 import org.w3c.dom.Node;
@@ -111,4 +115,26 @@ public final class DomUtils {
         }
         return attributes;
     }
+
+    public static Object parseXmlValue(final Element xml, final XmlCodecProvider codecProvider, final DataSchemaNode schema, final TypeDefinition<?> type, final SchemaContext schemaCtx) {
+        TypeDefinition<?> baseType = XmlUtils.resolveBaseTypeFrom(type);
+        if (baseType instanceof LeafrefTypeDefinition) {
+            final LeafrefTypeDefinition leafrefTypeDefinition = (LeafrefTypeDefinition) baseType;
+            baseType = SchemaContextUtil.getBaseTypeForLeafRef(leafrefTypeDefinition, schemaCtx, schema);
+        }
+
+        String text = xml.getTextContent();
+        text = text.trim();
+        final Object value;
+
+        if (baseType instanceof InstanceIdentifierType) {
+            value = InstanceIdentifierForXmlCodec.deserialize(xml, schemaCtx);
+        } else if (baseType instanceof IdentityrefTypeDefinition) {
+            value = InstanceIdentifierForXmlCodec.toIdentity(text, xml, schemaCtx);
+        } else {
+            value = parseXmlValue(xml, codecProvider, type);
+        }
+
+        return value;
+    }
 }
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/parser/AnyXmlDomParser.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/parser/AnyXmlDomParser.java
new file mode 100644 (file)
index 0000000..450477d
--- /dev/null
@@ -0,0 +1,19 @@
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser;
+
+import com.google.common.base.Preconditions;
+import javax.xml.transform.dom.DOMSource;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.AnyXmlNodeBaseParser;
+import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
+import org.w3c.dom.Element;
+
+public class AnyXmlDomParser extends AnyXmlNodeBaseParser<Element> {
+
+    @Override
+    protected DOMSource parseAnyXml(final Element element, final AnyXmlSchemaNode schema) {
+        final QName qName = schema.getQName();
+        Preconditions.checkArgument(element.getNodeName().equals(qName.getLocalName()));
+        Preconditions.checkArgument(element.getNamespaceURI().equals(qName.getNamespace().toString()));
+        return new DOMSource(element);
+    }
+}
index a02b60b2fd24b6443596e3dd4fe4e508433b0518..af58c481543eb5b0a459fb381605d484507721ac 100644 (file)
@@ -16,16 +16,21 @@ import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
+import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlCodecProvider;
 import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParser;
 import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParserFactory;
 import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.NodeParserDispatcher;
 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.w3c.dom.Element;
 
 public final class DomToNormalizedNodeParserFactory implements ToNormalizedNodeParserFactory<Element> {
@@ -37,11 +42,37 @@ public final class DomToNormalizedNodeParserFactory implements ToNormalizedNodeP
     private final LeafSetNodeDomParser leafSetNodeParser;
     private final MapNodeDomParser mapNodeParser;
     private final MapEntryNodeDomParser mapEntryNodeParser;
+    private final UnkeyedListEntryNodeDomParser unkeyedListEntryNodeParser;
+    private final UnkeyedListNodeDomParser unkeyedListNodeParser;
+    private final OrderedListNodeDomParser orderedListNodeParser;
+    private final AnyXmlDomParser anyXmlNodeParser;
+
+    private DomToNormalizedNodeParserFactory(final XmlCodecProvider codecProvider, final SchemaContext schema) {
+        leafNodeParser = new LeafNodeDomParser(codecProvider, schema);
+        leafSetEntryNodeParser = new LeafSetEntryNodeDomParser(codecProvider, schema);
+        leafSetNodeParser = new LeafSetNodeDomParser(leafSetEntryNodeParser);
+        anyXmlNodeParser = new AnyXmlDomParser();
+
+        final NodeParserDispatcher<Element> dispatcher = new NodeParserDispatcher.BaseNodeParserDispatcher<Element>(this) {
+
+        };
+
+        containerNodeParser = new ContainerNodeDomParser(dispatcher);
+        mapEntryNodeParser = new MapEntryNodeDomParser(dispatcher);
+        mapNodeParser = new MapNodeDomParser(mapEntryNodeParser);
+        orderedListNodeParser = new OrderedListNodeDomParser(mapEntryNodeParser);
+        unkeyedListEntryNodeParser = new UnkeyedListEntryNodeDomParser(dispatcher);
+        unkeyedListNodeParser = new UnkeyedListNodeDomParser(unkeyedListEntryNodeParser);
+        choiceNodeParser = new ChoiceNodeDomParser(dispatcher);
+        augmentationNodeParser = new AugmentationNodeDomParser(dispatcher);
+    }
 
+    @Deprecated
     private DomToNormalizedNodeParserFactory(final XmlCodecProvider codecProvider) {
         leafNodeParser = new LeafNodeDomParser(codecProvider);
         leafSetEntryNodeParser = new LeafSetEntryNodeDomParser(codecProvider);
         leafSetNodeParser = new LeafSetNodeDomParser(leafSetEntryNodeParser);
+        anyXmlNodeParser = new AnyXmlDomParser();
 
         final NodeParserDispatcher<Element> dispatcher = new NodeParserDispatcher.BaseNodeParserDispatcher<Element>(this) {
 
@@ -50,10 +81,18 @@ public final class DomToNormalizedNodeParserFactory implements ToNormalizedNodeP
         containerNodeParser = new ContainerNodeDomParser(dispatcher);
         mapEntryNodeParser = new MapEntryNodeDomParser(dispatcher);
         mapNodeParser = new MapNodeDomParser(mapEntryNodeParser);
+        orderedListNodeParser = new OrderedListNodeDomParser(mapEntryNodeParser);
+        unkeyedListEntryNodeParser = new UnkeyedListEntryNodeDomParser(dispatcher);
+        unkeyedListNodeParser = new UnkeyedListNodeDomParser(unkeyedListEntryNodeParser);
         choiceNodeParser = new ChoiceNodeDomParser(dispatcher);
         augmentationNodeParser = new AugmentationNodeDomParser(dispatcher);
     }
 
+    public static DomToNormalizedNodeParserFactory getInstance(final XmlCodecProvider codecProvider, final SchemaContext schema) {
+        return new DomToNormalizedNodeParserFactory(codecProvider, schema);
+    }
+
+    @Deprecated
     public static DomToNormalizedNodeParserFactory getInstance(final XmlCodecProvider codecProvider) {
         return new DomToNormalizedNodeParserFactory(codecProvider);
     }
@@ -64,7 +103,7 @@ public final class DomToNormalizedNodeParserFactory implements ToNormalizedNodeP
     }
 
     @Override
-    public ToNormalizedNodeParser<Element, ChoiceNode, org.opendaylight.yangtools.yang.model.api.ChoiceNode> getChoiceNodeParser() {
+    public ToNormalizedNodeParser<Element, ChoiceNode, ChoiceSchemaNode> getChoiceNodeParser() {
         return choiceNodeParser;
     }
 
@@ -98,8 +137,23 @@ public final class DomToNormalizedNodeParserFactory implements ToNormalizedNodeP
         return mapNodeParser;
     }
 
+    @Override
+    public ToNormalizedNodeParser<Element, UnkeyedListNode, ListSchemaNode> getUnkeyedListNodeParser() {
+        return unkeyedListNodeParser;
+    }
+
+    @Override
+    public ToNormalizedNodeParser<Element, UnkeyedListEntryNode, ListSchemaNode> getUnkeyedListEntryNodeParser() {
+        return unkeyedListEntryNodeParser;
+    }
+
+    @Override
+    public ToNormalizedNodeParser<Element, OrderedMapNode, ListSchemaNode> getOrderedListNodeParser() {
+        return orderedListNodeParser;
+    }
+
     @Override
     public ToNormalizedNodeParser<Element, AnyXmlNode, AnyXmlSchemaNode> getAnyXmlNodeParser() {
-        throw new UnsupportedOperationException();
+        return anyXmlNodeParser;
     }
 }
index 6c5d064268b09270ed80ef40522d932af19433c1..2e8ab87bd749d0134ee6ad68f9cf058d2e263bb7 100644 (file)
@@ -14,6 +14,7 @@ import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlCodecProvider;
 import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.LeafNodeBaseParser;
 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils;
 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.w3c.dom.Element;
 
 import com.google.common.base.Preconditions;
@@ -21,14 +22,21 @@ import com.google.common.base.Preconditions;
 final class LeafNodeDomParser extends LeafNodeBaseParser<Element> {
 
     private final XmlCodecProvider codecProvider;
+    private final SchemaContext ctx;
 
-    LeafNodeDomParser(XmlCodecProvider codecProvider) {
+    LeafNodeDomParser(XmlCodecProvider codecProvider, final SchemaContext schema) {
+        this.ctx = schema;
         this.codecProvider = Preconditions.checkNotNull(codecProvider);
     }
 
+    @Deprecated
+    LeafNodeDomParser(XmlCodecProvider codecProvider) {
+        this(codecProvider, null);
+    }
+
     @Override
     protected Object parseLeaf(Element xmlElement, LeafSchemaNode schema) {
-        return DomUtils.parseXmlValue(xmlElement, codecProvider, schema.getType());
+        return ctx == null ? DomUtils.parseXmlValue(xmlElement, codecProvider, schema.getType()) : DomUtils.parseXmlValue(xmlElement, codecProvider, schema, schema.getType(), ctx);
     }
 
     @Override
index 2b224a0e718b5064c6c2c32d259ebf29e3abffbc..0458cd5d106644cac40ed247956a640385fe9d8f 100644 (file)
@@ -14,6 +14,7 @@ import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlCodecProvider;
 import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.LeafSetEntryNodeBaseParser;
 import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils;
 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.w3c.dom.Element;
 
 import com.google.common.base.Preconditions;
@@ -21,14 +22,21 @@ import com.google.common.base.Preconditions;
 final class LeafSetEntryNodeDomParser extends LeafSetEntryNodeBaseParser<Element> {
 
     private final XmlCodecProvider codecProvider;
+    private final SchemaContext ctx;
 
-    LeafSetEntryNodeDomParser(XmlCodecProvider codecProvider) {
+    LeafSetEntryNodeDomParser(XmlCodecProvider codecProvider, final SchemaContext schema) {
+        ctx = schema;
         this.codecProvider = Preconditions.checkNotNull(codecProvider);
     }
 
+    @Deprecated
+    public LeafSetEntryNodeDomParser(final XmlCodecProvider codecProvider) {
+        this(codecProvider, null);
+    }
+
     @Override
     protected Object parseLeafListEntry(Element xmlElement, LeafListSchemaNode schema) {
-        return DomUtils.parseXmlValue(xmlElement, codecProvider, schema.getType());
+        return ctx == null ? DomUtils.parseXmlValue(xmlElement, codecProvider, schema.getType()) : DomUtils.parseXmlValue(xmlElement, codecProvider, schema, schema.getType(), ctx);
     }
 
     @Override
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/parser/ListEntryNodeDomParser.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/parser/ListEntryNodeDomParser.java
new file mode 100644 (file)
index 0000000..92496d7
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.LinkedListMultimap;
+import java.util.Map;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.ListEntryNodeBaseParser;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.NodeParserDispatcher;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils;
+import org.w3c.dom.Element;
+
+abstract class ListEntryNodeDomParser<N extends DataContainerNode<?>> extends ListEntryNodeBaseParser<Element, N> {
+
+    private final NodeParserDispatcher<Element> dispatcher;
+
+    ListEntryNodeDomParser(final NodeParserDispatcher<Element> dispatcher) {
+        this.dispatcher = Preconditions.checkNotNull(dispatcher);
+    }
+
+    @Override
+    protected LinkedListMultimap<QName, Element> mapChildElements(Iterable<Element> elements) {
+        return DomUtils.mapChildElementsForSingletonNode(elements.iterator().next());
+    }
+
+    @Override
+    protected NodeParserDispatcher<Element> getDispatcher() {
+        return dispatcher;
+    }
+
+    @Override
+    protected Map<QName, String> getAttributes(Element element) {
+        return DomUtils.toAttributes(element.getAttributes());
+    }
+}
index 65dde5cf5ba1a3a6801f04aacf82ae8f1de07a62..4d4d35aa7debb12ab7dc1fac204ba9c39a45238c 100644 (file)
@@ -7,37 +7,23 @@
  */
 package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser;
 
-import java.util.Map;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.MapEntryNodeBaseParser;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.NodeParserDispatcher;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.DomUtils;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 import org.w3c.dom.Element;
 
-import com.google.common.base.Preconditions;
-import com.google.common.collect.LinkedListMultimap;
-
-final class MapEntryNodeDomParser extends MapEntryNodeBaseParser<Element> {
-
-    private final NodeParserDispatcher<Element> dispatcher;
+final class MapEntryNodeDomParser extends ListEntryNodeDomParser<MapEntryNode> {
 
     MapEntryNodeDomParser(final NodeParserDispatcher<Element> dispatcher) {
-        this.dispatcher = Preconditions.checkNotNull(dispatcher);
-    }
-
-    @Override
-    protected LinkedListMultimap<QName, Element> mapChildElements(Iterable<Element> elements) {
-        return DomUtils.mapChildElementsForSingletonNode(elements.iterator().next());
-    }
-
-    @Override
-    protected NodeParserDispatcher<Element> getDispatcher() {
-        return dispatcher;
+        super(dispatcher);
     }
 
     @Override
-    protected Map<QName, String> getAttributes(Element element) {
-        return DomUtils.toAttributes(element.getAttributes());
+    protected final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> getBuilder(
+            ListSchemaNode schema) {
+        return Builders.mapEntryBuilder(schema);
     }
 }
index 0dd00aabb9b8ec267a4519324feedbddac071863..748564fdd1c6a3493112b3390259622caf6b3390 100644 (file)
@@ -22,7 +22,7 @@ final class MapNodeDomParser extends MapNodeBaseParser<Element> {
     }
 
     @Override
-    protected ToNormalizedNodeParser<Element, MapEntryNode, ListSchemaNode> getMapEntryNodeParser() {
+    protected ToNormalizedNodeParser<Element, MapEntryNode, ListSchemaNode> getListEntryNodeParser() {
         return mapEntryParser;
     }
 }
@@ -5,25 +5,24 @@
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
-package org.opendaylight.yangtools.yang.data.composite.node.schema.cnsn.parser;
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser;
 
-import org.opendaylight.yangtools.yang.data.api.Node;
 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
 import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParser;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.MapNodeBaseParser;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.OrderedListNodeBaseParser;
 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.w3c.dom.Element;
 
-public final class MapNodeCnSnParser extends MapNodeBaseParser<Node<?>> {
+final class OrderedListNodeDomParser extends OrderedListNodeBaseParser<Element> {
 
-    private final MapEntryNodeCnSnParser mapEntryNodeCnSnParser;
+    private final MapEntryNodeDomParser mapEntryNodeParser;
 
-    public MapNodeCnSnParser(MapEntryNodeCnSnParser mapEntryNodeCnSnParser) {
-        this.mapEntryNodeCnSnParser = mapEntryNodeCnSnParser;
+    OrderedListNodeDomParser(MapEntryNodeDomParser mapEntryNodeParser) {
+        this.mapEntryNodeParser = mapEntryNodeParser;
     }
 
     @Override
-    protected ToNormalizedNodeParser<Node<?>, MapEntryNode, ListSchemaNode> getMapEntryNodeParser() {
-        return mapEntryNodeCnSnParser;
+    protected ToNormalizedNodeParser<Element, MapEntryNode, ListSchemaNode> getListEntryNodeParser() {
+        return mapEntryNodeParser;
     }
-
 }
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/parser/UnkeyedListEntryNodeDomParser.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/parser/UnkeyedListEntryNodeDomParser.java
new file mode 100644 (file)
index 0000000..781f06c
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser;
+
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.NodeParserDispatcher;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.w3c.dom.Element;
+
+final class UnkeyedListEntryNodeDomParser extends ListEntryNodeDomParser<UnkeyedListEntryNode> {
+
+    UnkeyedListEntryNodeDomParser(final NodeParserDispatcher<Element> dispatcher) {
+        super(dispatcher);
+    }
+
+    @Override
+    protected final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, UnkeyedListEntryNode> getBuilder(
+            ListSchemaNode schema) {
+        return Builders.unkeyedListEntryBuilder().withNodeIdentifier(new NodeIdentifier(schema.getQName()));
+    }
+
+}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/parser/UnkeyedListNodeDomParser.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/parser/UnkeyedListNodeDomParser.java
new file mode 100644 (file)
index 0000000..15eed32
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser;
+
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.ToNormalizedNodeParser;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.parser.UnkeyedListNodeBaseParser;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.w3c.dom.Element;
+
+final class UnkeyedListNodeDomParser extends UnkeyedListNodeBaseParser<Element> {
+
+    private final UnkeyedListEntryNodeDomParser unkeyedListEntryNodeParser;
+
+    UnkeyedListNodeDomParser(UnkeyedListEntryNodeDomParser unkeyedListEntryNodeParser) {
+        this.unkeyedListEntryNodeParser = unkeyedListEntryNodeParser;
+    }
+
+    @Override
+    protected ToNormalizedNodeParser<Element, UnkeyedListEntryNode, ListSchemaNode> getListEntryNodeParser() {
+        return unkeyedListEntryNodeParser;
+    }
+}
index b9d8ef2a757a3dec9cd0f3faf00d2194fe02a24a..3fe79dc22c2e6d7f47f84cb75ade4f72461bef7b 100644 (file)
@@ -16,12 +16,14 @@ import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlCodecProvider;
 import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializer;
 import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializerFactory;
 import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
@@ -29,6 +31,8 @@ import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
+// TODO Is this used anywhere ? it is replaced by the NormalizedNode stream writer, COuld this be removed ?
+
 public final class DomFromNormalizedNodeSerializerFactory implements FromNormalizedNodeSerializerFactory<Element> {
     private final ContainerNodeDomSerializer containerSerializer;
     private final ChoiceNodeDomSerializer choiceSerializer;
@@ -36,8 +40,10 @@ public final class DomFromNormalizedNodeSerializerFactory implements FromNormali
     private final LeafNodeDomSerializer leafNodeSerializer;
     private final LeafSetNodeDomSerializer leafSetSerializer;
     private final MapNodeDomSerializer mapNodeSerializer;
+    private final UnkeyedListNodeDomSerializer unkeyedListNodeSerializer;
     private final LeafSetEntryNodeDomSerializer leafSetEntryNodeSerializer;
-       private final MapEntryNodeDomSerializer mapEntryNodeSerializer;
+    private final MapEntryNodeDomSerializer mapEntryNodeSerializer;
+    private final UnkeyedListEntryNodeDomSerializer unkeyedListEntryNodeSerializer;
 
        private DomFromNormalizedNodeSerializerFactory(final Document doc, final XmlCodecProvider codecProvider) {
                final NodeSerializerDispatcher.BaseNodeSerializerDispatcher<Element> dispatcher = new NodeSerializerDispatcher.BaseNodeSerializerDispatcher<Element>(this) {
@@ -54,6 +60,9 @@ public final class DomFromNormalizedNodeSerializerFactory implements FromNormali
 
         mapEntryNodeSerializer = new MapEntryNodeDomSerializer(doc, dispatcher);
         mapNodeSerializer = new MapNodeDomSerializer(mapEntryNodeSerializer);
+
+        unkeyedListEntryNodeSerializer = new UnkeyedListEntryNodeDomSerializer(doc, dispatcher);
+        unkeyedListNodeSerializer = new UnkeyedListNodeDomSerializer(unkeyedListEntryNodeSerializer);
        }
 
        public static DomFromNormalizedNodeSerializerFactory getInstance(final Document doc, final XmlCodecProvider codecProvider) {
@@ -66,7 +75,7 @@ public final class DomFromNormalizedNodeSerializerFactory implements FromNormali
        }
 
        @Override
-       public FromNormalizedNodeSerializer<Element, ChoiceNode, org.opendaylight.yangtools.yang.model.api.ChoiceNode> getChoiceNodeSerializer() {
+       public FromNormalizedNodeSerializer<Element, ChoiceNode, ChoiceSchemaNode> getChoiceNodeSerializer() {
                return choiceSerializer;
        }
 
@@ -100,6 +109,11 @@ public final class DomFromNormalizedNodeSerializerFactory implements FromNormali
                return mapNodeSerializer;
        }
 
+       @Override
+       public FromNormalizedNodeSerializer<Element, UnkeyedListNode, ListSchemaNode> getUnkeyedListNodeSerializer() {
+           return unkeyedListNodeSerializer;
+       }
+
         @Override
         public FromNormalizedNodeSerializer<Element, AnyXmlNode, AnyXmlSchemaNode> getAnyXmlNodeSerializer() {
             throw new UnsupportedOperationException();
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/serializer/ListEntryNodeDomSerializer.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/serializer/ListEntryNodeDomSerializer.java
new file mode 100644 (file)
index 0000000..f045f72
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.serializer;
+
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
+import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.ListEntryNodeBaseSerializer;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ *
+ * Common class for list entry node serialization (MapEntry, UnkeyedListEntry nodes)
+ *
+ * @param <N>
+ *            concrete entry node type
+ */
+abstract class ListEntryNodeDomSerializer<N extends DataContainerNode<?>> extends
+        ListEntryNodeBaseSerializer<Element, N> {
+    private final NodeSerializerDispatcher<Element> dispatcher;
+    private final Document doc;
+
+    ListEntryNodeDomSerializer(final Document doc, final NodeSerializerDispatcher<Element> dispatcher) {
+        this.doc = Preconditions.checkNotNull(doc);
+        this.dispatcher = Preconditions.checkNotNull(dispatcher);
+    }
+
+    @Override
+    public Iterable<Element> serialize(ListSchemaNode schema, N node) {
+        Element itemEl = XmlDocumentUtils.createElementFor(doc, node);
+
+        for (Element element : super.serialize(schema, node)) {
+            itemEl.appendChild(element);
+        }
+
+        return Collections.singletonList(itemEl);
+    }
+
+    @Override
+    protected NodeSerializerDispatcher<Element> getNodeDispatcher() {
+        return dispatcher;
+    }
+}
index dbe8a90fc67f3b0caffa782160a57d950e68b5ba..6178bbab6043586066d39ab4490fc7a382be1ec5 100644 (file)
@@ -7,40 +7,13 @@
  */
 package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.serializer;
 
-import java.util.Collections;
-
 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
-import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.MapEntryNodeBaseSerializer;
 import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-import com.google.common.base.Preconditions;
-
-final class MapEntryNodeDomSerializer extends MapEntryNodeBaseSerializer<Element> {
-    private final NodeSerializerDispatcher<Element> dispatcher;
-    private final Document doc;
-
+final class MapEntryNodeDomSerializer extends ListEntryNodeDomSerializer<MapEntryNode> {
     MapEntryNodeDomSerializer(final Document doc, final NodeSerializerDispatcher<Element> dispatcher) {
-        this.doc = Preconditions.checkNotNull(doc);
-        this.dispatcher = Preconditions.checkNotNull(dispatcher);
-    }
-
-    @Override
-    public Iterable<Element> serialize(ListSchemaNode schema, MapEntryNode node) {
-        Element itemEl = XmlDocumentUtils.createElementFor(doc, node);
-
-        for (Element element : super.serialize(schema, node)) {
-            itemEl.appendChild(element);
-        }
-
-        return Collections.singletonList(itemEl);
-    }
-
-    @Override
-    protected NodeSerializerDispatcher<Element> getNodeDispatcher() {
-        return dispatcher;
+        super(doc, dispatcher);
     }
 }
index 5404f193bfb69f0ec2283dbda2fee0dfe1cc5fa3..4dccd49305402750bae64a163e5697805abdd1bf 100644 (file)
@@ -8,12 +8,13 @@
 package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.serializer;
 
 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
 import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializer;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.MapNodeBaseSerializer;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.ListNodeBaseSerializer;
 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 import org.w3c.dom.Element;
 
-final class MapNodeDomSerializer extends MapNodeBaseSerializer<Element> {
+final class MapNodeDomSerializer extends ListNodeBaseSerializer<Element, MapNode, MapEntryNode> {
 
     private final FromNormalizedNodeSerializer<Element, MapEntryNode, ListSchemaNode> mapEntrySerializer;
 
@@ -22,7 +23,7 @@ final class MapNodeDomSerializer extends MapNodeBaseSerializer<Element> {
     }
 
     @Override
-    protected FromNormalizedNodeSerializer<Element, MapEntryNode, ListSchemaNode> getMapEntryNodeDomSerializer() {
+    protected FromNormalizedNodeSerializer<Element, MapEntryNode, ListSchemaNode> getListEntryNodeSerializer() {
         return mapEntrySerializer;
     }
 }
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/serializer/UnkeyedListEntryNodeDomSerializer.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/serializer/UnkeyedListEntryNodeDomSerializer.java
new file mode 100644 (file)
index 0000000..1cef516
--- /dev/null
@@ -0,0 +1,21 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.serializer;
+
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.NodeSerializerDispatcher;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+final class UnkeyedListEntryNodeDomSerializer extends ListEntryNodeDomSerializer<UnkeyedListEntryNode> {
+
+    UnkeyedListEntryNodeDomSerializer(final Document doc, final NodeSerializerDispatcher<Element> dispatcher) {
+        super(doc, dispatcher);
+    }
+
+}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/serializer/UnkeyedListNodeDomSerializer.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/transform/dom/serializer/UnkeyedListNodeDomSerializer.java
new file mode 100644 (file)
index 0000000..7e64d21
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.serializer;
+
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.FromNormalizedNodeSerializer;
+import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.serializer.ListNodeBaseSerializer;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.w3c.dom.Element;
+
+final class UnkeyedListNodeDomSerializer extends ListNodeBaseSerializer<Element, UnkeyedListNode, UnkeyedListEntryNode> {
+
+    private final FromNormalizedNodeSerializer<Element, UnkeyedListEntryNode, ListSchemaNode> unkeyedListEntrySerializer;
+
+    UnkeyedListNodeDomSerializer(UnkeyedListEntryNodeDomSerializer unkeyedListEntrySerializer) {
+        this.unkeyedListEntrySerializer = unkeyedListEntrySerializer;
+    }
+
+    @Override
+    protected FromNormalizedNodeSerializer<Element, UnkeyedListEntryNode, ListSchemaNode> getListEntryNodeSerializer() {
+        return unkeyedListEntrySerializer;
+    }
+}
index bfa3f28e6e95ec7ff34184778d74924adf09110d..e239c38bf03d2d8de528779a8cf42577fdee3214 100644 (file)
@@ -9,10 +9,14 @@ package org.opendaylight.yangtools.yang.data.impl.schema.tree;
 
 import static com.google.common.base.Preconditions.checkArgument;
 
+import com.google.common.base.Function;
+import com.google.common.base.Optional;
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
 import java.util.HashSet;
 import java.util.Set;
 import java.util.concurrent.ExecutionException;
-
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
@@ -25,19 +29,13 @@ import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableAu
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapEntryNodeBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableUnkeyedListEntryNodeBuilder;
-import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.AugmentationSchemaProxy;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-
-import com.google.common.base.Function;
-import com.google.common.base.Optional;
-import com.google.common.cache.CacheBuilder;
-import com.google.common.cache.CacheLoader;
-import com.google.common.cache.LoadingCache;
+import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
 
 /**
  * Base strategy for applying changes to a ContainerNode, irrespective of its
@@ -106,13 +104,12 @@ abstract class DataNodeContainerModificationStrategy<T extends DataNodeContainer
             return ImmutableAugmentationNodeBuilder.create((AugmentationNode) original);
         }
 
-
         private static AugmentationSchema createAugmentProxy(final AugmentationSchema schema, final DataNodeContainer resolved) {
             Set<DataSchemaNode> realChildSchemas = new HashSet<>();
             for(DataSchemaNode augChild : schema.getChildNodes()) {
                 realChildSchemas.add(resolved.getDataChildByName(augChild.getQName()));
             }
-            return new AugmentationSchemaProxy(schema, realChildSchemas);
+            return new EffectiveAugmentationSchema(schema, realChildSchemas);
         }
     }
 
index 0ed17c685a8aef53900a0b6a9fb71448f967a102..0f680fddadf30a6cf11410bf7ef2cb31e069c14a 100644 (file)
@@ -19,7 +19,6 @@ import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTree;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidate;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.slf4j.Logger;
@@ -54,7 +53,6 @@ final class InMemoryDataTree implements DataTree {
     public synchronized void setSchemaContext(final SchemaContext newSchemaContext) {
         Preconditions.checkNotNull(newSchemaContext);
 
-        LOG.info("Attempting to install schema contexts");
         LOG.debug("Following schema contexts will be attempted {}", newSchemaContext);
 
         final SchemaAwareApplyOperation operation = SchemaAwareApplyOperation.from(newSchemaContext);
@@ -86,7 +84,7 @@ final class InMemoryDataTree implements DataTree {
         final InMemoryDataTreeModification m = (InMemoryDataTreeModification)modification;
         final ModifiedNode root = m.getRootModification();
 
-        if (root.getType() == ModificationType.UNMODIFIED) {
+        if (root.getOperation() == LogicalOperation.NONE) {
             return new NoopDataTreeCandidate(PUBLIC_ROOT_PATH, root);
         }
 
index f6c5081bb67e2a0f0044122dfd665a8b6989e5f6..f6bb6ba2aac4e8da8c0ba922bd09d0f5621b43cb 100644 (file)
@@ -15,6 +15,10 @@ import java.util.Collection;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
+import org.opendaylight.yangtools.yang.data.api.schema.OrderedLeafSetNode;
+import org.opendaylight.yangtools.yang.data.api.schema.OrderedMapNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeCandidateNode;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
@@ -69,7 +73,39 @@ final class InMemoryDataTreeCandidate extends AbstractDataTreeCandidate {
 
         @Override
         public ModificationType getModificationType() {
-            return mod.getType();
+            switch (mod.getOperation()) {
+            case DELETE:
+                return ModificationType.DELETE;
+            case MERGE:
+                // Merge into non-existing data is a write
+                if (oldMeta == null) {
+                    return ModificationType.WRITE;
+                }
+
+                // Data-based checks to narrow down types
+                final NormalizedNode<?, ?> data = newMeta.getData();
+
+                // leaf or anyxml are always written
+                if (!(data instanceof NormalizedNodeContainer)) {
+                    return ModificationType.WRITE;
+                }
+
+                // Unkeyed collections are always written
+                if (data instanceof UnkeyedListNode || data instanceof OrderedMapNode || data instanceof OrderedLeafSetNode) {
+                    return ModificationType.WRITE;
+                }
+
+                // Everything else is subtree modified
+                return ModificationType.SUBTREE_MODIFIED;
+            case TOUCH:
+                return ModificationType.SUBTREE_MODIFIED;
+            case NONE:
+                return ModificationType.UNMODIFIED;
+            case WRITE:
+                return ModificationType.WRITE;
+            }
+
+            throw new IllegalStateException("Unhandled internal operation " + mod.getOperation());
         }
 
         private Optional<NormalizedNode<?, ?>> optionalData(final TreeNode meta) {
index 0b0c8516d84969e262b2b9878574b14bbc073620..eb6b9726bece91e6d9afa97af1d3037b21187117 100644 (file)
@@ -16,7 +16,6 @@ import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgum
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataTreeModification;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.StoreTreeNodes;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
@@ -118,7 +117,7 @@ final class InMemoryDataTreeModification implements DataTreeModification {
 
     private ModificationApplyOperation resolveModificationStrategy(final YangInstanceIdentifier path) {
         LOG.trace("Resolving modification apply strategy for {}", path);
-        if (rootNode.getType() == ModificationType.UNMODIFIED) {
+        if (rootNode.getOperation() == LogicalOperation.NONE) {
             strategyTree.upgradeIfPossible();
         }
 
@@ -164,7 +163,7 @@ final class InMemoryDataTreeModification implements DataTreeModification {
     public DataTreeModification newModification() {
         Preconditions.checkState(sealed == 1, "Attempted to chain on an unsealed modification");
 
-        if (rootNode.getType() == ModificationType.UNMODIFIED) {
+        if (rootNode.getOperation() == LogicalOperation.NONE) {
             // Simple fast case: just use the underlying modification
             return snapshot.newModification();
         }
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/tree/LogicalOperation.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/schema/tree/LogicalOperation.java
new file mode 100644 (file)
index 0000000..bdaa954
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.impl.schema.tree;
+
+import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
+
+/**
+ * Enumeration of all possible node modification states. These are used in
+ * data tree modification context to quickly assess what sort of modification
+ * the node is undergoing. This is a superset of {@link ModificationType}:
+ * where this type represents a logical operation, {@link ModificationType}
+ * represents a physical operation.
+ */
+enum LogicalOperation {
+    /**
+     * Node is currently unmodified.
+     */
+    NONE,
+
+    /**
+     * A child node, either direct or indirect, has been modified. This means
+     * that the data representation of this node has potentially changed.
+     */
+    TOUCH,
+
+    /**
+     * This node has been placed into the tree, potentially completely replacing
+     * pre-existing contents.
+     */
+    WRITE,
+
+    /**
+     * This node has been deleted along with any of its child nodes.
+     */
+    DELETE,
+
+    /**
+     * Node has been written into the tree, but instead of replacing pre-existing
+     * contents, it has been merged. This means that any incoming nodes which
+     * were present in the tree have been replaced, but their child nodes have
+     * been retained.
+     */
+    MERGE,
+}
index 448828bd9a0544b7f4e9d152d1f22c6e32aa5087..053e21ff2642b5fc5dfeca79fbbfaf514e8a4d44 100644 (file)
@@ -38,24 +38,24 @@ final class ModifiedNode extends NodeModification implements StoreTreeNode<Modif
         @Override
         public boolean apply(final @Nonnull ModifiedNode input) {
             Preconditions.checkNotNull(input);
-            switch (input.getType()) {
+            switch (input.getOperation()) {
             case DELETE:
             case MERGE:
             case WRITE:
                 return true;
-            case SUBTREE_MODIFIED:
-            case UNMODIFIED:
+            case TOUCH:
+            case NONE:
                 return false;
             }
 
-            throw new IllegalArgumentException(String.format("Unhandled modification type %s", input.getType()));
+            throw new IllegalArgumentException(String.format("Unhandled modification type %s", input.getOperation()));
         }
     };
 
     private final Map<PathArgument, ModifiedNode> children;
     private final Optional<TreeNode> original;
     private final PathArgument identifier;
-    private ModificationType modificationType = ModificationType.UNMODIFIED;
+    private LogicalOperation operation = LogicalOperation.NONE;
     private Optional<TreeNode> snapshotCache;
     private NormalizedNode<?, ?> value;
 
@@ -84,24 +84,15 @@ final class ModifiedNode extends NodeModification implements StoreTreeNode<Modif
         return identifier;
     }
 
-    /**
-     *
-     * Returns original store metadata
-     * @return original store metadata
-     */
     @Override
     Optional<TreeNode> getOriginal() {
         return original;
     }
 
-    /**
-     * Returns modification type
-     *
-     * @return modification type
-     */
+
     @Override
-    ModificationType getType() {
-        return modificationType;
+    LogicalOperation getOperation() {
+        return operation;
     }
 
     /**
@@ -131,8 +122,8 @@ final class ModifiedNode extends NodeModification implements StoreTreeNode<Modif
      */
     ModifiedNode modifyChild(final PathArgument child, final boolean isOrdered) {
         clearSnapshot();
-        if (modificationType == ModificationType.UNMODIFIED) {
-            updateModificationType(ModificationType.SUBTREE_MODIFIED);
+        if (operation == LogicalOperation.NONE) {
+            updateModificationType(LogicalOperation.TOUCH);
         }
         final ModifiedNode potential = children.get(child);
         if (potential != null) {
@@ -166,16 +157,16 @@ final class ModifiedNode extends NodeModification implements StoreTreeNode<Modif
      * Records a delete for associated node.
      */
     void delete() {
-        final ModificationType newType;
+        final LogicalOperation newType;
 
-        switch (modificationType) {
+        switch (operation) {
         case DELETE:
-        case UNMODIFIED:
+        case NONE:
             // We need to record this delete.
-            newType = ModificationType.DELETE;
+            newType = LogicalOperation.DELETE;
             break;
         case MERGE:
-        case SUBTREE_MODIFIED:
+        case TOUCH:
         case WRITE:
             /*
              * We are canceling a previous modification. This is a bit tricky,
@@ -185,10 +176,10 @@ final class ModifiedNode extends NodeModification implements StoreTreeNode<Modif
              * As documented in BUG-2470, a delete of data introduced in this
              * transaction needs to be turned into a no-op.
              */
-            newType = original.isPresent() ? ModificationType.DELETE : ModificationType.UNMODIFIED;
+            newType = original.isPresent() ? LogicalOperation.DELETE : LogicalOperation.NONE;
             break;
         default:
-            throw new IllegalStateException("Unhandled deletion of node with " + modificationType);
+            throw new IllegalStateException("Unhandled deletion of node with " + operation);
         }
 
         clearSnapshot();
@@ -204,14 +195,14 @@ final class ModifiedNode extends NodeModification implements StoreTreeNode<Modif
      */
     void write(final NormalizedNode<?, ?> value) {
         clearSnapshot();
-        updateModificationType(ModificationType.WRITE);
+        updateModificationType(LogicalOperation.WRITE);
         children.clear();
         this.value = value;
     }
 
     void merge(final NormalizedNode<?, ?> value) {
         clearSnapshot();
-        updateModificationType(ModificationType.MERGE);
+        updateModificationType(LogicalOperation.MERGE);
 
         /*
          * Blind overwrite of any previous data is okay, no matter whether the node
@@ -245,14 +236,14 @@ final class ModifiedNode extends NodeModification implements StoreTreeNode<Modif
             final ModifiedNode child = it.next();
             child.seal();
 
-            if (child.modificationType == ModificationType.UNMODIFIED) {
+            if (child.operation == LogicalOperation.NONE) {
                 it.remove();
             }
         }
 
-        // A SUBTREE_MODIFIED node without any children is a no-op
-        if (modificationType == ModificationType.SUBTREE_MODIFIED && children.isEmpty()) {
-            updateModificationType(ModificationType.UNMODIFIED);
+        // A TOUCH node without any children is a no-op
+        if (operation == LogicalOperation.TOUCH && children.isEmpty()) {
+            updateModificationType(LogicalOperation.NONE);
         }
     }
 
@@ -269,15 +260,15 @@ final class ModifiedNode extends NodeModification implements StoreTreeNode<Modif
         return snapshot;
     }
 
-    private void updateModificationType(final ModificationType type) {
-        modificationType = type;
+    private void updateModificationType(final LogicalOperation type) {
+        operation = type;
         clearSnapshot();
     }
 
     @Override
     public String toString() {
         return "NodeModification [identifier=" + identifier + ", modificationType="
-                + modificationType + ", childModification=" + children + "]";
+                + operation + ", childModification=" + children + "]";
     }
 
     /**
index f3282faa7bd7e20985a0c711e69be709e5dee6f2..225a931ec0a5eb65286cfe288936696bb28c27d1 100644 (file)
@@ -7,12 +7,10 @@
  */
 package org.opendaylight.yangtools.yang.data.impl.schema.tree;
 
-
 import com.google.common.base.Optional;
 import java.util.Collection;
 import org.opendaylight.yangtools.concepts.Identifiable;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
 
 /**
@@ -24,9 +22,9 @@ abstract class NodeModification implements Identifiable<PathArgument> {
     /**
      * Get the type of modification.
      *
-     * @return Modification type.
+     * @return Operation type.
      */
-    abstract ModificationType getType();
+    abstract LogicalOperation getOperation();
 
     /**
      * Get the original tree node to which the modification is to be applied.
index 7a91e232d85dce3f3286bb6e4b1c4f9826895495..979e79c1c71382ef74ba7cb1f4a375e072c76cc8 100644 (file)
@@ -57,7 +57,7 @@ final class NoopDataTreeCandidate extends AbstractDataTreeCandidate {
 
     protected NoopDataTreeCandidate(final YangInstanceIdentifier rootPath, final ModifiedNode modificationRoot) {
         super(rootPath);
-        Preconditions.checkArgument(modificationRoot.getType() == ModificationType.UNMODIFIED);
+        Preconditions.checkArgument(modificationRoot.getOperation() == LogicalOperation.NONE);
     }
 
     @Override
index 47e2e85e3e2e66817ecedd17f0014ade2050ad00..5b924d78d5075d6a38013846ee078067ec8f4c8f 100644 (file)
@@ -13,6 +13,7 @@ import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Iterables;
 import java.util.Map;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
@@ -33,7 +34,7 @@ import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMa
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableOrderedLeafSetNodeBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableOrderedMapNodeBuilder;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
@@ -206,8 +207,8 @@ abstract class NormalizedNodeContainerModificationStrategy extends SchemaAwareAp
 
         private final Map<YangInstanceIdentifier.PathArgument, ModificationApplyOperation> childNodes;
 
-        public ChoiceModificationStrategy(final ChoiceNode schemaNode) {
-            super(org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode.class);
+        public ChoiceModificationStrategy(final ChoiceSchemaNode schemaNode) {
+            super(ChoiceNode.class);
             ImmutableMap.Builder<YangInstanceIdentifier.PathArgument, ModificationApplyOperation> child = ImmutableMap.builder();
 
             for (ChoiceCaseNode caze : schemaNode.getCases()) {
@@ -227,8 +228,8 @@ abstract class NormalizedNodeContainerModificationStrategy extends SchemaAwareAp
         @Override
         @SuppressWarnings("rawtypes")
         protected DataContainerNodeBuilder createBuilder(final NormalizedNode<?, ?> original) {
-            checkArgument(original instanceof org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode);
-            return ImmutableChoiceNodeBuilder.create((org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode) original);
+            checkArgument(original instanceof ChoiceNode);
+            return ImmutableChoiceNodeBuilder.create((ChoiceNode) original);
         }
     }
 
index e721221ee9249db083d16bb9c0fffdd4c1ede5a7..aaee9c30d8fb96c27c9ca216d87a09da2861fe16 100644 (file)
@@ -18,12 +18,11 @@ import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.ConflictingModificationAppliedException;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.DataValidationFailedException;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.IncorrectDataStructureException;
-import org.opendaylight.yangtools.yang.data.api.schema.tree.ModificationType;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.TreeNode;
 import org.opendaylight.yangtools.yang.data.api.schema.tree.spi.Version;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
@@ -41,8 +40,8 @@ abstract class SchemaAwareApplyOperation implements ModificationApplyOperation {
             return new DataNodeContainerModificationStrategy.ContainerModificationStrategy((ContainerSchemaNode) schemaNode);
         } else if (schemaNode instanceof ListSchemaNode) {
             return fromListSchemaNode((ListSchemaNode) schemaNode);
-        } else if (schemaNode instanceof ChoiceNode) {
-            return new NormalizedNodeContainerModificationStrategy.ChoiceModificationStrategy((ChoiceNode) schemaNode);
+        } else if (schemaNode instanceof ChoiceSchemaNode) {
+            return new NormalizedNodeContainerModificationStrategy.ChoiceModificationStrategy((ChoiceSchemaNode) schemaNode);
         } else if (schemaNode instanceof LeafListSchemaNode) {
             return fromLeafListSchemaNode((LeafListSchemaNode) schemaNode);
         } else if (schemaNode instanceof LeafSchemaNode) {
@@ -113,17 +112,17 @@ abstract class SchemaAwareApplyOperation implements ModificationApplyOperation {
 
     @Override
     public void verifyStructure(final ModifiedNode modification) throws IllegalArgumentException {
-        if (modification.getType() == ModificationType.WRITE) {
+        if (modification.getOperation() == LogicalOperation.WRITE) {
             verifyWrittenStructure(modification.getWrittenValue());
         }
     }
 
     @Override
     public final void checkApplicable(final YangInstanceIdentifier path,final NodeModification modification, final Optional<TreeNode> current) throws DataValidationFailedException {
-        switch (modification.getType()) {
+        switch (modification.getOperation()) {
         case DELETE:
             checkDeleteApplicable(modification, current);
-        case SUBTREE_MODIFIED:
+        case TOUCH:
             checkSubtreeModificationApplicable(path, modification, current);
             return;
         case WRITE:
@@ -132,10 +131,10 @@ abstract class SchemaAwareApplyOperation implements ModificationApplyOperation {
         case MERGE:
             checkMergeApplicable(path, modification, current);
             return;
-        case UNMODIFIED:
+        case NONE:
             return;
         default:
-            throw new UnsupportedOperationException("Suplied modification type "+ modification.getType()+ "is not supported.");
+            throw new UnsupportedOperationException("Suplied modification type "+ modification.getOperation()+ "is not supported.");
         }
 
     }
@@ -192,10 +191,10 @@ abstract class SchemaAwareApplyOperation implements ModificationApplyOperation {
     public final Optional<TreeNode> apply(final ModifiedNode modification,
             final Optional<TreeNode> currentMeta, final Version version) {
 
-        switch (modification.getType()) {
+        switch (modification.getOperation()) {
         case DELETE:
             return modification.setSnapshot(Optional.<TreeNode> absent());
-        case SUBTREE_MODIFIED:
+        case TOUCH:
             Preconditions.checkArgument(currentMeta.isPresent(), "Metadata not available for modification",
                     modification);
             return modification.setSnapshot(Optional.of(applySubtreeChange(modification, currentMeta.get(),
@@ -213,7 +212,7 @@ abstract class SchemaAwareApplyOperation implements ModificationApplyOperation {
             return modification.setSnapshot(Optional.of(result));
         case WRITE:
             return modification.setSnapshot(Optional.of(applyWrite(modification, currentMeta, version)));
-        case UNMODIFIED:
+        case NONE:
             return currentMeta;
         default:
             throw new IllegalArgumentException("Provided modification type is not supported.");
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/util/AbstractCompositeNodeBuilder.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/util/AbstractCompositeNodeBuilder.java
deleted file mode 100644 (file)
index e22e200..0000000
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.util;
-
-import static com.google.common.base.Preconditions.checkNotNull;
-
-import com.google.common.collect.Iterables;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeContainerBuilder;
-
-/**
- * @deprecated Use one of the {@link NormalizedNodeContainerBuilder} implementations.
- */
-@Deprecated
-public abstract class AbstractCompositeNodeBuilder<P extends CompositeNode> extends AbstractNodeBuilder<P, CompositeNodeBuilder<P>> implements CompositeNodeBuilder<P> {
-
-    final List<Node<?>> childNodes;
-
-    public AbstractCompositeNodeBuilder() {
-        super();
-        childNodes = new ArrayList<>();
-    }
-
-    public AbstractCompositeNodeBuilder(final QName nodeType, final Map<QName, String> attributes) {
-        super(nodeType, attributes);
-        childNodes = new ArrayList<>();
-    }
-
-    public AbstractCompositeNodeBuilder(final QName nodeType, final Iterable<? extends Node<?>> nodes) {
-        super(nodeType);
-        childNodes = new ArrayList<>();
-    }
-
-    @Override
-    public AbstractCompositeNodeBuilder<P> add(final Node<?> node) {
-        childNodes.add(checkNotNull(node, "Node should not be null"));
-        return this;
-    }
-
-    @Override
-    public AbstractCompositeNodeBuilder<P> addAll(final Iterable<? extends Node<?>> nodes) {
-        Iterables.addAll(childNodes, checkNotNull(nodes, "Node should not be null"));
-        return this;
-    }
-
-    @Override
-    public CompositeNodeBuilder<P> addLeaf(final String leafLocalName, final String leafValue) {
-        return addLeaf(QName.create(getQName(), leafLocalName), leafValue);
-    }
-
-    public List<Node<?>> getChildNodes() {
-        return childNodes;
-    }
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/util/AbstractNodeBuilder.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/util/AbstractNodeBuilder.java
deleted file mode 100644 (file)
index 76a4088..0000000
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.util;
-
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-public abstract class AbstractNodeBuilder<P extends Node<?>, T extends NodeBuilder<P, T>> implements NodeBuilder<P, T> {
-
-    private final Map<QName, String> attributes;
-    private QName qName;
-
-    public AbstractNodeBuilder() {
-        this.attributes = new ConcurrentHashMap<>();
-    }
-
-    public AbstractNodeBuilder(QName nodeType, Map<QName, String> attributes) {
-        super();
-        this.qName = nodeType;
-        this.attributes = new ConcurrentHashMap<>(attributes);
-    }
-
-    public AbstractNodeBuilder(QName nodeType) {
-        this.qName = nodeType;
-        this.attributes = new ConcurrentHashMap<>();
-    }
-
-    @SuppressWarnings("unchecked")
-    protected final T thisInstance() {
-        return (T) this;
-    }
-
-    @Override
-    public final T setQName(QName name) {
-        this.qName = name;
-        return thisInstance();
-    }
-
-    public QName getQName() {
-        return qName;
-    }
-
-    @Override
-    public final T setAttribute(QName attrName, String attrValue) {
-        attributes.put(attrName, attrValue);
-        return thisInstance();
-    }
-
-    public Map<QName, String> getAttributes() {
-        return attributes;
-    }
-    
-    @Override
-    public T setAttribute(String attrName, String attrValue) {
-        attributes.put(QName.create(qName, attrName), attrValue);
-        return thisInstance();
-    }
-
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/util/CompositeNodeBuilder.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/util/CompositeNodeBuilder.java
deleted file mode 100644 (file)
index 9a2ed54..0000000
+++ /dev/null
@@ -1,24 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.util;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-/*
- * @deprecated Use one of the NormalizedNode builders instead.
- */
-@Deprecated
-public interface CompositeNodeBuilder<P extends CompositeNode> extends NodeBuilder<P,CompositeNodeBuilder<P>> {
-
-    CompositeNodeBuilder<P> addLeaf(QName leafName,Object leafValue);
-    CompositeNodeBuilder<P> add(Node<?> node);
-    CompositeNodeBuilder<P> addAll(Iterable<? extends Node<?>> nodes);
-    CompositeNodeBuilder<P> addLeaf(String leafLocalName, String leafValue);
-}
diff --git a/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/util/NodeBuilder.java b/yang/yang-data-impl/src/main/java/org/opendaylight/yangtools/yang/data/impl/util/NodeBuilder.java
deleted file mode 100644 (file)
index 2eae21b..0000000
+++ /dev/null
@@ -1,29 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl.util;
-
-import org.opendaylight.yangtools.concepts.Builder;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-public interface NodeBuilder<P extends Node<?>, T extends NodeBuilder<P, T>> extends Builder<P> {
-
-    T setQName(QName name);
-
-    QName getQName();
-
-    T setAttribute(QName attrName, String attrValue);
-
-    T setAttribute(String attrName, String attrValue);
-
-    /**
-     * @deprecated use {@link #build()}.
-     */
-    @Deprecated
-    P toInstance();
-}
diff --git a/yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/codec/xml/test/RpcReplyToDomTest.java b/yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/codec/xml/test/RpcReplyToDomTest.java
deleted file mode 100644 (file)
index 32134dd..0000000
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.codec.xml.test;
-
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-
-import javax.xml.parsers.DocumentBuilder;
-import javax.xml.parsers.DocumentBuilderFactory;
-import javax.xml.parsers.ParserConfigurationException;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser;
-import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
-import org.w3c.dom.Document;
-import org.xml.sax.SAXException;
-
-/**
- *
- * @author Lukas Sedlak <lsedlak@cisco.com>
- */
-public class RpcReplyToDomTest {
-
-    private static final DocumentBuilderFactory BUILDER_FACTORY;
-    private static final String RES_SCHEMA_DIR = "/org/opendaylight/yangtools/yang/data/impl/schema";
-
-    private final static String MODEL_NAMESPACE = "org:opendaylight:rpc-reply:test:ns:yang";
-    private final static String MODEL_REVISION = "2014-07-17";
-
-    private final static QName RPC_OUTPUT_QNAME = QName.create(MODEL_NAMESPACE, MODEL_REVISION, "output");
-    private final static QName ROCK_THE_HOUSE_QNAME = QName.create(MODEL_NAMESPACE, MODEL_REVISION, "rock-the-house");
-    private final static QName ACTIV_SW_IMAGE_QNAME = QName.create(MODEL_NAMESPACE, MODEL_REVISION, "activate-software-image");
-
-    private SchemaContext schemaContext;
-    private Document testPayload1;
-    private Document testPayload2;
-
-    static {
-        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
-        factory.setNamespaceAware(true);
-        factory.setCoalescing(true);
-        factory.setIgnoringElementContentWhitespace(true);
-        factory.setIgnoringComments(true);
-        BUILDER_FACTORY = factory;
-    }
-
-    @Before
-    public void setup() throws Exception {
-        final List<InputStream> modelsToParse = Collections
-                .singletonList(getClass().getResourceAsStream(RES_SCHEMA_DIR + "/rpc-test-model.yang"));
-        assertNotNull(modelsToParse);
-        assertNotNull(modelsToParse.get(0));
-
-        final YangContextParser parser = new YangParserImpl();
-        final Set<Module> modules = parser.parseYangModelsFromStreams(modelsToParse);
-        assertTrue(!modules.isEmpty());
-        schemaContext = parser.resolveSchemaContext(modules);
-        assertNotNull(schemaContext);
-
-        final InputStream rpcPayloadStream1 = getClass().getResourceAsStream(RES_SCHEMA_DIR + "/rpc-test-payload1.xml");
-        InputStream rpcPayloadStream2 = getClass().getResourceAsStream(RES_SCHEMA_DIR + "/rpc-test-payload2.xml");
-
-        assertNotNull(rpcPayloadStream1);
-        assertNotNull(rpcPayloadStream2);
-
-        testPayload1 = readXmlToDocument(rpcPayloadStream1);
-        testPayload2 = readXmlToDocument(rpcPayloadStream2);
-
-        assertNotNull(testPayload1);
-        assertNotNull(testPayload2);
-    }
-
-    private static Document readXmlToDocument(final InputStream xmlContent) throws SAXException, IOException {
-        DocumentBuilder dBuilder;
-        try {
-            dBuilder = BUILDER_FACTORY.newDocumentBuilder();
-        } catch (ParserConfigurationException e) {
-            throw new IllegalStateException("Failed to parse XML document", e);
-        }
-        Document doc = dBuilder.parse(xmlContent);
-
-        doc.getDocumentElement().normalize();
-        return doc;
-    }
-
-    @Test
-    public void test() {
-        final CompositeNode rockNode = XmlDocumentUtils
-                .rpcReplyToDomNodes(testPayload1, ROCK_THE_HOUSE_QNAME, schemaContext);
-        assertNotNull(rockNode);
-
-        final String namespace = "org:opendaylight:rpc-reply:test:ns:yang";
-        final String revision = "2014-07-17";
-
-        CompositeNode output = rockNode.getFirstCompositeByName(RPC_OUTPUT_QNAME);
-        assertNotNull(output);
-
-        final SimpleNode<?> zipCode = output.getFirstSimpleByName(
-                QName.create(namespace, revision, "zip-code"));
-        assertNotNull(zipCode);
-
-        final CompositeNode activNode = XmlDocumentUtils
-                .rpcReplyToDomNodes(testPayload2, ACTIV_SW_IMAGE_QNAME, schemaContext);
-        assertNotNull(activNode);
-
-        output = activNode.getFirstCompositeByName(RPC_OUTPUT_QNAME);
-        assertNotNull(output);
-
-        final CompositeNode imgProps = output
-                .getFirstCompositeByName(QName.create(namespace, revision, "image-properties"));
-        assertNotNull(imgProps);
-        final CompositeNode imgProperty = imgProps
-                .getFirstCompositeByName(QName.create(namespace, revision, "image-property"));
-        assertNotNull(imgProperty);
-
-        final SimpleNode<?> imgId = imgProperty
-                .getFirstSimpleByName(QName.create(namespace, revision, "image-id"));
-        assertNotNull(imgId);
-    }
-}
diff --git a/yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/CompositeNodeTOImplTest.java b/yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/CompositeNodeTOImplTest.java
deleted file mode 100644 (file)
index 70bffc0..0000000
+++ /dev/null
@@ -1,58 +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.yangtools.yang.data.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.util.ArrayList;
-import java.util.List;
-
-import org.apache.commons.lang.SerializationUtils;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-@Deprecated
-public class CompositeNodeTOImplTest {
-    @Test
-    public void testSerialization() throws Exception{
-        CompositeNodeTOImpl child1 = new CompositeNodeTOImpl(QName.create("ns", "2013-12-09", "child1"), null, new ArrayList<Node<?>>(), ModifyAction.REPLACE);
-        CompositeNodeTOImpl child2 = new CompositeNodeTOImpl(QName.create("ns", "2013-12-09", "child2"), null, new ArrayList<Node<?>>(), ModifyAction.REPLACE);
-        SimpleNodeTOImpl child3 = new SimpleNodeTOImpl(QName.create("ns", "2013-12-09", "child2"), null, "foo");
-
-        List<Node<?>> children = new ArrayList<Node<?>>();
-        children.add(child1);
-        children.add(child2);
-        children.add(child3);
-
-        CompositeNodeTOImpl parent = new CompositeNodeTOImpl(QName.create("ns", "2013-12-09", "parent"), null, new ArrayList<Node<?>>(), ModifyAction.REPLACE);
-
-        CompositeNodeTOImpl object = new CompositeNodeTOImpl(QName.create("ns", "2013-12-09", "root"), parent, children , ModifyAction.MERGE);
-
-        CompositeNodeTOImpl clone = (CompositeNodeTOImpl) SerializationUtils.clone(object);
-
-        assertNotNull(clone.getNodeType());
-        assertEquals(ModifyAction.MERGE, clone.getModificationAction());
-        assertNotNull(clone.getParent());
-        assertNotNull(clone.getParent().getNodeType());
-        assertNotNull(clone.getValue());
-        assertEquals(3, clone.getValue().size());
-        assertNotNull(clone.getValue().get(0).getNodeType());
-        assertNotNull(clone.getValue().get(1).getNodeType());
-
-        SimpleNodeTOImpl child3Clone = (SimpleNodeTOImpl) clone.getValue().get(2);
-
-        assertNotNull(child3Clone.getNodeType());
-        assertTrue(child3Clone instanceof SimpleNodeTOImpl);
-        assertEquals("foo", child3Clone.getValue());
-
-    }
-}
diff --git a/yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/LazyNodeToNodeMapTest.java b/yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/LazyNodeToNodeMapTest.java
deleted file mode 100644 (file)
index 0824d8b..0000000
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import java.net.URI;
-import java.util.Date;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-
-/**
- * @author michal.rehak
- *
- */
-@Deprecated
-public class LazyNodeToNodeMapTest {
-
-    private LazyNodeToNodeMap lazyN2N;
-    private CompositeNode tree;
-
-    /**
-     * prepare test values
-     * @throws Exception
-     */
-    @Before
-    public void setUp() throws Exception {
-        lazyN2N = new LazyNodeToNodeMap();
-
-        QName qName = QName.create(
-                new URI("urn:ietf:params:xml:ns:netconf:base:1.0"),
-                new Date(42), "yang-data-impl-mutableTest");
-
-        tree = NodeHelper.buildTestConfigTree(qName);
-    }
-
-    /**
-     * Test method for {@link org.opendaylight.yangtools.yang.data.impl.LazyNodeToNodeMap#getMutableEquivalent(org.opendaylight.yangtools.yang.data.api.Node)}.
-     */
-    @Test
-    public void testGetMutableEquivalent() {
-        MutableCompositeNode mutableTree = (MutableCompositeNode) lazyN2N.getMutableEquivalent(tree);
-
-        Assert.assertNull(mutableTree.getParent());
-        Assert.assertEquals(tree.getNodeType(), mutableTree.getNodeType());
-        Assert.assertEquals(1, lazyN2N.getKeyNodes().size());
-
-        Node<?> subNode = tree.getCompositesByName("topologies").iterator().next();
-        Node<?> subMutant = lazyN2N.getMutableEquivalent(subNode);
-
-        Assert.assertNotNull(subMutant.getParent());
-        Assert.assertEquals(subNode.getNodeType(), subMutant.getNodeType());
-        Assert.assertEquals(2, lazyN2N.getKeyNodes().size());
-
-        Assert.assertEquals(mutableTree, subMutant.getParent());
-        Assert.assertEquals(mutableTree.getValue().size(), 1);
-        Assert.assertEquals(mutableTree.getValue().iterator().next(), subMutant);
-    }
-
-    /**
-     * Test method for {@link org.opendaylight.yangtools.yang.data.impl.LazyNodeToNodeMap#getMutableRoot()}.
-     */
-    @Test
-    public void testGetMutableRoot() {
-        Node<?> subNode = tree.getCompositesByName("topologies").iterator().next();
-        Node<?> subMutant = lazyN2N.getMutableEquivalent(subNode);
-
-        Assert.assertNotNull(subMutant.getParent());
-        Assert.assertEquals(subMutant.getParent(), lazyN2N.getMutableRoot());
-    }
-
-}
diff --git a/yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/MyNodeBuilder.java b/yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/MyNodeBuilder.java
deleted file mode 100644 (file)
index 2ad9aed..0000000
+++ /dev/null
@@ -1,187 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import groovy.util.BuilderSupport;
-
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.util.Date;
-import java.util.Map;
-import java.util.Map.Entry;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * @author michal.rehak
- */
-@Deprecated
-public class MyNodeBuilder extends BuilderSupport {
-
-    private static final Logger LOG = LoggerFactory.getLogger(MyNodeBuilder.class);
-
-    private URI qnNamespace;
-    private final Date qnRevision;
-
-    private CompositeNode rootNode;
-
-    /**
-     * @param baseQName
-     */
-    private MyNodeBuilder(final QName baseQName) {
-        qnNamespace = baseQName.getNamespace();
-        qnRevision = baseQName.getRevision();
-    }
-
-    /**
-     * @return initialized singleton instance
-     */
-    public static MyNodeBuilder newInstance() {
-        QName qName = null;
-        try {
-            qName = QName.create(
-                    new URI("urn:opendaylight:controller:network"),
-                    new Date(42), "node");
-        } catch (URISyntaxException e) {
-            LOG.error(e.getMessage(), e);
-        }
-        return new MyNodeBuilder(qName);
-    }
-
-    @Override
-    protected void setParent(final Object parent, final Object child) {
-        // do nothing
-        if (child instanceof AbstractNodeTO<?>) {
-            ((AbstractNodeTO<?>) child).setParent((CompositeNode) parent);
-        } else {
-            LOG.error("PARENTING FAILED: "+parent + " -> " + child);
-        }
-    }
-
-    @Override
-    protected Object createNode(final Object name) {
-        MutableCompositeNode newNode = NodeFactory.createMutableCompositeNode(
-                createQName(name), getCurrentNode(), null, null, null);
-        NodeUtils.fixParentRelation(newNode);
-        return newNode;
-    }
-
-    @Override
-    protected Object createNode(final Object name, @SuppressWarnings("rawtypes") final Map attributes) {
-        ModifyAction modifyAction = processAttributes(attributes);
-        MutableCompositeNode newNode = NodeFactory.createMutableCompositeNode(
-                createQName(name), getCurrentNode(), null, modifyAction, null);
-        NodeUtils.fixParentRelation(newNode);
-        return newNode;
-    }
-
-
-    @Override
-    protected Object createNode(final Object name, @SuppressWarnings("rawtypes") final Map attributes, final Object value) {
-        ModifyAction modifyAction = processAttributes(attributes);
-        SimpleNode<Object> newNode = NodeFactory.createImmutableSimpleNode(
-                createQName(name), (CompositeNode) getCurrent(), value, modifyAction);
-        NodeUtils.fixParentRelation(newNode);
-        return newNode;
-    }
-
-    /**
-     * @param attributes
-     * @return
-     */
-    private ModifyAction processAttributes(@SuppressWarnings("rawtypes") final Map attributes) {
-        LOG.debug("attributes:" + attributes);
-        ModifyAction modAction = null;
-
-        @SuppressWarnings("unchecked")
-        Map<String, String> attributesSane = attributes;
-        for (Entry<String, String> attr : attributesSane.entrySet()) {
-            switch (attr.getKey()) {
-            case "xmlns":
-                try {
-                    qnNamespace = new URI(attr.getValue());
-                } catch (URISyntaxException e) {
-                    LOG.error(e.getMessage(), e);
-                }
-                break;
-            case "modifyAction":
-                modAction = ModifyAction.valueOf(attr.getValue());
-                break;
-
-            default:
-                throw new IllegalArgumentException("Attribute not supported: "+attr.getKey());
-            }
-        }
-        return modAction;
-    }
-
-    @Override
-    protected Object createNode(final Object name, final Object value) {
-        SimpleNode<Object> newNode = NodeFactory.createImmutableSimpleNode(createQName(name), (CompositeNode) getCurrent(), value);
-        NodeUtils.fixParentRelation(newNode);
-        return newNode;
-    }
-
-    private QName createQName(final Object localName) {
-        LOG.debug("qname for: "+localName);
-        return QName.create(qnNamespace, qnRevision, (String) localName);
-    }
-
-    protected CompositeNode getCurrentNode() {
-        if (getCurrent() != null) {
-            if (getCurrent() instanceof CompositeNode) {
-                return (CompositeNode) getCurrent();
-
-            } else {
-                throw new IllegalAccessError("current node is not of type CompositeNode, but: "
-                        +getCurrent().getClass().getSimpleName());
-            }
-        }
-
-        return null;
-    }
-
-    @Override
-    protected Object postNodeCompletion(final Object parent, final Object node) {
-        Node<?> nodeRevisited = (Node<?>) node;
-        LOG.debug("postNodeCompletion at: \n  "+ nodeRevisited+"\n  "+parent);
-        if (nodeRevisited instanceof MutableCompositeNode) {
-            MutableCompositeNode mutant = (MutableCompositeNode) nodeRevisited;
-            if (mutant.getValue().isEmpty()) {
-                LOG.error("why is it having empty value? -- " + mutant);
-            }
-            nodeRevisited = NodeFactory.createImmutableCompositeNode(
-                    mutant.getNodeType(), mutant.getParent(), mutant.getValue(), mutant.getModificationAction());
-            NodeUtils.fixChildrenRelation((CompositeNode) nodeRevisited);
-
-            if (parent == null) {
-                rootNode = (CompositeNode) nodeRevisited;
-            } else {
-                NodeUtils.fixParentRelation(nodeRevisited);
-                nodeRevisited.getParent().getValue().remove(mutant);
-            }
-        }
-
-
-        return nodeRevisited;
-    }
-
-    /**
-     * @return tree root
-     */
-    public CompositeNode getRootNode() {
-        return rootNode;
-    }
-}
diff --git a/yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/NodeFactoryTest.java b/yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/NodeFactoryTest.java
deleted file mode 100644 (file)
index cafc14c..0000000
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.NodeModification;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.w3c.dom.Document;
-
-/**
- * @author michal.rehak
- *
- */
-@Deprecated
-public class NodeFactoryTest {
-
-    private QName qName;
-    private CompositeNode network;
-
-    private String ns;
-    private Document networkShadow;
-
-
-    /**
-     * @throws Exception
-     */
-    @Before
-    public void setUp() throws Exception {
-        ns = "urn:ietf:params:xml:ns:netconf:base:1.0";
-        qName = QName.create(
-                new URI(ns),
-                new Date(42), "node");
-        network = NodeHelper.buildTestConfigTree(qName);
-        networkShadow = NodeUtils.buildShadowDomTree(network);
-        NodeHelper.compareXmlTree(networkShadow, "./config02-shadow.xml", getClass());
-    }
-
-    /**
-     * Test method for methods creating immutable nodes in
-     * {@link org.opendaylight.yangtools.yang.data.impl.NodeFactory}.
-     * @throws Exception
-     */
-    @Test
-    public void testImmutableNodes() throws Exception {
-        Assert.assertEquals(2, network.getValue().size());
-        CompositeNode tpList = NodeUtils.findNodeByXpath(networkShadow,
-                NodeHelper.AddNamespaceToPattern(
-                        "//{0}node[{0}node-id/text()='nodeId_19']/{0}termination-points", ns));
-
-
-        Assert.assertEquals(2, tpList.getCompositesByName("termination-point").size());
-    }
-
-    /**
-     * Test method for methods creating immutable and mutable nodes:
-     * {@link NodeFactory#createMutableCompositeNode(QName, CompositeNode, List, ModifyAction, CompositeNode)},
-     * {@link NodeFactory#createMutableSimpleNode(QName, CompositeNode, Object, ModifyAction, SimpleNode)}
-     * @throws Exception
-     */
-    @Test
-    public void testMutableNodes() throws Exception {
-        // <config>
-        //   <top xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
-        //     <interface xc:operation="delete">
-        //       <name>Ethernet0/0</name>
-        //       <mtu>1500</mtu>
-        //     </interface>
-        //     <interface>
-        //       <name>Ethernet0/1</name>
-        //       <mtu>1501</mtu>
-        //     </interface>
-        //   </top>
-        // </config>
-
-
-        List<Node<?>> value = new ArrayList<Node<?>>();
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "name"), null, "Ethernet0/0"));
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "mtu"), null, 1500));
-
-        MutableCompositeNode ifNode = NodeFactory.createMutableCompositeNode(
-                QName.create(qName, "interface"), null,
-                value, ModifyAction.DELETE, null);
-        ifNode.init();
-        NodeHelper.assignParentToChildren(ifNode);
-
-        value = new ArrayList<Node<?>>();
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "name"), null, "Ethernet1/0"));
-        value.add(NodeFactory.createMutableSimpleNode(QName.create(qName, "mtu"), null, 1501, ModifyAction.REMOVE, null));
-
-        CompositeNode ifNode2 = NodeFactory.createImmutableCompositeNode(QName.create(qName, "interface"), null, value);
-        NodeHelper.assignParentToChildren(ifNode2);
-
-        value = new ArrayList<Node<?>>();
-        value.add(ifNode);
-        value.add(ifNode2);
-
-        CompositeNode topNode = NodeFactory.createImmutableCompositeNode(QName.create(qName, "top"), null, value);
-        NodeHelper.assignParentToChildren(topNode);
-        value = new ArrayList<Node<?>>();
-        value.add(topNode);
-
-        CompositeNode root = NodeFactory.createImmutableCompositeNode(QName.create(qName, "config"), null, value);
-        Document shadowConfig = NodeUtils.buildShadowDomTree(root);
-        NodeHelper.compareXmlTree(shadowConfig, "./mutableNodesConfig.xml", getClass());
-
-        Assert.assertEquals(1, root.getValue().size());
-        Assert.assertEquals(1, ifNode.getSimpleNodesByName("name").size());
-        Assert.assertEquals(1, ifNode.getSimpleNodesByName("mtu").size());
-        Assert.assertEquals(2, topNode.getCompositesByName("interface").size());
-        NodeModification interfaceMod = topNode.getCompositesByName("interface").get(0);
-        Assert.assertEquals(ModifyAction.DELETE, interfaceMod.getModificationAction());
-    }
-
-    /**
-     * test of {@link NodeFactory#copyDeepAsMutable(CompositeNode, Map)}
-     * @throws Exception
-     */
-    @Test
-    public void testCopyDeepAsMutable() throws Exception {
-        Map<Node<?>, Node<?>> mutableToOrig = new HashMap<>();
-        CompositeNode mutableNetwork = NodeFactory.copyDeepAsMutable(network, mutableToOrig);
-
-        Document mutableNetworkShadow = NodeUtils.buildShadowDomTree(mutableNetwork);
-
-        NodeHelper.compareXmlTree(mutableNetworkShadow, "./config02-shadow.xml", getClass());
-
-        CompositeNode immutableNetwork = NodeFactory.copyDeepAsImmutable(mutableNetwork, null);
-        Assert.assertEquals(network, immutableNetwork);
-    }
-
-
-    /**
-     * test of {@link NodeFactory#copyDeepAsImmutable(CompositeNode, Map)}
-     * @throws Exception
-     */
-    @Test
-    public void testCopyDeepAsImmutable() throws Exception {
-        Map<Node<?>, Node<?>> mutableToOrig = new HashMap<>();
-        CompositeNode immutableNetwork = NodeFactory.copyDeepAsImmutable(network, mutableToOrig);
-
-        Document mutableNetworkShadow = NodeUtils.buildShadowDomTree(immutableNetwork);
-        NodeHelper.compareXmlTree(mutableNetworkShadow, "./config02-shadow.xml", getClass());
-
-        Assert.assertEquals(network, immutableNetwork);
-    }
-
-}
diff --git a/yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/NodeHelper.java b/yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/NodeHelper.java
deleted file mode 100644 (file)
index 901750b..0000000
+++ /dev/null
@@ -1,426 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import groovy.lang.Binding;
-import groovy.lang.GroovyShell;
-import groovy.lang.Script;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.PrintStream;
-import java.io.Reader;
-import java.io.StringWriter;
-import java.lang.reflect.Method;
-import java.text.MessageFormat;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-import javax.xml.transform.OutputKeys;
-import javax.xml.transform.Transformer;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.TransformerFactory;
-import javax.xml.transform.dom.DOMSource;
-import javax.xml.transform.stream.StreamResult;
-import org.custommonkey.xmlunit.Diff;
-import org.junit.Assert;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodes;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.parser.api.YangModelParser;
-import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-import org.xml.sax.SAXException;
-
-/**
- * @author michal.rehak
- *
- * @deprecated Use {@link NormalizedNodes} instead.
- */
-@Deprecated
-public abstract class NodeHelper {
-
-    private static final Logger LOG = LoggerFactory.getLogger(NodeHelper.class);
-
-    /** xml source of example network configuration */
-    public static final String NETWORK_XML =
-            "<network xmlns=\"urn:opendaylight:controller:network\">\n" +
-                    //"<network>\n" +
-                    "    <topologies>\n" +
-                    "        <topology>\n" +
-                    "            <topology-id>topId_01</topology-id>\n" +
-                    "            <nodes>\n" +
-                    "                <node>\n" +
-                    "                    <node-id>nodeId_02</node-id>\n" +
-                    "                    <supporting-ne>networkId_02</supporting-ne>\n" +
-                    "                    <termination-points>\n" +
-                    "                        <termination-point>\n" +
-                    "                            <tp-id>tpId_03</tp-id>\n" +
-                    "                        </termination-point>\n" +
-                    "                    </termination-points>\n" +
-                    "                </node>\n" +
-                    "                <node>\n" +
-                    "                    <node-id>nodeId_16</node-id>\n" +
-                    "                    <supporting-ne>networkId_17</supporting-ne>\n" +
-                    "                    <termination-points>\n" +
-                    "                        <termination-point>\n" +
-                    "                            <tp-id>tpId_18</tp-id>\n" +
-                    "                        </termination-point>\n" +
-                    "                    </termination-points>\n" +
-                    "                </node>\n" +
-                    "                <node>\n" +
-                    "                    <node-id>nodeId_19</node-id>\n" +
-                    "                    <supporting-ne>networkId_20</supporting-ne>\n" +
-                    "                    <termination-points>\n" +
-                    "                        <termination-point>\n" +
-                    "                            <tp-id>tpId_18</tp-id>\n" +
-                    "                        </termination-point>\n" +
-                    "                        <termination-point>\n" +
-                    "                            <tp-id>tpId_19</tp-id>\n" +
-                    "                        </termination-point>\n" +
-                    "                    </termination-points>\n" +
-                    "                </node>\n" +
-                    "            </nodes>\n" +
-                    "            <links>\n" +
-                    "                <link>\n" +
-                    "                    <link-id>linkId_04</link-id>\n" +
-                    "                    <source>\n" +
-                    "                        <source-node>nodeId_05</source-node>\n" +
-                    "                        <source-tp>tpId_06</source-tp>\n" +
-                    "                    </source>\n" +
-                    "                    <destination>\n" +
-                    "                        <dest-node>nodeId_07</dest-node>\n" +
-                    "                        <dest-tp>tpId_08</dest-tp>\n" +
-                    "                    </destination>\n" +
-                    "                </link>\n" +
-                    "                <link>\n" +
-                    "                    <link-id>linkId_11</link-id>\n" +
-                    "                    <source>\n" +
-                    "                        <source-node>nodeId_12</source-node>\n" +
-                    "                        <source-tp>tpId_13</source-tp>\n" +
-                    "                    </source>\n" +
-                    "                    <destination>\n" +
-                    "                        <dest-node>nodeId_14</dest-node>\n" +
-                    "                        <dest-tp>tpId_15</dest-tp>\n" +
-                    "                    </destination>\n" +
-                    "                </link>\n" +
-                    "            </links>\n" +
-                    "        </topology>\n" +
-                    "    </topologies>\n" +
-                    "    <network-elements>\n" +
-                    "        <network-element>\n" +
-                    "            <element-id>ntElementId_09</element-id>\n" +
-                    "        </network-element>\n" +
-                    "        <network-element>\n" +
-                    "            <element-id>ntElementId_10</element-id>\n" +
-                    "        </network-element>\n" +
-                    "    </network-elements>\n" +
-                    "</network>";
-
-    private static String domTreeString(final Document domTree) throws TransformerException {
-        TransformerFactory transformerFact = TransformerFactory.newInstance();
-        transformerFact.setAttribute("indent-number", 4);
-        Transformer transformer = transformerFact.newTransformer();
-        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
-        //initialize StreamResult with File object to save to file
-        StreamResult result = new StreamResult(new StringWriter());
-        DOMSource source = new DOMSource(domTree);
-        transformer.transform(source, result);
-        return result.getWriter().toString();
-    }
-
-    /**
-     * @param domTree
-     * @param out
-     * @throws Exception
-     */
-    private static void dumpDoc(final Document domTree, final PrintStream out) throws Exception {
-        out.println(domTreeString(domTree));
-    }
-
-    public static void dumpDoc(final Document domTree, final Logger logger) throws TransformerException {
-        logger.info("{}", domTreeString(domTree));
-    }
-
-    /**
-     * @param qName
-     * @return example tree, see {@link #NETWORK_XML}
-     */
-    public static CompositeNode buildTestConfigTree(final QName qName) {
-        List<Node<?>> value = new ArrayList<Node<?>>();
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "element-id"), null, "ntElementId_09"));
-        CompositeNode ntElementNode1 = NodeFactory.createImmutableCompositeNode(QName.create(qName, "network-element"),
-                null, value);
-        assignParentToChildren(ntElementNode1);
-
-        value = new ArrayList<Node<?>>();
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "element-id"), null, "ntElementId_10"));
-        CompositeNode ntElementNode2 = NodeFactory.createImmutableCompositeNode(QName.create(qName, "network-element"),
-                null, value);
-        assignParentToChildren(ntElementNode2);
-
-        value = new ArrayList<Node<?>>();
-        value.add(ntElementNode1);
-        value.add(ntElementNode2);
-        CompositeNode ntElementsNode = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "network-elements"), null, value);
-        assignParentToChildren(ntElementsNode);
-
-        value = new ArrayList<Node<?>>();
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "dest-node"), null, "nodeId_07"));
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "dest-tp"), null, "tpId_08"));
-        CompositeNode destination = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "destination"), null,
-                value);
-        assignParentToChildren(destination);
-
-        value = new ArrayList<Node<?>>();
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "source-node"), null, "nodeId_05"));
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "source-tp"), null, "tpId_06"));
-        CompositeNode source = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "source"), null, value);
-        assignParentToChildren(source);
-
-        value = new ArrayList<Node<?>>();
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "link-id"), null, "linkId_04"));
-        value.add(source);
-        value.add(destination);
-        CompositeNode link1 = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "link"), null, value);
-        assignParentToChildren(link1);
-
-        value = new ArrayList<Node<?>>();
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "dest-node"), null, "nodeId_14"));
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "dest-tp"), null, "tpId_15"));
-        destination = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "destination"), null, value);
-        assignParentToChildren(destination);
-
-        value = new ArrayList<Node<?>>();
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "source-node"), null, "nodeId_12"));
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "source-tp"), null, "tpId_13"));
-        source = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "source"), null, value);
-        assignParentToChildren(source);
-
-        value = new ArrayList<Node<?>>();
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "link-id"), null, "linkId_11"));
-        value.add(source);
-        value.add(destination);
-        CompositeNode link2 = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "link"), null, value);
-        assignParentToChildren(link2);
-
-        value = new ArrayList<Node<?>>();
-        value.add(link1);
-        value.add(link2);
-        CompositeNode links = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "links"), null, value);
-        assignParentToChildren(links);
-
-
-        value = new ArrayList<Node<?>>();
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "tp-id"), null, "tpId_03"));
-        CompositeNode terminationPointNode1 = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "termination-point"), null, value);
-        assignParentToChildren(terminationPointNode1);
-
-        value = new ArrayList<Node<?>>();
-        value.add(terminationPointNode1);
-        CompositeNode terminationPointsNode = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "termination-points"), null, value);
-        assignParentToChildren(terminationPointsNode);
-
-        value = new ArrayList<Node<?>>();
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "node-id"), null, "nodeId_02"));
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "supporting-ne"), null, "networkId_02"));
-        value.add(terminationPointsNode);
-        CompositeNode node1Node = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "node"), null, value);
-        assignParentToChildren(node1Node);
-
-        value = new ArrayList<Node<?>>();
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "tp-id"), null, "tpId_18"));
-        terminationPointNode1 = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "termination-point"),
-                null, value);
-        assignParentToChildren(terminationPointNode1);
-
-        value = new ArrayList<Node<?>>();
-        value.add(terminationPointNode1);
-        terminationPointsNode = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "termination-points"),
-                null, value);
-        assignParentToChildren(terminationPointsNode);
-
-        value = new ArrayList<Node<?>>();
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "node-id"), null, "nodeId_16"));
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "supporting-ne"), null, "networkId_17"));
-        value.add(terminationPointsNode);
-        CompositeNode node2Node = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "node"), null, value);
-        assignParentToChildren(node2Node);
-
-        value = new ArrayList<Node<?>>();
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "tp-id"), null, "tpId_18"));
-        terminationPointNode1 = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "termination-point"),
-                null, value);
-        assignParentToChildren(terminationPointNode1);
-
-        value = new ArrayList<Node<?>>();
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "tp-id"), null, "tpId_19"));
-        CompositeNode terminationPointNode2 = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "termination-point"), null, value);
-        assignParentToChildren(terminationPointNode2);
-
-        value = new ArrayList<Node<?>>();
-        value.add(terminationPointNode1);
-        value.add(terminationPointNode2);
-        terminationPointsNode = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "termination-points"),
-                null, value);
-        assignParentToChildren(terminationPointsNode);
-
-        value = new ArrayList<Node<?>>();
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "node-id"), null, "nodeId_19"));
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "supporting-ne"), null, "networkId_20"));
-        value.add(terminationPointsNode);
-        CompositeNode node3Node = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "node"), null, value);
-        assignParentToChildren(node3Node);
-
-        value = new ArrayList<Node<?>>();
-        value.add(node1Node);
-        value.add(node2Node);
-        value.add(node3Node);
-        CompositeNode nodesNode = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "nodes"), null, value);
-        assignParentToChildren(nodesNode);
-
-        value = new ArrayList<Node<?>>();
-        value.add(links);
-        value.add(nodesNode);
-        value.add(NodeFactory.createImmutableSimpleNode(QName.create(qName, "topology-id"), null, "topId_01"));
-        CompositeNode topology = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "topology"), null, value);
-        assignParentToChildren(topology);
-
-        value = new ArrayList<Node<?>>();
-        value.add(topology);
-        CompositeNode topologies = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "topologies"), null,
-                value);
-        assignParentToChildren(topologies);
-
-        value = new ArrayList<Node<?>>();
-        value.add(topologies);
-        value.add(ntElementsNode);
-        CompositeNode network = NodeFactory.createImmutableCompositeNode(
-                QName.create(qName, "network"), null, value);
-        assignParentToChildren(network);
-
-        return network;
-    }
-
-    /**
-     * @param parentNode
-     */
-    public static void assignParentToChildren(final CompositeNode parentNode) {
-        for (Node<?> child : parentNode.getValue()) {
-            ((AbstractNodeTO<?>) child).setParent(parentNode);
-        }
-    }
-
-    /**
-     * @return schema context of controller-network.yang
-     */
-    public static SchemaContext loadSchemaContext() {
-        YangModelParser yParser = new YangParserImpl();
-        List<InputStream> yangInputStreams = new ArrayList<>();
-        yangInputStreams.add(NodeHelper.class.getResourceAsStream(
-                "/controller-network.yang"));
-        yangInputStreams.add(NodeHelper.class.getResourceAsStream(
-                "/ietf-inet-types@2010-09-24.yang"));
-        Set<Module> modules = yParser
-                .parseYangModelsFromStreams(yangInputStreams);
-        return yParser.resolveSchemaContext(modules);
-    }
-
-    /**
-     * @param scriptName
-     * @return tree root
-     * @throws Exception
-     */
-    public static CompositeNode loadConfigByGroovy(final String scriptName) throws Exception {
-        InputStream configStream = NodeHelper.class.getResourceAsStream(scriptName);
-        Binding binding = new Binding();
-        GroovyShell gShell = new GroovyShell(binding);
-        LOG.debug("groovy: starting script parse..  {}", scriptName);
-        Script configScript = gShell.parse(new InputStreamReader(configStream));
-        LOG.debug("groovy: starting script..  {}", scriptName);
-        configScript.run();
-        LOG.debug("groovy: digging result");
-        Object xmlGen = binding.getVariable("xmlGen");
-        LOG.debug("xmlGen = {}", xmlGen);
-        Method getter = xmlGen.getClass().getDeclaredMethod("getBuilder", new Class[0]);
-        MyNodeBuilder builder = (MyNodeBuilder) getter.invoke(xmlGen, new Object[0]);
-
-        return builder.getRootNode();
-    }
-
-    /**
-     * @param pattern , e.g.: <pre>"//{0}:network/{1}:xx[text() = 'sss']"</pre>
-     * @param nsArg , e.g.: <pre>{"uri:ns1", "uri:ns2"}</pre>
-     * @return pattern with namespaces: <pre>//uri:ns1:network/uri:ns2:xx[text() = ''sss'']"</pre>
-     */
-    public static String AddNamespaceToPattern(final String pattern, final Object... nsArg) {
-        Object[] ns = nsArg;
-        String patternNs = pattern.replaceAll("'", "''");
-        if (ns == null) {
-            ns = new Object[]{""};
-        } else {
-            // add ':' into pattern after placeholders
-            patternNs = patternNs.replaceAll("(\\{[0-9]+\\})", "$1:");
-        }
-
-        return MessageFormat.format(patternNs, ns);
-    }
-
-    /**
-     * @param tree
-     * @param xmlFile
-     * @param clazz
-     * @throws Exception
-     * @throws SAXException
-     * @throws IOException
-     */
-    public static void compareXmlTree(final Document tree, final String xmlFile, final Class<?> clazz) throws Exception,
-    SAXException, IOException {
-        ByteArrayOutputStream actualRaw = new ByteArrayOutputStream();
-        dumpDoc(tree, new PrintStream(actualRaw));
-        Reader actualReader = new InputStreamReader(new ByteArrayInputStream(actualRaw.toByteArray()));
-
-        Reader expectedReader = new InputStreamReader(clazz.getResourceAsStream(xmlFile));
-        Diff myDiff = new Diff(expectedReader, actualReader);
-        myDiff.overrideDifferenceListener(new IgnoreWhiteCharsDiffListener());
-
-        boolean similar = myDiff.similar();
-        if (! similar) {
-            LOG.info("{}", new String(actualRaw.toByteArray()));
-        }
-        Assert.assertEquals(myDiff.toString(), true, similar);
-    }
-}
diff --git a/yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/NodeModificationBuilderImplTest.java b/yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/NodeModificationBuilderImplTest.java
deleted file mode 100644 (file)
index 70c2c81..0000000
+++ /dev/null
@@ -1,300 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import static org.junit.Assert.assertSame;
-
-import java.net.URI;
-import java.util.Date;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-
-/**
- * @author michal.rehak
- *
- */
-@Deprecated
-public class NodeModificationBuilderImplTest {
-
-    private static final Logger LOG = LoggerFactory.getLogger(NodeModificationBuilderImplTest.class);
-
-    private SchemaContext schemaCtx;
-    private QName qName;
-    private CompositeNode network;
-    private NodeModificationBuilderImpl nodeModificationBuilder;
-
-    private String ns;
-
-    /**
-     * @throws Exception
-     */
-    private void dumpResult() throws Exception {
-        CompositeNode diffTree = nodeModificationBuilder.buildDiffTree();
-        CompositeNode diffTreeImmutable = NodeFactory.copyDeepAsImmutable(diffTree, null);
-
-        Document diffShadow = NodeUtils.buildShadowDomTree(diffTreeImmutable);
-        NodeHelper.dumpDoc(diffShadow, LOG);
-    }
-
-    /**
-     * prepare schemaContext
-     *
-     * @throws Exception
-     */
-    @Before
-    public void setUp() throws Exception {
-        schemaCtx = NodeHelper.loadSchemaContext();
-
-        ns = "urn:opendaylight:controller:network";
-        qName = QName.create(new URI(ns), new Date(1369000800000L), "topos");
-        network = NodeHelper.buildTestConfigTree(qName);
-
-        nodeModificationBuilder = new NodeModificationBuilderImpl(schemaCtx);
-    }
-
-    /**
-     * Test method for
-     * {@link org.opendaylight.yangtools.yang.data.impl.NodeModificationBuilderImpl#getMutableEquivalent(org.opendaylight.yangtools.yang.data.api.Node)}
-     * .
-     */
-    @Test
-    public void testGetMutableEquivalent() {
-        MutableCompositeNode rootMutable = (MutableCompositeNode) nodeModificationBuilder.getMutableEquivalent(network);
-
-        CompositeNode topologies = network.getCompositesByName("topologies").iterator().next();
-        Node<?> mutableEquivalent = nodeModificationBuilder.getMutableEquivalent(topologies);
-        CompositeNode topologiesMutable = rootMutable.getCompositesByName("topologies").iterator().next();
-
-        assertSame(topologiesMutable, mutableEquivalent);
-    }
-
-    /**
-     * Test method for
-     * {@link org.opendaylight.yangtools.yang.data.impl.NodeModificationBuilderImpl#buildDiffTree()}
-     * .
-     *
-     * @throws Exception
-     */
-    @Test
-    public void testBuildDiffTreeAddSimple() throws Exception {
-        LOG.debug("testBuildDiffTreeAddSimple");
-        Document networkShadow = NodeUtils.buildShadowDomTree(network);
-        CompositeNode needle = NodeUtils.findNodeByXpath(networkShadow,
-                NodeHelper.AddNamespaceToPattern("//{0}node[{0}node-id='nodeId_19']//{0}termination-point[2]", ns));
-
-        MutableCompositeNode mutableParent = (MutableCompositeNode) nodeModificationBuilder
-                .getMutableEquivalent(needle);
-
-        MutableSimpleNode<String> newMutable = NodeFactory.createMutableSimpleNode(
-                QName.create(needle.getNodeType(),
-                        "anySubNode"), mutableParent, "42", null, null);
-
-        nodeModificationBuilder.addNode(newMutable);
-        dumpResult();
-    }
-
-    /**
-     * Test method for
-     * {@link org.opendaylight.yangtools.yang.data.impl.NodeModificationBuilderImpl#buildDiffTree()}
-     * .
-     *
-     * @throws Exception
-     */
-    @Test
-    public void testBuildDiffTreeAddComposite() throws Exception {
-        LOG.debug("testBuildDiffTreeAddComposite");
-        Document networkShadow = NodeUtils.buildShadowDomTree(network);
-        CompositeNode needle = NodeUtils.findNodeByXpath(networkShadow,
-                NodeHelper.AddNamespaceToPattern("//{0}node[{0}node-id='nodeId_19']//{0}termination-point[2]", ns));
-
-        MutableCompositeNode mutableParent = (MutableCompositeNode) nodeModificationBuilder
-                .getMutableEquivalent(needle);
-
-        MutableSimpleNode<String> newMutable = NodeFactory.createMutableSimpleNode(
-                QName.create(needle.getNodeType(),
-                        "anySubNode"), null, "42", null, null);
-
-        MutableCompositeNode newMutableCom = NodeFactory.createMutableCompositeNode(
-                QName.create(needle.getNodeType(),
-                        "anySubNode"), mutableParent, NodeUtils.buildChildrenList(newMutable), null, null);
-        NodeUtils.fixChildrenRelation(newMutableCom);
-        newMutableCom.init();
-
-        nodeModificationBuilder.addNode(newMutableCom);
-        dumpResult();
-    }
-
-    /**
-     * Test method for
-     * {@link org.opendaylight.yangtools.yang.data.impl.NodeModificationBuilderImpl#buildDiffTree()}
-     * .
-     *
-     * @throws Exception
-     */
-    @Test
-    public void testBuildDiffTreeDeleteComposite() throws Exception {
-        LOG.debug("testBuildDiffTreeDeleteComposite");
-        Document networkShadow = NodeUtils.buildShadowDomTree(network);
-        SimpleNode<?> needle = NodeUtils.findNodeByXpath(networkShadow, NodeHelper.AddNamespaceToPattern(
-                "//{0}node[{0}node-id='nodeId_19']//{0}termination-point[2]/{0}tp-id", ns));
-
-        @SuppressWarnings("unchecked")
-        MutableSimpleNode<String> mutableNeedle = (MutableSimpleNode<String>) nodeModificationBuilder
-        .getMutableEquivalent(needle);
-
-        nodeModificationBuilder.deleteNode(mutableNeedle.getParent().asMutable());
-        dumpResult();
-    }
-
-    /**
-     * Test method for
-     * {@link org.opendaylight.yangtools.yang.data.impl.NodeModificationBuilderImpl#buildDiffTree()}
-     * .
-     *
-     * @throws Exception
-     */
-    @Test
-    public void testBuildDiffTreeDeleteSimple() throws Exception {
-        LOG.debug("testBuildDiffTreeDeleteSimple");
-        Document networkShadow = NodeUtils.buildShadowDomTree(network);
-        SimpleNode<?> needle = NodeUtils.findNodeByXpath(networkShadow, NodeHelper.AddNamespaceToPattern(
-                "//{0}node[{0}node-id='nodeId_19']//{0}termination-point[2]/{0}tp-id", ns));
-
-        @SuppressWarnings("unchecked")
-        MutableSimpleNode<String> mutableNeedle = (MutableSimpleNode<String>) nodeModificationBuilder
-        .getMutableEquivalent(needle);
-
-        nodeModificationBuilder.deleteNode(mutableNeedle);
-        dumpResult();
-    }
-
-    /**
-     * Test method for
-     * {@link org.opendaylight.yangtools.yang.data.impl.NodeModificationBuilderImpl#buildDiffTree()}
-     * .
-     *
-     * @throws Exception
-     */
-    @Test
-    public void testBuildDiffTreeMerge() throws Exception {
-        LOG.debug("testBuildDiffTreeMerge");
-        Document networkShadow = NodeUtils.buildShadowDomTree(network);
-        SimpleNode<?> needle = NodeUtils.findNodeByXpath(networkShadow, NodeHelper.AddNamespaceToPattern(
-                "//{0}node[{0}node-id='nodeId_19']//{0}termination-point[2]/{0}tp-id", ns));
-
-        @SuppressWarnings("unchecked")
-        MutableSimpleNode<String> mutableNeedle = (MutableSimpleNode<String>) nodeModificationBuilder
-        .getMutableEquivalent(needle);
-
-        mutableNeedle.setValue("tpId_18x");
-        nodeModificationBuilder.mergeNode(mutableNeedle.getParent().asMutable());
-        dumpResult();
-    }
-
-    /**
-     * Test method for
-     * {@link org.opendaylight.yangtools.yang.data.impl.NodeModificationBuilderImpl#buildDiffTree()}
-     * .
-     *
-     * @throws Exception
-     */
-    @Test
-    public void testBuildDiffTreeRemoveComposite() throws Exception {
-        LOG.debug("testBuildDiffTreeRemoveComposite");
-        Document networkShadow = NodeUtils.buildShadowDomTree(network);
-        SimpleNode<?> needle = NodeUtils.findNodeByXpath(networkShadow, NodeHelper.AddNamespaceToPattern(
-                "//{0}node[{0}node-id='nodeId_19']//{0}termination-point[2]/{0}tp-id", ns));
-
-        @SuppressWarnings("unchecked")
-        MutableSimpleNode<String> mutableNeedle = (MutableSimpleNode<String>) nodeModificationBuilder
-        .getMutableEquivalent(needle);
-
-        nodeModificationBuilder.removeNode(mutableNeedle.getParent().asMutable());
-        dumpResult();
-    }
-
-    /**
-     * Test method for
-     * {@link org.opendaylight.yangtools.yang.data.impl.NodeModificationBuilderImpl#buildDiffTree()}
-     * .
-     *
-     * @throws Exception
-     */
-    @Test
-    public void testBuildDiffTreeRemoveSimple() throws Exception {
-        LOG.debug("testBuildDiffTreeRemoveSimple");
-        Document networkShadow = NodeUtils.buildShadowDomTree(network);
-        SimpleNode<?> needle = NodeUtils.findNodeByXpath(networkShadow, NodeHelper.AddNamespaceToPattern(
-                "//{0}node[{0}node-id='nodeId_19']//{0}termination-point[2]/{0}tp-id", ns));
-
-        @SuppressWarnings("unchecked")
-        MutableSimpleNode<String> mutableNeedle = (MutableSimpleNode<String>) nodeModificationBuilder
-        .getMutableEquivalent(needle);
-
-        nodeModificationBuilder.removeNode(mutableNeedle);
-        dumpResult();
-    }
-
-    /**
-     * Test method for
-     * {@link org.opendaylight.yangtools.yang.data.impl.NodeModificationBuilderImpl#buildDiffTree()}
-     * .
-     *
-     * @throws Exception
-     */
-    @Test
-    public void testBuildDiffTreeReplaceComposite() throws Exception {
-        LOG.debug("testBuildDiffTreeReplaceComposite");
-        Document networkShadow = NodeUtils.buildShadowDomTree(network);
-        SimpleNode<?> needle = NodeUtils.findNodeByXpath(networkShadow, NodeHelper.AddNamespaceToPattern(
-                "//{0}node[{0}node-id='nodeId_19']//{0}termination-point[2]/{0}tp-id", ns));
-
-        @SuppressWarnings("unchecked")
-        MutableSimpleNode<String> mutableNeedle = (MutableSimpleNode<String>) nodeModificationBuilder
-        .getMutableEquivalent(needle);
-
-        mutableNeedle.setValue("tpId_18x");
-        nodeModificationBuilder.replaceNode(mutableNeedle.getParent().asMutable());
-        dumpResult();
-    }
-
-    /**
-     * Test method for
-     * {@link org.opendaylight.yangtools.yang.data.impl.NodeModificationBuilderImpl#buildDiffTree()}
-     * .
-     *
-     * @throws Exception
-     */
-    @Test
-    public void testBuildDiffTreeReplaceSimple() throws Exception {
-        LOG.debug("testBuildDiffTreeReplaceSimple");
-        Document networkShadow = NodeUtils.buildShadowDomTree(network);
-        SimpleNode<?> needle = NodeUtils.findNodeByXpath(networkShadow, NodeHelper.AddNamespaceToPattern(
-                "//{0}node[{0}node-id='nodeId_19']//{0}termination-point[2]/{0}tp-id", ns));
-
-        @SuppressWarnings("unchecked")
-        MutableSimpleNode<String> mutableNeedle = (MutableSimpleNode<String>) nodeModificationBuilder
-        .getMutableEquivalent(needle);
-
-        mutableNeedle.setValue("tpId_18x");
-        nodeModificationBuilder.replaceNode(mutableNeedle);
-        dumpResult();
-    }
-
-}
diff --git a/yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/NodeUtilsTest.java b/yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/NodeUtilsTest.java
deleted file mode 100644 (file)
index 6afd46f..0000000
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import java.io.IOException;
-import java.net.URI;
-import java.util.Date;
-import java.util.Deque;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.w3c.dom.Document;
-
-/**
- * @author michal.rehak
- *
- */
-@Deprecated
-public class NodeUtilsTest {
-
-    private static final Logger LOG = LoggerFactory
-            .getLogger(NodeUtilsTest.class);
-
-    private QName qName;
-    private CompositeNode network;
-
-    private String ns;
-
-
-    /**
-     * @throws Exception
-     */
-    @Before
-    public void setUp() throws Exception {
-        ns = "urn:ietf:params:xml:ns:netconf:base:1.0";
-        qName = QName.create(
-                new URI(ns),
-                new Date(42), "yang-data-impl-mutableTest");
-        network = NodeHelper.buildTestConfigTree(qName);
-    }
-
-    /**
-     * Test method for {@link org.opendaylight.yangtools.yang.data.impl.NodeUtils#buildPath(org.opendaylight.yangtools.yang.data.api.Node)}.
-     * @throws Exception
-     */
-    @Test
-    public void testBuildPath() throws Exception {
-        SimpleNode<?> needle = network.getCompositesByName("topologies").iterator().next()
-                .getCompositesByName("topology").iterator().next()
-                .getSimpleNodesByName("topology-id").iterator().next();
-        String breadCrumbs = NodeUtils.buildPath(needle);
-
-        Assert.assertEquals("network.topologies.topology.topology-id", breadCrumbs);
-    }
-
-    /**
-     * Test method for {@link org.opendaylight.yangtools.yang.data.impl.NodeUtils#buildShadowDomTree(org.opendaylight.yangtools.yang.data.api.CompositeNode)}.
-     * @throws Exception
-     */
-    @Test
-    public void testBuildShadowDomTree() throws Exception {
-        MemoryConsumption mc = new MemoryConsumption();
-        mc.startObserving();
-
-        Document networkShadow = NodeUtils.buildShadowDomTree(network);
-
-        LOG.debug("After dom built: "+mc.finishObserving());
-        NodeHelper.compareXmlTree(networkShadow, "./config02-shadow.xml", getClass());
-    }
-
-    /**
-     * Test method for {@link org.opendaylight.yangtools.yang.data.impl.NodeUtils#findNodeByXpath(org.w3c.dom.Document, java.lang.String)}.
-     * @throws Exception
-     */
-    @Test
-    public void testFindNodeByXpath() throws Exception {
-        Document networkShadow = NodeUtils.buildShadowDomTree(network);
-        MemoryConsumption mc = new MemoryConsumption();
-        mc.startObserving();
-
-        SimpleNode<String> needle = NodeUtils.findNodeByXpath(networkShadow,
-                NodeHelper.AddNamespaceToPattern(
-                        "//{0}node[{0}node-id='nodeId_19']//{0}termination-point[2]/{0}tp-id", ns));
-
-        LOG.debug("After xpath executed: "+mc.finishObserving());
-
-        Assert.assertNotNull(needle);
-        Assert.assertEquals("tpId_18", needle.getValue());
-    }
-
-    /**
-     * Test method for {@link org.opendaylight.yangtools.yang.data.impl.NodeUtils#buildNodeMap(java.util.List)}.
-     */
-    @Test
-    public void testBuildNodeMap() {
-        CompositeNode topology = network.getCompositesByName("topologies").iterator().next()
-                .getCompositesByName("topology").iterator().next();
-
-        Map<QName, List<Node<?>>> nodeMap = NodeUtils.buildNodeMap(topology.getValue());
-        Assert.assertEquals(3, nodeMap.size());
-    }
-
-    /**
-     * Test method for {@link org.opendaylight.yangtools.yang.data.impl.NodeUtils#buildMapOfListNodes(org.opendaylight.yangtools.yang.model.api.SchemaContext)}.
-     */
-    @Test
-    public void testBuildMapOfListNodes() {
-        SchemaContext schemaCtx = NodeHelper.loadSchemaContext();
-        Map<String, ListSchemaNode> mapOfLists = NodeUtils.buildMapOfListNodes(schemaCtx);
-        Assert.assertEquals(5, mapOfLists.size());
-    }
-
-    /**
-     * Test method for {@link org.opendaylight.yangtools.yang.data.impl.NodeUtils#buildMapOfListNodes(org.opendaylight.yangtools.yang.model.api.SchemaContext)}.
-     * @throws Exception
-     * @throws IOException
-     */
-    @Test
-    public void testLoadConfigByGroovy() throws IOException, Exception {
-        CompositeNode treeRoot = NodeHelper.loadConfigByGroovy("./config02.groovy");
-        Document shadowTree = NodeUtils.buildShadowDomTree(treeRoot);
-        try {
-            checkFamilyBinding(treeRoot);
-        } catch (Exception e) {
-            LOG.error(e.getMessage());
-            throw e;
-        }
-
-        NodeHelper.compareXmlTree(shadowTree, "./config02g-shadow.xml", getClass());
-    }
-
-    private static void checkFamilyBinding(final CompositeNode treeRoot) throws Exception {
-        Deque<CompositeNode> jobQueue = new LinkedList<>();
-        jobQueue.push(treeRoot);
-
-        while (!jobQueue.isEmpty()) {
-            CompositeNode job = jobQueue.pop();
-            for (Node<?> child : job.getValue()) {
-                if (child instanceof CompositeNode) {
-                    jobQueue.push((CompositeNode) child);
-                }
-
-                if (job != child.getParent()) {
-                    throw new Exception("binding mismatch occured: \nPARENT["+job+"]\n CHILD[" + child+"]\n  +->  "+child.getParent());
-                }
-            }
-        }
-    }
-
-}
diff --git a/yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/XmlTreeBuilderTest.java b/yang/yang-data-impl/src/test/java/org/opendaylight/yangtools/yang/data/impl/XmlTreeBuilderTest.java
deleted file mode 100644 (file)
index 0d7445d..0000000
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.impl;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.InputStream;
-import java.net.URI;
-import java.util.List;
-
-import javax.xml.stream.XMLStreamException;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-
-/**
- * The class <code>XmlTreeBuilderTest</code> contains tests for the class
- * {@link <code>XmlTreeBuilder</code>}
- *
- * @author Lukas Sedlak
- */
-public class XmlTreeBuilderTest {
-
-       private InputStream inputStream;
-
-       /**
-        * Perform pre-test initialization
-        *
-        * @throws Exception
-        */
-       @Before
-       public void setUp() throws Exception {
-               final URI inputFile = getClass().getResource("/rpc-getDeviceEquipment.xml").toURI();
-               inputStream = new FileInputStream(new File(inputFile));
-       }
-
-       /**
-        * Run the Node<?> buildDataTree(InputStream) method test
-        */
-       @SuppressWarnings("unchecked")
-       @Test
-       public void testBuildDataTree()
-       {
-               Node<?> rootNode = null;
-               try {
-                       rootNode = XmlTreeBuilder.buildDataTree(inputStream);
-               } catch (XMLStreamException e) {
-                       e.printStackTrace();
-               }
-               assertNotNull(rootNode);
-               assertTrue(rootNode instanceof CompositeNode);
-
-               CompositeNode compRootNode = (CompositeNode)rootNode;
-               assertNotNull(compRootNode.getValue());
-
-               SimpleNode<String> methodName = null;
-               SimpleNode<String> emptyTag = null;
-               CompositeNode params = null;
-               for (final Node<?> childNode : compRootNode.getValue()) {
-                       if (childNode instanceof SimpleNode) {
-                               if ("emptyTag".equals(childNode.getNodeType().getLocalName())) {
-                                       emptyTag = (SimpleNode<String>) childNode;
-                               } else if ("methodName".equals(childNode.getNodeType().getLocalName())) {
-                                       methodName = (SimpleNode<String>) childNode;
-                               }
-
-                       } else if (childNode instanceof CompositeNode) {
-                               params = (CompositeNode) childNode;
-                       }
-               }
-
-               assertNotNull(methodName);
-               assertNotNull(params);
-               assertTrue(emptyTag.getValue().isEmpty());
-               assertEquals(methodName.getValue(), "getDeviceEquipment");
-
-               String deviceId = null;
-               String deviceIP = null;
-               for (final Node<?> param : params.getValue()) {
-                       if (param instanceof CompositeNode) {
-                               final Node<?> valueNode = ((CompositeNode) param).getValue().get(0);
-
-                               assertTrue(valueNode instanceof CompositeNode);
-                               final CompositeNode value = (CompositeNode) valueNode;
-                               final Node<?> stringNode = value.getValue().get(0);
-                               assertTrue(stringNode instanceof SimpleNode);
-
-                               final SimpleNode<String> string = (SimpleNode<String>) stringNode;
-                               if ("DeviceID123".equals(string.getValue())) {
-                                       deviceId = string.getValue();
-                               } else if ("172.23.218.75".equals(string.getValue())) {
-                                       deviceIP = string.getValue();
-                               }
-                       }
-               }
-
-               assertNotNull(deviceId);
-               assertNotNull(deviceIP);
-       }
-
-       @Test
-       public void nodeMapInCompositeNodeTest() {
-           Node<?> rootNode = null;
-            try {
-                    rootNode = XmlTreeBuilder.buildDataTree(inputStream);
-            } catch (XMLStreamException e) {
-                    e.printStackTrace();
-            }
-
-            CompositeNode compRootNode = (CompositeNode)rootNode;
-            List<CompositeNode> params = compRootNode.getCompositesByName("params");
-            assertEquals(1, params.size());
-            List<CompositeNode> compositesByName = params.get(0).getCompositesByName("param");
-            assertEquals(2, compositesByName.size());
-       }
-}
index e93a5704d5d1914810a612d53505f044819af632..4145ea8d79201af817aa385f65efd9fc25f34839 100644 (file)
@@ -8,35 +8,21 @@
 
 package org.opendaylight.yangtools.yang.data.impl.codec.xml;
 
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
 import com.google.common.base.Charsets;
-import com.google.common.base.Optional;
 import com.google.common.collect.Lists;
 import com.google.common.io.ByteSource;
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.io.InputStream;
-import javax.activation.UnsupportedDataTypeException;
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
-import org.custommonkey.xmlunit.XMLUnit;
 import org.junit.Before;
-import org.junit.Test;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-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.parser.impl.YangParserImpl;
 import org.w3c.dom.Document;
-import org.w3c.dom.Element;
 import org.xml.sax.SAXException;
 
 public class XmlDocumentUtilsTest {
@@ -54,7 +40,9 @@ public class XmlDocumentUtilsTest {
 
     public static final String XML_CONTENT = "<input xmlns=\"urn:opendaylight:controller:rpc:test\">\n" +
             "<a>value</a>\n" +
-            "<ref xmlns:ltha=\"urn:opendaylight:controller:rpc:test\">/ltha:cont/ltha:l[ltha:id='id']</ref>\n" +
+            "<ref xmlns:ltha=\"urn:opendaylight:controller:rpc:test\">"+
+            "/ltha:cont/ltha:l[  ltha:id='id/foo/bar'  ]"+
+            "</ref>\n" +
             "</input>";
 
     public static final String RPC_REPLY = "<rpc-reply xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\" message-id=\"m-1\">\n" +
@@ -77,32 +65,6 @@ public class XmlDocumentUtilsTest {
         testRpc = rpcTestModule.getRpcs().iterator().next();
     }
 
-    @Test
-    public void testRpcInputTransform() throws Exception {
-
-        final Document inputDocument = readXmlToDocument(XML_CONTENT);
-        final Element input = inputDocument.getDocumentElement();
-
-        final CompositeNode node = inputXmlToCompositeNode(input);
-        final SimpleNode<?> refParsed = node.getSimpleNodesByName("ref").iterator().next();
-        assertEquals(YangInstanceIdentifier.class, refParsed.getValue().getClass());
-        final Document serializedDocument = inputCompositeNodeToXml(node);
-
-        XMLUnit.compareXML(inputDocument, serializedDocument);
-    }
-
-    @Test
-    public void testRpcReplyToDom() throws Exception {
-        final Document reply = readXmlToDocument(RPC_REPLY);
-        final CompositeNode domNodes = XmlDocumentUtils.rpcReplyToDomNodes(reply, QName.create("urn:opendaylight:controller:rpc:test", "2014-07-28", "test"), schema);
-        assertEquals(1, domNodes.getValue().size());
-        final Node<?> outputNode = domNodes.getValue().get(0);
-        assertTrue(outputNode instanceof CompositeNode);
-        assertEquals(1, ((CompositeNode) outputNode).getValue().size());
-        final Node<?> okNode = ((CompositeNode) outputNode).getValue().get(0);
-        assertEquals("ok", okNode.getNodeType().getLocalName());
-    }
-
     public static Document readXmlToDocument(final String xmlContent) throws SAXException, IOException {
         return readXmlToDocument(new ByteArrayInputStream(xmlContent.getBytes(Charsets.UTF_8)));
     }
@@ -119,14 +81,4 @@ public class XmlDocumentUtilsTest {
         doc.getDocumentElement().normalize();
         return doc;
     }
-
-    public Document inputCompositeNodeToXml(final CompositeNode cNode)
-            throws UnsupportedDataTypeException {
-        return XmlDocumentUtils.toDocument(cNode, testRpc.getInput(), XmlDocumentUtils.defaultValueCodecProvider());
-    }
-
-    public CompositeNode inputXmlToCompositeNode(final Element e) {
-        return (CompositeNode) XmlDocumentUtils.toDomNode(e, Optional.<DataSchemaNode>of(testRpc.getInput()),
-                Optional.of(XmlDocumentUtils.defaultValueCodecProvider()), Optional.of(schema));
-    }
 }
index be321e526508a824e210fb7edebe037e0f9aeea4..817afccc6a6cf1a8dd790b8f74065c3c9dcf320c 100644 (file)
@@ -20,7 +20,6 @@ import java.net.URI;
 import java.net.URISyntaxException;
 import java.util.AbstractMap;
 import java.util.Arrays;
-import java.util.Collections;
 import java.util.Map;
 import javax.xml.stream.XMLOutputFactory;
 import javax.xml.stream.XMLStreamWriter;
@@ -31,8 +30,6 @@ import org.junit.Ignore;
 import org.junit.Test;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.impl.ImmutableCompositeNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
@@ -146,34 +143,6 @@ public class XmlStreamUtilsTest {
         return targetBaseType;
     }
 
-    @Test
-    public void testEmptyNodeWithAttribute() throws Exception {
-        final ByteArrayOutputStream out = new ByteArrayOutputStream();
-        final XMLStreamWriter writer =  XML_OUTPUT_FACTORY.createXMLStreamWriter(out);
-
-        final Map<QName, String> attrs = Maps.newHashMap();
-        attrs.put(QName.create("namespaceAttr", "2012-12-12", "attr1"), "value");
-        final QName qName = QName.create("urn:opendaylight:controller:rpc:test", "2014-07-28", "cont");
-        final ImmutableCompositeNode dataAttributes = ImmutableCompositeNode.create(qName, attrs, Collections.<Node<?>>emptyList());
-        XmlStreamUtils.create(XmlUtils.DEFAULT_XML_CODEC_PROVIDER).writeDocument(writer, dataAttributes);
-
-        writer.close();
-        out.close();
-
-        final String xmlAsString = new String(out.toByteArray());
-
-        // TODO why resulting xml does not have namespace definition ? If sending xml by e.g. netconf the namespace is there but not here in test
-        final String expectedXmlAsString = "<cont xmlns:a=\"namespaceAttr\" a:attr1=\"value\"></cont>";
-
-        XMLUnit.setIgnoreAttributeOrder(true);
-        final Document control = XMLUnit.buildControlDocument(expectedXmlAsString);
-        final Document test = XMLUnit.buildTestDocument(xmlAsString);
-        final Diff diff = XMLUnit.compareXML(control, test);
-
-        final boolean identical = diff.identical();
-        assertTrue("Xml differs: " + diff.toString(), identical);
-    }
-
     private Map<String, String> mapPrefixed(final Iterable<Map.Entry<URI, String>> prefixes) {
         final Map<String, String> mappedPrefixes = Maps.newHashMap();
         for (final Map.Entry<URI, String> prefix : prefixes) {
index c9fbe58e5e6f053d933b7c74f710bcd057478d0a..9c69016e19c4a086dd2496be4523fcf9b0d02b1b 100644 (file)
@@ -12,18 +12,17 @@ import com.google.common.base.Preconditions;
 import com.google.common.collect.Collections2;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
-
 import java.io.InputStream;
 import java.net.URI;
 import java.util.Collections;
 import java.util.List;
 import java.util.Set;
-
 import org.junit.Before;
 import org.junit.Test;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
+import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
@@ -33,7 +32,7 @@ import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContaine
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableChoiceNodeSchemaAwareBuilder;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableMapNodeSchemaAwareBuilder;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
@@ -169,8 +168,8 @@ public class NormalizedDataBuilderTest {
         LeafSchemaNode augumentString1SchemaNode = (LeafSchemaNode) getSchemaNode(schema, "test", "augmentString1");
         LeafSchemaNode augumentString2SchemaNode = (LeafSchemaNode) getSchemaNode(schema, "test", "augmentString2");
 
-        ChoiceNode choice1SchemaNode = (ChoiceNode) getSchemaNode(schema, "test", "choice");
-        org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode choice = ImmutableChoiceNodeSchemaAwareBuilder
+        ChoiceSchemaNode choice1SchemaNode = (ChoiceSchemaNode) getSchemaNode(schema, "test", "choice");
+        ChoiceNode choice = ImmutableChoiceNodeSchemaAwareBuilder
                 .create(choice1SchemaNode)
                 .withChild(Builders.<String> leafBuilder(augumentString1SchemaNode).withValue("case1").build())
                 // This should fail, since child node belongs to different case
@@ -228,8 +227,8 @@ public class NormalizedDataBuilderTest {
             }
             if (dataSchemaNode instanceof DataNodeContainer) {
                 containers.add((DataNodeContainer) dataSchemaNode);
-            } else if (dataSchemaNode instanceof ChoiceNode) {
-                containers.addAll(((ChoiceNode) dataSchemaNode).getCases());
+            } else if (dataSchemaNode instanceof ChoiceSchemaNode) {
+                containers.addAll(((ChoiceSchemaNode) dataSchemaNode).getCases());
             }
         }
 
index 8979339abbb159610674b4fbe7616149f0840b5c..30a9db0fbf55146b7af82b1b8b5f39076a7a5f8b 100644 (file)
@@ -13,7 +13,6 @@ import com.google.common.collect.Collections2;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 import com.google.common.collect.Sets;
-
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.StringWriter;
@@ -27,18 +26,20 @@ import java.util.Date;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-
 import javax.xml.parsers.DocumentBuilder;
 import javax.xml.parsers.DocumentBuilderFactory;
 import javax.xml.parsers.ParserConfigurationException;
+import javax.xml.stream.XMLOutputFactory;
+import javax.xml.stream.XMLStreamException;
+import javax.xml.stream.XMLStreamWriter;
 import javax.xml.transform.OutputKeys;
 import javax.xml.transform.Transformer;
 import javax.xml.transform.TransformerException;
 import javax.xml.transform.TransformerFactory;
 import javax.xml.transform.TransformerFactoryConfigurationError;
+import javax.xml.transform.dom.DOMResult;
 import javax.xml.transform.dom.DOMSource;
 import javax.xml.transform.stream.StreamResult;
-
 import org.custommonkey.xmlunit.Diff;
 import org.custommonkey.xmlunit.XMLUnit;
 import org.junit.Test;
@@ -51,6 +52,10 @@ import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
+import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
+import org.opendaylight.yangtools.yang.data.impl.codec.xml.XMLStreamNormalizedNodeStreamWriter;
 import org.opendaylight.yangtools.yang.data.impl.codec.xml.XmlDocumentUtils;
 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedDataBuilderTest;
@@ -63,6 +68,7 @@ import org.opendaylight.yangtools.yang.data.impl.schema.transform.dom.parser.Dom
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -73,6 +79,7 @@ import org.xml.sax.SAXException;
 @RunWith(Parameterized.class)
 public class NormalizedNodeXmlTranslationTest {
     private static final Logger logger = LoggerFactory.getLogger(NormalizedNodeXmlTranslationTest.class);
+    private final SchemaContext schema;
 
     @Parameterized.Parameters()
     public static Collection<Object[]> data() {
@@ -86,32 +93,31 @@ public class NormalizedNodeXmlTranslationTest {
         });
     }
 
-
     public static final String NAMESPACE = "urn:opendaylight:params:xml:ns:yang:controller:test";
     private static Date revision;
     static {
         try {
             revision = new SimpleDateFormat("yyyy-MM-dd").parse("2014-03-13");
-        } catch (ParseException e) {
+        } catch (final ParseException e) {
             throw new RuntimeException(e);
         }
     }
 
     private static ContainerNode withAttributes() {
-        DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> b = Builders.containerBuilder();
+        final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> b = Builders.containerBuilder();
         b.withNodeIdentifier(getNodeIdentifier("container"));
 
-        CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = Builders.mapBuilder().withNodeIdentifier(
+        final CollectionNodeBuilder<MapEntryNode, MapNode> listBuilder = Builders.mapBuilder().withNodeIdentifier(
                 getNodeIdentifier("list"));
 
-        Map<QName, Object> predicates = Maps.newHashMap();
+        final Map<QName, Object> predicates = Maps.newHashMap();
         predicates.put(getNodeIdentifier("uint32InList").getNodeType(), 3L);
 
-        DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> list1Builder = Builders
+        final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifierWithPredicates, MapEntryNode> list1Builder = Builders
                 .mapEntryBuilder().withNodeIdentifier(
                         new YangInstanceIdentifier.NodeIdentifierWithPredicates(getNodeIdentifier("list").getNodeType(),
                                 predicates));
-        NormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier,Object,LeafNode<Object>> uint32InListBuilder
+        final NormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier,Object,LeafNode<Object>> uint32InListBuilder
         = Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("uint32InList"));
 
         list1Builder.withChild(uint32InListBuilder.withValue(3L).build());
@@ -119,15 +125,15 @@ public class NormalizedNodeXmlTranslationTest {
         listBuilder.withChild(list1Builder.build());
         b.withChild(listBuilder.build());
 
-        NormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier, Object, LeafNode<Object>> booleanBuilder
+        final NormalizedNodeBuilder<YangInstanceIdentifier.NodeIdentifier, Object, LeafNode<Object>> booleanBuilder
         = Builders.leafBuilder().withNodeIdentifier(getNodeIdentifier("boolean"));
         booleanBuilder.withValue(false);
         b.withChild(booleanBuilder.build());
 
-        ListNodeBuilder<Object, LeafSetEntryNode<Object>> leafListBuilder
+        final ListNodeBuilder<Object, LeafSetEntryNode<Object>> leafListBuilder
         = Builders.leafSetBuilder().withNodeIdentifier(getNodeIdentifier("leafList"));
 
-        NormalizedNodeBuilder<YangInstanceIdentifier.NodeWithValue, Object, LeafSetEntryNode<Object>> leafList1Builder
+        final NormalizedNodeBuilder<YangInstanceIdentifier.NodeWithValue, Object, LeafSetEntryNode<Object>> leafList1Builder
         = Builders.leafSetEntryBuilder().withNodeIdentifier(new YangInstanceIdentifier.NodeWithValue(getNodeIdentifier("leafList").getNodeType(), "a"));
 
         leafList1Builder.withValue("a");
@@ -140,7 +146,7 @@ public class NormalizedNodeXmlTranslationTest {
 
     private static ContainerNode augmentChoiceHell() {
 
-        DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> b = Builders.containerBuilder();
+        final DataContainerNodeBuilder<YangInstanceIdentifier.NodeIdentifier, ContainerNode> b = Builders.containerBuilder();
         b.withNodeIdentifier(getNodeIdentifier("container"));
 
         b.withChild(
@@ -190,9 +196,9 @@ public class NormalizedNodeXmlTranslationTest {
     }
 
     public static YangInstanceIdentifier.AugmentationIdentifier getAugmentIdentifier(final String... childNames) {
-        Set<QName> qn = Sets.newHashSet();
+        final Set<QName> qn = Sets.newHashSet();
 
-        for (String childName : childNames) {
+        for (final String childName : childNames) {
             qn.add(getNodeIdentifier(childName).getNodeType());
         }
 
@@ -200,7 +206,7 @@ public class NormalizedNodeXmlTranslationTest {
     }
 
     public NormalizedNodeXmlTranslationTest(final String yangPath, final String xmlPath, final ContainerNode expectedNode) {
-        SchemaContext schema = parseTestSchema(yangPath);
+        schema = parseTestSchema(yangPath);
         this.xmlPath = xmlPath;
         this.containerNode = (ContainerSchemaNode) NormalizedDataBuilderTest.getSchemaNode(schema, "test", "container");
         this.expectedNode = expectedNode;
@@ -212,8 +218,8 @@ public class NormalizedNodeXmlTranslationTest {
 
 
     SchemaContext parseTestSchema(final String... yangPath) {
-        YangParserImpl yangParserImpl = new YangParserImpl();
-        Set<Module> modules = yangParserImpl.parseYangModelsFromStreams(getTestYangs(yangPath));
+        final YangParserImpl yangParserImpl = new YangParserImpl();
+        final Set<Module> modules = yangParserImpl.parseYangModelsFromStreams(getTestYangs(yangPath));
         return yangParserImpl.resolveSchemaContext(modules);
     }
 
@@ -223,7 +229,7 @@ public class NormalizedNodeXmlTranslationTest {
                 new Function<String, InputStream>() {
             @Override
             public InputStream apply(final String input) {
-                InputStream resourceAsStream = NormalizedDataBuilderTest.class.getResourceAsStream(input);
+                final InputStream resourceAsStream = NormalizedDataBuilderTest.class.getResourceAsStream(input);
                 Preconditions.checkNotNull(resourceAsStream, "File %s was null", resourceAsStream);
                 return resourceAsStream;
             }
@@ -232,36 +238,76 @@ public class NormalizedNodeXmlTranslationTest {
 
     @Test
     public void testTranslation() throws Exception {
-        Document doc = loadDocument(xmlPath);
+        final Document doc = loadDocument(xmlPath);
 
-        ContainerNode built =
-                DomToNormalizedNodeParserFactory.getInstance(DomUtils.defaultValueCodecProvider()).getContainerNodeParser().parse(
+        final ContainerNode built =
+                DomToNormalizedNodeParserFactory.getInstance(DomUtils.defaultValueCodecProvider(), schema).getContainerNodeParser().parse(
                         Collections.singletonList(doc.getDocumentElement()), containerNode);
 
         if (expectedNode != null) {
             org.junit.Assert.assertEquals(expectedNode, built);
         }
 
+        System.err.println(built);
         logger.info("{}", built);
 
-        Iterable<Element> els = DomFromNormalizedNodeSerializerFactory.getInstance(XmlDocumentUtils.getDocument(), DomUtils.defaultValueCodecProvider())
-                .getContainerNodeSerializer().serialize(containerNode, built);
-
-        Element el = els.iterator().next();
+        final Element elementNS = XmlDocumentUtils.getDocument().createElementNS(containerNode.getQName().getNamespace().toString(), containerNode.getQName().getLocalName());
+        writeNormalizedNode(built, new DOMResult(elementNS), SchemaPath.create(true), schema);
 
         XMLUnit.setIgnoreWhitespace(true);
         XMLUnit.setIgnoreComments(true);
+        XMLUnit.setIgnoreAttributeOrder(true);
+        XMLUnit.setNormalize(true);
+
 
         System.err.println(toString(doc.getDocumentElement()));
-        System.err.println(toString(el));
+        System.err.println(toString(elementNS));
+
+        final Diff diff = new Diff(XMLUnit.buildControlDocument(toString(doc.getDocumentElement())), XMLUnit.buildTestDocument(toString(elementNS)));
+
+        // FIXME the comparison cannot be performed, since the qualifiers supplied by XMlUnit do not work correctly in this case
+        // We need to implement custom qualifier so that the element ordering does not mess the DIFF
+//        dd.overrideElementQualifier(new MultiLevelElementNameAndTextQualifier(100, true));
+//        assertTrue(dd.toString(), dd.similar());
+    }
+
 
-        boolean diff = new Diff(XMLUnit.buildControlDocument(toString(doc.getDocumentElement())), XMLUnit.buildTestDocument(toString(el))).similar();
+    static final XMLOutputFactory XML_FACTORY;
+    static {
+        XML_FACTORY = XMLOutputFactory.newFactory();
+        XML_FACTORY.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, false);
+    }
+
+    private void writeNormalizedNode(final NormalizedNode<?, ?> normalized, final DOMResult result, final SchemaPath schemaPath, final SchemaContext context)
+            throws IOException, XMLStreamException {
+        NormalizedNodeWriter normalizedNodeWriter = null;
+        NormalizedNodeStreamWriter normalizedNodeStreamWriter = null;
+        XMLStreamWriter writer = null;
+        try {
+            writer = XML_FACTORY.createXMLStreamWriter(result);
+            normalizedNodeStreamWriter = XMLStreamNormalizedNodeStreamWriter.create(writer, context, schemaPath);
+            normalizedNodeWriter = NormalizedNodeWriter.forStreamWriter(normalizedNodeStreamWriter);
+
+            normalizedNodeWriter.write(normalized);
+
+            normalizedNodeWriter.flush();
+        } finally {
+            if(normalizedNodeWriter != null) {
+                normalizedNodeWriter.close();
+            }
+            if(normalizedNodeStreamWriter != null) {
+                normalizedNodeStreamWriter.close();
+            }
+            if(writer != null) {
+                writer.close();
+            }
+        }
     }
 
     private Document loadDocument(final String xmlPath) throws Exception {
-        InputStream resourceAsStream = NormalizedDataBuilderTest.class.getResourceAsStream(xmlPath);
+        final InputStream resourceAsStream = NormalizedDataBuilderTest.class.getResourceAsStream(xmlPath);
 
-        Document currentConfigElement = readXmlToDocument(resourceAsStream);
+        final Document currentConfigElement = readXmlToDocument(resourceAsStream);
         Preconditions.checkNotNull(currentConfigElement);
         return currentConfigElement;
     }
@@ -269,7 +315,7 @@ public class NormalizedNodeXmlTranslationTest {
     private static final DocumentBuilderFactory BUILDERFACTORY;
 
     static {
-        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
         factory.setNamespaceAware(true);
         factory.setCoalescing(true);
         factory.setIgnoringElementContentWhitespace(true);
@@ -278,13 +324,13 @@ public class NormalizedNodeXmlTranslationTest {
     }
 
     private Document readXmlToDocument(final InputStream xmlContent) throws IOException, SAXException {
-        DocumentBuilder dBuilder;
+        final DocumentBuilder dBuilder;
         try {
             dBuilder = BUILDERFACTORY.newDocumentBuilder();
-        } catch (ParserConfigurationException e) {
+        } catch (final ParserConfigurationException e) {
             throw new RuntimeException("Failed to parse XML document", e);
         }
-        Document doc = dBuilder.parse(xmlContent);
+        final Document doc = dBuilder.parse(xmlContent);
 
         doc.getDocumentElement().normalize();
         return doc;
@@ -292,11 +338,11 @@ public class NormalizedNodeXmlTranslationTest {
 
     public static String toString(final Element xml) {
         try {
-            Transformer transformer = TransformerFactory.newInstance().newTransformer();
+            final Transformer transformer = TransformerFactory.newInstance().newTransformer();
             transformer.setOutputProperty(OutputKeys.INDENT, "yes");
 
-            StreamResult result = new StreamResult(new StringWriter());
-            DOMSource source = new DOMSource(xml);
+            final StreamResult result = new StreamResult(new StringWriter());
+            final DOMSource source = new DOMSource(xml);
             transformer.transform(source, result);
 
             return result.getWriter().toString();
index b36531b2ff9a80293d125eb394497e4bb9755af3..8210413230c07186a22887238bfe0e8d13610a6f 100644 (file)
         <containerInList name="inContainer">
             <uint32>32</uint32>
             <uint16>16</uint16>
+            <identityr xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:test">prefix:b</identityr>
+            <anyX xmlns="urn:opendaylight:params:xml:ns:yang:controller:test">direct Value</anyX>
+            <uint16-ref>16</uint16-ref>
+            <instance-id xmlns:prefix="urn:opendaylight:params:xml:ns:yang:controller:test">/prefix:container/prefix:list[prefix:uint32InList="1"]</instance-id>
         </containerInList>
         <stringAugmentedToList>augmentInList</stringAugmentedToList>
         <stringAugmentedToListInCase1>augmentInListCase1</stringAugmentedToListInCase1>
         <containerInList>
             <uint32>32</uint32>
             <uint16>16</uint16>
+            <identityr>b</identityr>
+            <anyX>
+                <container xmlns="randomNamespace" xmlns:pref="prefixed:namespace">
+                    <pref:boolean>true</pref:boolean>
+                    <innerContainer xmlns:p="prefixed:namespace">
+                        <uint16 xmlns:pref2="prefixed:namespace">pref2:44</uint16>
+                    </innerContainer>
+                </container>
+                <container2 xmlns="randomNamespace2"/>
+            </anyX>
         </containerInList>
         <!--<stringAugmentedToListInCase1>augmentInListCase1</stringAugmentedToListInCase1>-->
         <stringAugmentedToListInCase2>augmentInListCase2</stringAugmentedToListInCase2>
     </list>
+    <list>
+        <uint32InList>4</uint32InList>
+        <containerInList>
+            <anyX>
+                <netconf-state xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring">
+                    <schemas>
+                        <schema>
+                            <identifier>module</identifier>
+                            <version>2012-12-12</version>
+                            <format xmlns:x="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring">x:yang</format>
+                        </schema>
+                    </schemas>
+                </netconf-state>
+            </anyX>
+        </containerInList>
+    </list>
     <list>
         <uint32InList>3</uint32InList>
     </list>
index 5f0e5000d13dc205aaf24b3fe1267128f5c5dd2c..29edc670e12f1cd027e6c5160bfdf2afd7d148d8 100644 (file)
@@ -11,6 +11,12 @@ module test {
             "Initial revision";
     }
 
+    identity a {}
+
+    identity b {
+        base "test:a";
+    }
+
     grouping listGroup {
         list list {
             key "uint32InList";
@@ -26,6 +32,24 @@ module test {
                 leaf uint16 {
                     type uint16;
                 }
+
+                leaf identityr {
+                    type identityref {
+                        base "test:a";
+                     }
+                }
+
+                leaf uint16-ref {
+                    type leafref {
+                        path "../uint16";
+                     }
+                }
+
+                leaf instance-id {
+                    type instance-identifier;
+                }
+
+                anyxml anyX;
             }
         }
      }
index fd6b9c6ab183bc1f13ddc5f5715b331fdde67c1f..41af22664daa2e4515963af7a4431f0a94cd1e21 100644 (file)
@@ -23,8 +23,10 @@ import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
 import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
@@ -33,8 +35,8 @@ import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
 abstract class AbstractContainerNodeModification<S, N extends DataContainerNode<?>> implements Modification<S, N> {
 
     @Override
-    public final Optional<N> modify(S schema, Optional<N> actual, Optional<N> modification,
-            OperationStack operationStack) throws DataModificationException {
+    public final Optional<N> modify(final S schema, final Optional<N> actual, final Optional<N> modification,
+            final OperationStack operationStack) throws DataModificationException {
 
         operationStack.enteringNode(modification);
 
@@ -75,8 +77,8 @@ abstract class AbstractContainerNodeModification<S, N extends DataContainerNode<
 
     protected abstract QName getQName(S schema);
 
-    private Optional<N> modifyContainer(S schema, Optional<N> actual, Optional<N> modification,
-            OperationStack operationStack) throws DataModificationException {
+    private Optional<N> modifyContainer(final S schema, final Optional<N> actual, final Optional<N> modification,
+            final OperationStack operationStack) throws DataModificationException {
 
         if (!actual.isPresent()) {
             return modification;
@@ -93,8 +95,8 @@ abstract class AbstractContainerNodeModification<S, N extends DataContainerNode<
         return build(schema, merged);
     }
 
-    private List<? extends DataContainerChild<?, ?>> modifyContainerChildNodes(S schema, OperationStack operationStack,
-            N actual, N modification, Set<YangInstanceIdentifier.PathArgument> toProcess) throws DataModificationException {
+    private List<? extends DataContainerChild<?, ?>> modifyContainerChildNodes(final S schema, final OperationStack operationStack,
+            final N actual, final N modification, final Set<YangInstanceIdentifier.PathArgument> toProcess) throws DataModificationException {
         List<DataContainerChild<?, ?>> result = Lists.newArrayList();
 
         for (YangInstanceIdentifier.PathArgument childToProcessId : toProcess) {
@@ -111,8 +113,8 @@ abstract class AbstractContainerNodeModification<S, N extends DataContainerNode<
         return result;
     }
 
-    private Optional<? extends DataContainerChild<?, ?>> modifyContainerNode(OperationStack operationStack, N actual,
-            N modification, YangInstanceIdentifier.PathArgument childToProcess, Object schemaChild)
+    private Optional<? extends DataContainerChild<?, ?>> modifyContainerNode(final OperationStack operationStack, final N actual,
+            final N modification, final YangInstanceIdentifier.PathArgument childToProcess, final Object schemaChild)
             throws DataModificationException {
 
         Optional<DataContainerChild<?, ?>> storedChildren = actual.getChild(childToProcess);
@@ -121,7 +123,7 @@ abstract class AbstractContainerNodeModification<S, N extends DataContainerNode<
         return NodeDispatcher.dispatchChildModification(schemaChild, storedChildren, modifiedChildren, operationStack);
     }
 
-    private Object findSchema(S schema, YangInstanceIdentifier.PathArgument childToProcessId) {
+    private Object findSchema(final S schema, final YangInstanceIdentifier.PathArgument childToProcessId) {
         if (childToProcessId instanceof YangInstanceIdentifier.AugmentationIdentifier) {
             return findSchemaForAugment(schema, (YangInstanceIdentifier.AugmentationIdentifier) childToProcessId);
         } else {
@@ -133,7 +135,7 @@ abstract class AbstractContainerNodeModification<S, N extends DataContainerNode<
 
     protected abstract Object findSchemaForAugment(S schema, YangInstanceIdentifier.AugmentationIdentifier childToProcessId);
 
-    private Optional<N> build(S schema, List<? extends DataContainerChild<?, ?>> result) {
+    private Optional<N> build(final S schema, final List<? extends DataContainerChild<?, ?>> result) {
         DataContainerNodeBuilder<?, N> b = getBuilder(schema);
 
         // TODO skip empty container nodes ? e.g. if container looses all its child nodes
@@ -149,8 +151,8 @@ abstract class AbstractContainerNodeModification<S, N extends DataContainerNode<
 
     protected abstract DataContainerNodeBuilder<?, N> getBuilder(S schema);
 
-    protected Set<YangInstanceIdentifier.PathArgument> getChildrenToProcess(S schema, Optional<N> actual,
-            Optional<N> modification) throws DataModificationException {
+    protected Set<YangInstanceIdentifier.PathArgument> getChildrenToProcess(final S schema, final Optional<N> actual,
+            final Optional<N> modification) throws DataModificationException {
         Set<YangInstanceIdentifier.PathArgument> qNames = Sets.newLinkedHashSet();
 
         qNames.addAll(getChildQNames(actual));
@@ -158,7 +160,7 @@ abstract class AbstractContainerNodeModification<S, N extends DataContainerNode<
         return qNames;
     }
 
-    private Set<? extends YangInstanceIdentifier.PathArgument> getChildQNames(Optional<N> actual) {
+    private Set<? extends YangInstanceIdentifier.PathArgument> getChildQNames(final Optional<N> actual) {
         Set<YangInstanceIdentifier.PathArgument> qNames = Sets.newLinkedHashSet();
 
         for (DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?> child : actual.get().getValue()) {
@@ -174,12 +176,13 @@ abstract class AbstractContainerNodeModification<S, N extends DataContainerNode<
         private static final LeafSetNodeModification LEAF_SET_NODE_MODIFICATION = new LeafSetNodeModification();
         private static final AugmentationNodeModification AUGMENTATION_NODE_MODIFICATION = new AugmentationNodeModification();
         private static final MapNodeModification MAP_NODE_MODIFICATION = new MapNodeModification();
+        private static final UnkeyedListNodeModification UNKEYED_LIST_NODE_MODIFICATION = new UnkeyedListNodeModification();
         private static final ContainerNodeModification CONTAINER_NODE_MODIFICATION = new ContainerNodeModification();
         private static final ChoiceNodeModification CHOICE_NODE_MODIFICATION = new ChoiceNodeModification();
 
-        static Optional<? extends DataContainerChild<?, ?>> dispatchChildModification(Object schemaChild,
-                Optional<DataContainerChild<?, ?>> actual, Optional<DataContainerChild<?, ?>> modification,
-                OperationStack operations) throws DataModificationException {
+        static Optional<? extends DataContainerChild<?, ?>> dispatchChildModification(final Object schemaChild,
+                final Optional<DataContainerChild<?, ?>> actual, final Optional<DataContainerChild<?, ?>> modification,
+                final OperationStack operations) throws DataModificationException {
 
             if (schemaChild instanceof LeafSchemaNode) {
                 return onLeafNode((LeafSchemaNode) schemaChild, actual, modification, operations);
@@ -190,9 +193,13 @@ abstract class AbstractContainerNodeModification<S, N extends DataContainerNode<
             } else if (schemaChild instanceof AugmentationSchema) {
                 return onAugmentationNode((AugmentationSchema) schemaChild, actual, modification, operations);
             } else if (schemaChild instanceof ListSchemaNode) {
-                return onMapNode((ListSchemaNode) schemaChild, actual, modification, operations);
-            } else if (schemaChild instanceof org.opendaylight.yangtools.yang.model.api.ChoiceNode) {
-                return onChoiceNode((org.opendaylight.yangtools.yang.model.api.ChoiceNode) schemaChild, actual,
+                if (((ListSchemaNode)schemaChild).getKeyDefinition().isEmpty()) {
+                    return onUnkeyedNode((ListSchemaNode) schemaChild, actual, modification, operations);
+                } else {
+                    return onMapNode((ListSchemaNode) schemaChild, actual, modification, operations);
+                }
+            } else if (schemaChild instanceof ChoiceSchemaNode) {
+                return onChoiceNode((ChoiceSchemaNode) schemaChild, actual,
                         modification, operations);
             }
 
@@ -200,9 +207,9 @@ abstract class AbstractContainerNodeModification<S, N extends DataContainerNode<
         }
 
         private static Optional<? extends DataContainerChild<?, ?>> onChoiceNode(
-                org.opendaylight.yangtools.yang.model.api.ChoiceNode schemaChild,
-                Optional<? extends DataContainerChild<?, ?>> actual,
-                Optional<? extends DataContainerChild<?, ?>> modification, OperationStack operations)
+            final ChoiceSchemaNode schemaChild,
+                final Optional<? extends DataContainerChild<?, ?>> actual,
+                final Optional<? extends DataContainerChild<?, ?>> modification, final OperationStack operations)
                 throws DataModificationException {
             checkType(actual, ChoiceNode.class);
             checkType(modification, ChoiceNode.class);
@@ -210,9 +217,9 @@ abstract class AbstractContainerNodeModification<S, N extends DataContainerNode<
                     (Optional<ChoiceNode>) modification, operations);
         }
 
-        private static Optional<? extends DataContainerChild<?, ?>> onMapNode(ListSchemaNode schemaChild,
-                Optional<? extends DataContainerChild<?, ?>> actual,
-                Optional<? extends DataContainerChild<?, ?>> modification, OperationStack operations)
+        private static Optional<? extends DataContainerChild<?, ?>> onMapNode(final ListSchemaNode schemaChild,
+                final Optional<? extends DataContainerChild<?, ?>> actual,
+                final Optional<? extends DataContainerChild<?, ?>> modification, final OperationStack operations)
                 throws DataModificationException {
             checkType(actual, MapNode.class);
             checkType(modification, MapNode.class);
@@ -220,9 +227,19 @@ abstract class AbstractContainerNodeModification<S, N extends DataContainerNode<
                     (Optional<MapNode>) modification, operations);
         }
 
-        private static Optional<? extends DataContainerChild<?, ?>> onAugmentationNode(AugmentationSchema schemaChild,
-                Optional<? extends DataContainerChild<?, ?>> actual,
-                Optional<? extends DataContainerChild<?, ?>> modification, OperationStack operations)
+        private static Optional<? extends DataContainerChild<?, ?>> onUnkeyedNode(final ListSchemaNode schemaChild,
+                final Optional<? extends DataContainerChild<?, ?>> actual,
+                        final Optional<? extends DataContainerChild<?, ?>> modification, final OperationStack operations)
+                                throws DataModificationException {
+            checkType(actual, UnkeyedListNode.class);
+            checkType(modification, UnkeyedListNode.class);
+            return UNKEYED_LIST_NODE_MODIFICATION.modify(schemaChild, (Optional<UnkeyedListNode>) actual,
+                    (Optional<UnkeyedListNode>) modification, operations);
+        }
+
+        private static Optional<? extends DataContainerChild<?, ?>> onAugmentationNode(final AugmentationSchema schemaChild,
+                final Optional<? extends DataContainerChild<?, ?>> actual,
+                final Optional<? extends DataContainerChild<?, ?>> modification, final OperationStack operations)
                 throws DataModificationException {
             checkType(actual, AugmentationNode.class);
             checkType(modification, AugmentationNode.class);
@@ -230,9 +247,9 @@ abstract class AbstractContainerNodeModification<S, N extends DataContainerNode<
                     (Optional<AugmentationNode>) modification, operations);
         }
 
-        private static Optional<? extends DataContainerChild<?, ?>> onLeafSetNode(LeafListSchemaNode schemaChild,
-                Optional<? extends DataContainerChild<?, ?>> actual,
-                Optional<? extends DataContainerChild<?, ?>> modification, OperationStack operations)
+        private static Optional<? extends DataContainerChild<?, ?>> onLeafSetNode(final LeafListSchemaNode schemaChild,
+                final Optional<? extends DataContainerChild<?, ?>> actual,
+                final Optional<? extends DataContainerChild<?, ?>> modification, final OperationStack operations)
                 throws DataModificationException {
             checkType(actual, LeafSetNode.class);
             checkType(modification, LeafSetNode.class);
@@ -240,9 +257,9 @@ abstract class AbstractContainerNodeModification<S, N extends DataContainerNode<
                     (Optional<LeafSetNode<?>>) modification, operations);
         }
 
-        private static Optional<? extends DataContainerChild<?, ?>> onContainerNode(ContainerSchemaNode schemaChild,
-                Optional<? extends DataContainerChild<?, ?>> actual,
-                Optional<? extends DataContainerChild<?, ?>> modification, OperationStack operations)
+        private static Optional<? extends DataContainerChild<?, ?>> onContainerNode(final ContainerSchemaNode schemaChild,
+                final Optional<? extends DataContainerChild<?, ?>> actual,
+                final Optional<? extends DataContainerChild<?, ?>> modification, final OperationStack operations)
                 throws DataModificationException {
             checkType(actual, ContainerNode.class);
             checkType(modification, ContainerNode.class);
@@ -250,9 +267,9 @@ abstract class AbstractContainerNodeModification<S, N extends DataContainerNode<
                     (Optional<ContainerNode>) modification, operations);
         }
 
-        private static Optional<? extends DataContainerChild<?, ?>> onLeafNode(LeafSchemaNode schemaChild,
-                Optional<? extends DataContainerChild<?, ?>> actual,
-                Optional<? extends DataContainerChild<?, ?>> modification, OperationStack operations)
+        private static Optional<? extends DataContainerChild<?, ?>> onLeafNode(final LeafSchemaNode schemaChild,
+                final Optional<? extends DataContainerChild<?, ?>> actual,
+                final Optional<? extends DataContainerChild<?, ?>> modification, final OperationStack operations)
                 throws DataModificationException {
             checkType(actual, LeafNode.class);
             checkType(modification, LeafNode.class);
@@ -260,7 +277,7 @@ abstract class AbstractContainerNodeModification<S, N extends DataContainerNode<
                     (Optional<LeafNode<?>>) modification, operations);
         }
 
-        private static void checkType(Optional<? extends DataContainerChild<?, ?>> actual, Class<?> leafNodeClass) {
+        private static void checkType(final Optional<? extends DataContainerChild<?, ?>> actual, final Class<?> leafNodeClass) {
             if (actual.isPresent()) {
                 Preconditions.checkArgument(leafNodeClass.isAssignableFrom(actual.get().getClass()),
                         "Unexpected node type, should be: %s, but was: %s, for: %s", leafNodeClass, actual.getClass(),
index e4674caaa95a42d705fca62080dfc561d6a3e6a2..a7840ba70480d669e19d9969e3ae9f5e86a27a70 100644 (file)
@@ -12,30 +12,30 @@ import com.google.common.collect.Sets;
 import java.util.Set;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 
-final class ChoiceNodeModification extends
-        AbstractContainerNodeModification<ChoiceNode, org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode> {
+final class ChoiceNodeModification extends AbstractContainerNodeModification<ChoiceSchemaNode, ChoiceNode> {
 
     @Override
-    protected QName getQName(ChoiceNode schema) {
+    protected QName getQName(final ChoiceSchemaNode schema) {
         return schema.getQName();
     }
 
     @Override
-    protected Object findSchemaForChild(ChoiceNode schema, QName nodeType) {
+    protected Object findSchemaForChild(final ChoiceSchemaNode schema, final QName nodeType) {
         return SchemaUtils.findSchemaForChild(schema, nodeType);
     }
 
     @Override
-    protected Set<YangInstanceIdentifier.PathArgument> getChildrenToProcess(ChoiceNode schema,
-            Optional<org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode> actual,
-            Optional<org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode> modification)
+    protected Set<YangInstanceIdentifier.PathArgument> getChildrenToProcess(final ChoiceSchemaNode schema,
+            final Optional<ChoiceNode> actual,
+            final Optional<ChoiceNode> modification)
             throws DataModificationException {
         Set<YangInstanceIdentifier.PathArgument> childrenToProcess = super.getChildrenToProcess(schema, actual,
                 modification);
@@ -84,18 +84,18 @@ final class ChoiceNodeModification extends
         return childrenToProcessFiltered;
     }
 
-    private boolean belongsToCase(ChoiceCaseNode detectedCase, YangInstanceIdentifier.PathArgument childToProcess) {
+    private boolean belongsToCase(final ChoiceCaseNode detectedCase, final YangInstanceIdentifier.PathArgument childToProcess) {
         return detectedCase.getDataChildByName(childToProcess.getNodeType()) != null;
     }
 
     @Override
-    protected Object findSchemaForAugment(ChoiceNode schema, YangInstanceIdentifier.AugmentationIdentifier childToProcessId) {
+    protected Object findSchemaForAugment(final ChoiceSchemaNode schema, final YangInstanceIdentifier.AugmentationIdentifier childToProcessId) {
         return SchemaUtils.findSchemaForAugment(schema, childToProcessId.getPossibleChildNames());
     }
 
     @Override
-    protected DataContainerNodeBuilder<?, org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode> getBuilder(
-            ChoiceNode schema) {
+    protected DataContainerNodeBuilder<?, ChoiceNode> getBuilder(
+            final ChoiceSchemaNode schema) {
         return Builders.choiceBuilder(schema);
     }
 }
index bfbe329c7d40236e177ffad6bcd22d7c6ec53ca2..c8cbe545ce0f57f1522edf5479114966e0d49301 100644 (file)
@@ -8,9 +8,7 @@
 package org.opendaylight.yangtools.yang.data.operations;
 
 import com.google.common.base.Optional;
-
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.Node;
 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
 import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
@@ -41,10 +39,6 @@ public class DataModificationException extends Exception {
             super(String.format("Data missing for node: %s", nodeType), nodeType);
         }
 
-        public DataMissingException(final QName nodeType, final Node<?> modificationNode) {
-            super(String.format("Data missing for node: %s, %s", nodeType, modificationNode), nodeType);
-        }
-
         public DataMissingException(final QName nodeType, final NormalizedNode<?, ?> modificationNode) {
             super(String.format("Data missing for node: %s, %s", nodeType, modificationNode), nodeType);
         }
diff --git a/yang/yang-data-operations/src/main/java/org/opendaylight/yangtools/yang/data/operations/UnkeyedListNodeModification.java b/yang/yang-data-operations/src/main/java/org/opendaylight/yangtools/yang/data/operations/UnkeyedListNodeModification.java
new file mode 100644 (file)
index 0000000..a6c2d61
--- /dev/null
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.operations;
+
+import com.google.common.base.Optional;
+import com.google.common.collect.Lists;
+import java.util.List;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
+import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
+import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.CollectionNodeBuilder;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+public class UnkeyedListNodeModification implements Modification<ListSchemaNode, UnkeyedListNode> {
+
+    public static final MapEntryNodeModification MAP_ENTRY_NODE_MODIFICATION = new MapEntryNodeModification();
+
+    @Override
+    public Optional<UnkeyedListNode> modify(ListSchemaNode schema, Optional<UnkeyedListNode> actual,
+            Optional<UnkeyedListNode> modification, OperationStack operationStack) throws DataModificationException {
+
+        // Merge or None operation on parent, leaving actual if modification not present
+        if (modification.isPresent() == false)
+            return actual;
+
+        List<UnkeyedListEntryNode> resultNodes = Lists.newArrayList();
+        if (actual.isPresent())
+            resultNodes = unkeyedListEntries(actual.get());
+
+        // TODO implement ordering for modification nodes
+
+        for (UnkeyedListEntryNode unkeyedListEntryModification : modification.get().getValue()) {
+
+            operationStack.enteringNode(unkeyedListEntryModification);
+
+            YangInstanceIdentifier.NodeIdentifier entryKey = unkeyedListEntryModification.getIdentifier();
+
+            switch (operationStack.getCurrentOperation()) {
+            case NONE:
+                break;
+            // DataModificationException.DataMissingException.check(schema.getQName(), actual, mapEntryModification);
+            case MERGE:
+            case CREATE: {
+                DataModificationException.DataExistsException.check(schema.getQName(), actual,
+                        unkeyedListEntryModification);
+                resultNodes.add(unkeyedListEntryModification);
+            }
+            case REPLACE: {
+                break;
+            }
+            case DELETE: {
+                // DataModificationException.DataMissingException.check(schema.getQName(), actual,
+                // unkeyedListEntryModification);
+                break;
+            }
+            case REMOVE: {
+                break;
+            }
+            default:
+                throw new UnsupportedOperationException(
+                        String.format("Unable to perform operation: %s on: %s, unknown",
+                                operationStack.getCurrentOperation(), schema));
+            }
+
+            operationStack.exitingNode(unkeyedListEntryModification);
+        }
+        return build(schema, resultNodes);
+    }
+
+    private Optional<UnkeyedListNode> build(ListSchemaNode schema, List<UnkeyedListEntryNode> resultNodes) {
+        if (resultNodes.isEmpty())
+            return Optional.absent();
+
+        CollectionNodeBuilder<UnkeyedListEntryNode, UnkeyedListNode> b = Builders.unkeyedListBuilder();
+        b.withNodeIdentifier(new NodeIdentifier(schema.getQName()));
+
+        for (UnkeyedListEntryNode child : resultNodes) {
+            b.withChild(child);
+        }
+
+        return Optional.of(b.build());
+    }
+
+    private List<UnkeyedListEntryNode> unkeyedListEntries(UnkeyedListNode unkeyedListNode) {
+        List<UnkeyedListEntryNode> unkeyedListEntries = Lists.newArrayList();
+
+        for (UnkeyedListEntryNode unkeyedListEntryNode : unkeyedListNode.getValue()) {
+            unkeyedListEntries.add(unkeyedListEntryNode);
+        }
+
+        return unkeyedListEntries;
+    }
+
+}
index bebee24315bc0cef52fbf13d492e6b71643b4a30..f05db1e5da95e06c6c40afc4acf67d1020467368 100644 (file)
@@ -72,6 +72,7 @@ public class YangDataOperationsTest {
     protected final Optional<ContainerNode> currentConfig;
     protected final Optional<ContainerNode> modification;
     protected final ModifyAction modifyAction;
+    private final SchemaContext schema;
 
     @Parameterized.Parameters()
     public static Collection<Object[]> data() {
@@ -98,7 +99,7 @@ public class YangDataOperationsTest {
     }
 
     public YangDataOperationsTest(final String testDir) throws Exception {
-        SchemaContext schema = parseTestSchema();
+        schema = parseTestSchema();
         containerNode = (ContainerSchemaNode) getSchemaNode(schema, "test", "container");
         this.testDirName = testDir;
 
@@ -177,7 +178,7 @@ public class YangDataOperationsTest {
         Document currentConfigElement = readXmlToDocument(resourceAsStream);
         Preconditions.checkNotNull(currentConfigElement);
 
-        return Optional.of(DomToNormalizedNodeParserFactory.getInstance(DomUtils.defaultValueCodecProvider()).getContainerNodeParser().parse(
+        return Optional.of(DomToNormalizedNodeParserFactory.getInstance(DomUtils.defaultValueCodecProvider(), schema).getContainerNodeParser().parse(
                 Collections.singletonList(currentConfigElement.getDocumentElement()), containerNode));
     }
 
index b86f4400197981a3537efec94f8b1f8ed43f9ca6..85d904a2698534df081c0e47ec91e626edb5d78a 100644 (file)
             <groupId>${project.groupId}</groupId>
             <artifactId>yang-data-api</artifactId>
         </dependency>
+        <dependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>yang-model-api</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>${project.groupId}</groupId>
+            <artifactId>yang-model-util</artifactId>
+        </dependency>
     </dependencies>
 </project>
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AbstractContainerNode.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AbstractContainerNode.java
deleted file mode 100644 (file)
index d97b2fb..0000000
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.util;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
-
-/**
- * @deprecated Use one of the {@link NormalizedNodeContainer} implementation packages.
- */
-@Deprecated
-public abstract class AbstractContainerNode extends AbstractNode<List<Node<?>>> implements CompositeNode {
-
-    @Override
-    public SimpleNode<?> getFirstSimpleByName(final QName leaf) {
-        List<SimpleNode<?>> list = getSimpleNodesByName(leaf);
-        if (list.size() == 0) {
-            return null;
-        }
-        return list.get(0);
-    }
-
-    protected AbstractContainerNode(final QName name, final CompositeNode parent) {
-        super(name, parent);
-    }
-
-    public AbstractContainerNode(final QName name) {
-        super(name, null);
-    }
-
-    @Override
-    public List<Node<?>> getChildren() {
-        return getValue();
-    }
-
-    @Override
-    public List<Node<?>> getValue() {
-        Map<QName, List<Node<?>>> map = getNodeMap();
-        if (map == null) {
-            throw new IllegalStateException("nodeMap should not be null");
-        }
-        List<Node<?>> ret = new ArrayList<Node<?>>();
-        Collection<List<Node<?>>> values = map.values();
-        for (List<Node<?>> list : values) {
-            ret.addAll(list);
-        }
-        return ret;
-    }
-
-    protected abstract Map<QName, List<Node<?>>> getNodeMap();
-
-    @Override
-    public List<CompositeNode> getCompositesByName(final QName children) {
-        Map<QName, List<Node<?>>> map = getNodeMap();
-        if (map == null) {
-            throw new IllegalStateException("nodeMap should not be null");
-        }
-        List<Node<?>> toFilter = map.get(children);
-        List<CompositeNode> list = new ArrayList<CompositeNode>();
-        for (Node<?> node : toFilter) {
-            if (node instanceof CompositeNode) {
-                list.add((CompositeNode) node);
-            }
-        }
-        return list;
-    }
-
-    @Override
-    public List<SimpleNode<?>> getSimpleNodesByName(final QName children) {
-        Map<QName, List<Node<?>>> map = getNodeMap();
-        if (map == null) {
-            throw new IllegalStateException("nodeMap should not be null");
-        }
-        List<Node<?>> toFilter = map.get(children);
-        List<SimpleNode<?>> list = new ArrayList<SimpleNode<?>>();
-
-        for (Node<?> node : toFilter) {
-            if (node instanceof SimpleNode<?>) {
-                list.add((SimpleNode<?>) node);
-            }
-        }
-        return list;
-    }
-
-    @Override
-    public CompositeNode getFirstCompositeByName(final QName container) {
-        List<CompositeNode> list = getCompositesByName(container);
-        if (list.size() == 0) {
-            return null;
-        }
-        return list.get(0);
-    }
-
-    public SimpleNode<?> getFirstLeafByName(final QName leaf) {
-        List<SimpleNode<?>> list = getSimpleNodesByName(leaf);
-        if (list.size() == 0) {
-            return null;
-        }
-        return list.get(0);
-    }
-
-    @Override
-    public List<CompositeNode> getCompositesByName(final String children) {
-        return getCompositesByName(localQName(children));
-    }
-
-    @Override
-    public List<SimpleNode<?>> getSimpleNodesByName(final String children) {
-        return getSimpleNodesByName(localQName(children));
-    }
-
-    private QName localQName(final String str) {
-        return QName.create(getNodeType(), str);
-    }
-}
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AbstractInteriorContextNode.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AbstractInteriorContextNode.java
new file mode 100644 (file)
index 0000000..0ec3baf
--- /dev/null
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+
+abstract class AbstractInteriorContextNode<T extends PathArgument> extends
+        DataSchemaContextNode<T> {
+
+    protected AbstractInteriorContextNode(final T identifier, final DataSchemaNode schema) {
+        super(identifier, schema);
+    }
+
+    @Override
+    public boolean isLeaf() {
+        return false;
+    }
+
+}
\ No newline at end of file
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AbstractLeafNodeContext.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AbstractLeafNodeContext.java
new file mode 100644 (file)
index 0000000..84e8a97
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+
+abstract class AbstractLeafNodeContext<T extends PathArgument> extends DataSchemaContextNode<T> {
+
+    protected AbstractLeafNodeContext(final T identifier, final DataSchemaNode potential) {
+        super(identifier, potential);
+    }
+
+    @Override
+    public DataSchemaContextNode<?> getChild(final PathArgument child) {
+        return null;
+    }
+
+    @Override
+    public DataSchemaContextNode<?> getChild(final QName child) {
+        return null;
+    }
+
+    @Override
+    public boolean isLeaf() {
+        return true;
+    }
+
+}
\ No newline at end of file
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AbstractMixinContextNode.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AbstractMixinContextNode.java
new file mode 100644 (file)
index 0000000..3806612
--- /dev/null
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+
+abstract class AbstractMixinContextNode<T extends PathArgument> extends
+        AbstractInteriorContextNode<T> {
+
+    protected AbstractMixinContextNode(final T identifier, final DataSchemaNode schema) {
+        super(identifier, schema);
+    }
+
+    @Override
+    public final boolean isMixin() {
+        return true;
+    }
+
+}
\ No newline at end of file
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AbstractNode.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AbstractNode.java
deleted file mode 100644 (file)
index 35a959e..0000000
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.util;
-
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.data.api.CompositeNode;
-import org.opendaylight.yangtools.yang.data.api.ModifyAction;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-/**
- * @deprecated Use one of the {@link NormalizedNode} implementation packages.
- */
-@Deprecated
-public abstract class AbstractNode<T> implements Node<T> {
-
-    private final QName nodeName;
-    private final CompositeNode parent;
-
-    protected AbstractNode(final QName name, final CompositeNode parent) {
-        nodeName = name;
-        this.parent = parent;
-    }
-
-    @Override
-    public QName getNodeType() {
-        return this.nodeName;
-    }
-
-    @Override
-    public CompositeNode getParent() {
-        return parent;
-    }
-
-    /* (non-Javadoc)
-     */
-    /**
-     * @see org.opendaylight.yangtools.yang.data.api.NodeModification#getModificationAction()
-     */
-    public ModifyAction getModificationAction() {
-        // TODO Auto-generated method stub
-        return null;
-    }
-}
index 3e47e966cf94a1f1f6b0e6b485fb922678f02ce0..ef6ac8eb31860a72325d98d7436f82ba291f8e24 100644 (file)
@@ -9,17 +9,10 @@ package org.opendaylight.yangtools.yang.data.util;
 
 import com.google.common.annotations.Beta;
 import com.google.common.base.Preconditions;
-import com.google.common.base.Splitter;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.LinkedHashMap;
-import java.util.List;
 import java.util.Map;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
+import javax.annotation.Nonnull;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
@@ -31,20 +24,21 @@ import org.opendaylight.yangtools.yang.data.api.codec.InstanceIdentifierCodec;
  */
 @Beta
 public abstract class AbstractStringInstanceIdentifierCodec extends AbstractNamespaceCodec implements InstanceIdentifierCodec<String> {
-    private static final Pattern PREDICATE_PATTERN = Pattern.compile("\\[(.*?)\\]");
-    private static final Splitter SLASH_SPLITTER = Splitter.on('/');
 
     @Override
     public final String serialize(final YangInstanceIdentifier data) {
         StringBuilder sb = new StringBuilder();
+        DataSchemaContextNode<?> current = getDataContextTree().getRoot();
         for (PathArgument arg : data.getPathArguments()) {
-            if(arg instanceof AugmentationIdentifier) {
+            current = current.getChild(arg);
+
+            if(current.isMixin()) {
                 /*
                  * XML/YANG instance identifier does not have concept
-                 * of augmentation identifier, which identifies
-                 * mixin (same as paretn element), so we can safely
-                 * ignore it if it is part of path (since child node)
-                 * is identified in same fashion.
+                 * of augmentation identifier, or list as whole which
+                 * identifies mixin (same as paretn element),
+                 * so we can safely ignore it if it is part of path
+                 * (since child node) is identified in same fashion.
                  *
                  */
                 continue;
@@ -67,90 +61,33 @@ public abstract class AbstractStringInstanceIdentifierCodec extends AbstractName
                 sb.append("']");
             }
         }
-
         return sb.toString();
     }
 
+    /**
+     *
+     * Returns DataSchemaContextTree associated with SchemaContext for which
+     * serialization / deserialization occurs.
+     *
+     * Implementations MUST provide non-null Data Tree context, in order
+     * for correct serialization / deserialization of PathArguments,
+     * since XML representation does not have Augmentation arguments
+     * and does not provide path arguments for cases.
+     *
+     * This effectively means same input XPath representation of Path Argument
+     * may result in different YangInstanceIdentifiers if models are different
+     * in uses of choices and cases.
+     *
+     * @return DataSchemaContextTree associated with SchemaContext for which
+     * serialization / deserialization occurs.
+     */
+    protected abstract @Nonnull DataSchemaContextTree getDataContextTree();
+
     @Override
     public final YangInstanceIdentifier deserialize(final String data) {
         Preconditions.checkNotNull(data, "Data may not be null");
-
-        final Iterator<String> xPathParts = SLASH_SPLITTER.split(data).iterator();
-
-        // must be at least "/pr:node"
-        if (!xPathParts.hasNext() || !xPathParts.next().isEmpty() || !xPathParts.hasNext()) {
-            return null;
-        }
-
-        List<PathArgument> result = new ArrayList<>();
-        while (xPathParts.hasNext()) {
-            String xPathPartTrimmed = xPathParts.next().trim();
-
-            PathArgument pathArgument = toPathArgument(xPathPartTrimmed);
-            if (pathArgument != null) {
-                result.add(pathArgument);
-            }
-        }
-        return YangInstanceIdentifier.create(result);
+        XpathStringParsingPathArgumentBuilder builder = new XpathStringParsingPathArgumentBuilder(this, data);
+        return YangInstanceIdentifier.create(builder.build());
     }
 
-    private PathArgument toPathArgument(final String xPathArgument) {
-        final QName mainQName = parseQName(xPathArgument);
-
-        // predicates
-        final Matcher matcher = PREDICATE_PATTERN.matcher(xPathArgument);
-        final Map<QName, Object> predicates = new LinkedHashMap<>();
-        QName currentQName = mainQName;
-
-        while (matcher.find()) {
-            final String predicateStr = matcher.group(1).trim();
-            final int indexOfEqualityMark = predicateStr.indexOf('=');
-            if (indexOfEqualityMark != -1) {
-                final String predicateValue = toPredicateValue(predicateStr.substring(indexOfEqualityMark + 1));
-                if (predicateValue == null) {
-                    return null;
-                }
-
-                if (predicateStr.charAt(0) != '.') {
-                    // target is not a leaf-list
-                    currentQName = parseQName(predicateStr.substring(0, indexOfEqualityMark));
-                    if (currentQName == null) {
-                        return null;
-                    }
-                }
-                predicates.put(currentQName, predicateValue);
-            }
-        }
-
-        if (predicates.isEmpty()) {
-            return new YangInstanceIdentifier.NodeIdentifier(mainQName);
-        } else {
-            return new YangInstanceIdentifier.NodeIdentifierWithPredicates(mainQName, predicates);
-        }
-    }
-
-    private static String toPredicateValue(final String predicatedValue) {
-        final String predicatedValueTrimmed = predicatedValue.trim();
-        if (predicatedValue.isEmpty()) {
-            return null;
-        }
-
-        switch (predicatedValueTrimmed.charAt(0)) {
-        case '"':
-            return trimIfEndIs(predicatedValueTrimmed, '"');
-        case '\'':
-            return trimIfEndIs(predicatedValueTrimmed, '\'');
-        default:
-            return null;
-        }
-    }
-
-    private static String trimIfEndIs(final String str, final char end) {
-        final int l = str.length() - 1;
-        if (str.charAt(l) != end) {
-            return null;
-        }
-
-        return str.substring(1, l);
-    }
 }
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AnyXmlContextNode.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AnyXmlContextNode.java
new file mode 100644 (file)
index 0000000..fa6f64c
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
+
+class AnyXmlContextNode extends DataSchemaContextNode<NodeIdentifier> {
+
+    protected AnyXmlContextNode(final AnyXmlSchemaNode schema) {
+        super(new NodeIdentifier(schema.getQName()), schema);
+    }
+
+    @Override
+    public DataSchemaContextNode<?> getChild(final PathArgument child) {
+        return null;
+    }
+
+    @Override
+    public DataSchemaContextNode<?> getChild(final QName child) {
+        return null;
+    }
+
+    @Override
+    public boolean isLeaf() {
+        return false;
+    }
+
+}
\ No newline at end of file
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AugmentationContextNode.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/AugmentationContextNode.java
new file mode 100644 (file)
index 0000000..a2393ca
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import java.util.Set;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
+import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+
+final class AugmentationContextNode extends
+        DataContainerContextNode<AugmentationIdentifier> {
+
+    public AugmentationContextNode(final AugmentationSchema augmentation, final DataNodeContainer schema) {
+        // super();
+        super(augmentationIdentifierFrom(augmentation), augmentationProxy(augmentation, schema), null);
+    }
+
+    @Override
+    public boolean isMixin() {
+        return true;
+    }
+
+    @Override
+    protected DataSchemaContextNode<?> fromLocalSchemaAndQName(final DataNodeContainer schema, final QName child) {
+        DataSchemaNode result = findChildSchemaNode(schema, child);
+        // We try to look up if this node was added by augmentation
+        if ((schema instanceof DataSchemaNode) && result.isAugmenting()) {
+            return fromAugmentation(schema, (AugmentationTarget) schema, result);
+        }
+        return fromDataSchemaNode(result);
+    }
+
+    @Override
+    protected Set<QName> getQNameIdentifiers() {
+        return getIdentifier().getPossibleChildNames();
+    }
+
+}
\ No newline at end of file
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/ChoiceNodeContextNode.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/ChoiceNodeContextNode.java
new file mode 100644 (file)
index 0000000..582c50b
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import com.google.common.collect.ImmutableMap;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+
+class ChoiceNodeContextNode extends AbstractMixinContextNode<NodeIdentifier> {
+
+    private final ImmutableMap<QName, DataSchemaContextNode<?>> byQName;
+    private final ImmutableMap<PathArgument, DataSchemaContextNode<?>> byArg;
+
+    protected ChoiceNodeContextNode(final ChoiceSchemaNode schema) {
+        super(new NodeIdentifier(schema.getQName()), schema);
+        ImmutableMap.Builder<QName, DataSchemaContextNode<?>> byQNameBuilder = ImmutableMap.builder();
+        ImmutableMap.Builder<PathArgument, DataSchemaContextNode<?>> byArgBuilder = ImmutableMap.builder();
+
+        for (ChoiceCaseNode caze : schema.getCases()) {
+            for (DataSchemaNode cazeChild : caze.getChildNodes()) {
+                DataSchemaContextNode<?> childOp = fromDataSchemaNode(cazeChild);
+                byArgBuilder.put(childOp.getIdentifier(), childOp);
+                for (QName qname : childOp.getQNameIdentifiers()) {
+                    byQNameBuilder.put(qname, childOp);
+                }
+            }
+        }
+        byQName = byQNameBuilder.build();
+        byArg = byArgBuilder.build();
+    }
+
+    @Override
+    public DataSchemaContextNode<?> getChild(final PathArgument child) {
+        return byArg.get(child);
+    }
+
+    @Override
+    public DataSchemaContextNode<?> getChild(final QName child) {
+        return byQName.get(child);
+    }
+}
\ No newline at end of file
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/ContainerContextNode.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/ContainerContextNode.java
new file mode 100644 (file)
index 0000000..10e49b6
--- /dev/null
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+
+final class ContainerContextNode extends DataContainerContextNode<NodeIdentifier> {
+
+    protected ContainerContextNode(final ContainerSchemaNode schema) {
+        super(new NodeIdentifier(schema.getQName()), schema, schema);
+    }
+
+}
\ No newline at end of file
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/DataContainerContextNode.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/DataContainerContextNode.java
new file mode 100644 (file)
index 0000000..2cbbf1f
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+
+class DataContainerContextNode<T extends PathArgument> extends
+        AbstractInteriorContextNode<T> {
+
+    private final DataNodeContainer schema;
+    private final Map<QName, DataSchemaContextNode<?>> byQName;
+    private final Map<PathArgument, DataSchemaContextNode<?>> byArg;
+
+    protected DataContainerContextNode(final T identifier, final DataNodeContainer schema,
+            final DataSchemaNode node) {
+        super(identifier, node);
+        this.schema = schema;
+        this.byArg = new ConcurrentHashMap<>();
+        this.byQName = new ConcurrentHashMap<>();
+    }
+
+    @Override
+    public DataSchemaContextNode<?> getChild(final PathArgument child) {
+        DataSchemaContextNode<?> potential = byArg.get(child);
+        if (potential != null) {
+            return potential;
+        }
+        potential = fromLocalSchema(child);
+        return register(potential);
+    }
+
+    private DataSchemaContextNode<?> fromLocalSchema(final PathArgument child) {
+        if (child instanceof AugmentationIdentifier) {
+            return fromSchemaAndQNameChecked(schema, ((AugmentationIdentifier) child).getPossibleChildNames()
+                    .iterator().next());
+        }
+        return fromSchemaAndQNameChecked(schema, child.getNodeType());
+    }
+
+    @Override
+    public DataSchemaContextNode<?> getChild(final QName child) {
+        DataSchemaContextNode<?> potential = byQName.get(child);
+        if (potential != null) {
+            return potential;
+        }
+        potential = fromLocalSchemaAndQName(schema, child);
+        return register(potential);
+    }
+
+    protected DataSchemaContextNode<?> fromLocalSchemaAndQName(final DataNodeContainer schema2, final QName child) {
+        return fromSchemaAndQNameChecked(schema2, child);
+    }
+
+    private DataSchemaContextNode<?> register(final DataSchemaContextNode<?> potential) {
+        if (potential != null) {
+            byArg.put(potential.getIdentifier(), potential);
+            for (QName qName : potential.getQNameIdentifiers()) {
+                byQName.put(qName, potential);
+            }
+        }
+        return potential;
+    }
+
+}
\ No newline at end of file
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/DataSchemaContextNode.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/DataSchemaContextNode.java
new file mode 100644 (file)
index 0000000..b777c59
--- /dev/null
@@ -0,0 +1,206 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+
+import com.google.common.collect.FluentIterable;
+import com.google.common.collect.ImmutableSet;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import javax.annotation.Nullable;
+import org.opendaylight.yangtools.concepts.Identifiable;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
+import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.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 org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
+
+/**
+ * Schema derived data providing necessary information for mapping
+ * between {@link org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode}
+ * and serialization format defined in RFC6020, since the mapping
+ * is not one-to-one.
+ *
+ * @param <T> Path Argument type
+ *
+ */
+public abstract class DataSchemaContextNode<T extends PathArgument> implements Identifiable<T> {
+
+    private final T identifier;
+    private final DataSchemaNode dataSchemaNode;
+
+    @Override
+    public T getIdentifier() {
+        return identifier;
+    };
+
+    protected DataSchemaContextNode(final T identifier, final SchemaNode schema) {
+        super();
+        this.identifier = identifier;
+        if (schema instanceof DataSchemaNode) {
+            this.dataSchemaNode = (DataSchemaNode) schema;
+        } else {
+            this.dataSchemaNode = null;
+        }
+    }
+
+    public boolean isMixin() {
+        return false;
+    }
+
+    public boolean isKeyedEntry() {
+        return false;
+    }
+
+    protected Set<QName> getQNameIdentifiers() {
+        return Collections.singleton(identifier.getNodeType());
+    }
+
+    public abstract @Nullable DataSchemaContextNode<?> getChild(final PathArgument child);
+
+    public abstract @Nullable DataSchemaContextNode<?> getChild(QName child);
+
+    public abstract boolean isLeaf();
+
+
+    public @Nullable DataSchemaNode getDataSchemaNode() {
+        return dataSchemaNode;
+    }
+
+    static final DataSchemaNode findChildSchemaNode(final DataNodeContainer parent, final QName child) {
+        DataSchemaNode potential = parent.getDataChildByName(child);
+        if (potential == null) {
+            Iterable<ChoiceSchemaNode> choices = FluentIterable.from(
+                    parent.getChildNodes()).filter(ChoiceSchemaNode.class);
+            potential = findChoice(choices, child);
+        }
+        return potential;
+    }
+
+    static DataSchemaContextNode<?> fromSchemaAndQNameChecked(final DataNodeContainer schema, final QName child) {
+        DataSchemaNode result = findChildSchemaNode(schema, child);
+        // We try to look up if this node was added by augmentation
+        if ((schema instanceof DataSchemaNode) && result.isAugmenting()) {
+            return fromAugmentation(schema, (AugmentationTarget) schema, result);
+        }
+        return fromDataSchemaNode(result);
+    }
+
+    private static ChoiceSchemaNode findChoice(final Iterable<ChoiceSchemaNode> choices, final QName child) {
+        ChoiceSchemaNode foundChoice = null;
+        choiceLoop: for (ChoiceSchemaNode choice : choices) {
+            for (ChoiceCaseNode caze : choice.getCases()) {
+                if (findChildSchemaNode(caze, child) != null) {
+                    foundChoice = choice;
+                    break choiceLoop;
+                }
+            }
+        }
+        return foundChoice;
+    }
+
+    public static AugmentationIdentifier augmentationIdentifierFrom(final AugmentationSchema augmentation) {
+        ImmutableSet.Builder<QName> potentialChildren = ImmutableSet.builder();
+        for (DataSchemaNode child : augmentation.getChildNodes()) {
+            potentialChildren.add(child.getQName());
+        }
+        return new AugmentationIdentifier(potentialChildren.build());
+    }
+
+    static DataNodeContainer augmentationProxy(final AugmentationSchema augmentation,
+            final DataNodeContainer schema) {
+        Set<DataSchemaNode> children = new HashSet<>();
+        for (DataSchemaNode augNode : augmentation.getChildNodes()) {
+            children.add(schema.getDataChildByName(augNode.getQName()));
+        }
+        return new EffectiveAugmentationSchema(augmentation, children);
+    }
+
+    /**
+     * Returns a DataContextNodeOperation for provided child node
+     *
+     * If supplied child is added by Augmentation this operation returns a
+     * DataContextNodeOperation for augmentation, otherwise returns a
+     * DataContextNodeOperation for child as call for
+     * {@link #fromDataSchemaNode(DataSchemaNode)}.
+     *
+     *
+     * @param parent
+     * @param parentAug
+     * @param child
+     * @return
+     */
+    static @Nullable DataSchemaContextNode<?> fromAugmentation(final DataNodeContainer parent,
+            final AugmentationTarget parentAug, final DataSchemaNode child) {
+        AugmentationSchema augmentation = null;
+        for (AugmentationSchema aug : parentAug.getAvailableAugmentations()) {
+            DataSchemaNode potential = aug.getDataChildByName(child.getQName());
+            if (potential != null) {
+                augmentation = aug;
+                break;
+            }
+        }
+        if (augmentation != null) {
+            return new AugmentationContextNode(augmentation, parent);
+        }
+        return fromDataSchemaNode(child);
+    }
+
+    public static @Nullable DataSchemaContextNode<?> fromDataSchemaNode(final DataSchemaNode potential) {
+        if (potential instanceof ContainerSchemaNode) {
+            return new ContainerContextNode((ContainerSchemaNode) potential);
+        } else if (potential instanceof ListSchemaNode) {
+            return fromListSchemaNode((ListSchemaNode) potential);
+        } else if (potential instanceof LeafSchemaNode) {
+            return new LeafContextNode((LeafSchemaNode) potential);
+        } else if (potential instanceof ChoiceSchemaNode) {
+            return new ChoiceNodeContextNode((ChoiceSchemaNode) potential);
+        } else if (potential instanceof LeafListSchemaNode) {
+            return fromLeafListSchemaNode((LeafListSchemaNode) potential);
+        } else if (potential instanceof AnyXmlSchemaNode) {
+            return new AnyXmlContextNode((AnyXmlSchemaNode) potential);
+        }
+        return null;
+    }
+
+    private static DataSchemaContextNode<?> fromListSchemaNode(final ListSchemaNode potential) {
+        List<QName> keyDefinition = potential.getKeyDefinition();
+        if (keyDefinition == null || keyDefinition.isEmpty()) {
+            return new UnkeyedListMixinContextNode(potential);
+        }
+        if (potential.isUserOrdered()) {
+            return new OrderedMapMixinContextNode(potential);
+        }
+        return new UnorderedMapMixinContextNode(potential);
+    }
+
+    private static DataSchemaContextNode<?> fromLeafListSchemaNode(final LeafListSchemaNode potential) {
+        if (potential.isUserOrdered()) {
+            return new OrderedLeafListMixinContextNode(potential);
+        }
+        return new UnorderedLeafListMixinContextNode(potential);
+    }
+
+    public static DataSchemaContextNode<?> from(final SchemaContext ctx) {
+        return new ContainerContextNode(ctx);
+    }
+}
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/DataSchemaContextTree.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/DataSchemaContextTree.java
new file mode 100644 (file)
index 0000000..27224b4
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import com.google.common.cache.CacheBuilder;
+import com.google.common.cache.CacheLoader;
+import com.google.common.cache.LoadingCache;
+import java.util.Iterator;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+
+public class DataSchemaContextTree {
+
+    private static final LoadingCache<SchemaContext, DataSchemaContextTree> TREES = CacheBuilder.newBuilder()
+            .weakKeys()
+            .build(new CacheLoader<SchemaContext, DataSchemaContextTree>() {
+
+                @Override
+                public DataSchemaContextTree load(SchemaContext key) throws Exception {
+                    return new DataSchemaContextTree(key);
+                }
+
+            });
+
+    private final DataSchemaContextNode<?> root;
+
+    private DataSchemaContextTree(final SchemaContext ctx) {
+        root = DataSchemaContextNode.from(ctx);
+    }
+
+
+    public static DataSchemaContextTree from(SchemaContext ctx) {
+        return TREES.getUnchecked(ctx);
+    }
+
+    public DataSchemaContextNode<?> getChild(final YangInstanceIdentifier path) {
+        DataSchemaContextNode<?> currentOp = root;
+        Iterator<PathArgument> arguments = path.getPathArguments().iterator();
+        while (arguments.hasNext()) {
+            currentOp = currentOp.getChild(arguments.next());
+        }
+        return currentOp;
+    }
+
+    public DataSchemaContextNode<?> getRoot() {
+        return root;
+    }
+
+}
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/LeafContextNode.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/LeafContextNode.java
new file mode 100644 (file)
index 0000000..378d235
--- /dev/null
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
+
+final class LeafContextNode extends AbstractLeafNodeContext<NodeIdentifier> {
+
+    protected LeafContextNode(final LeafSchemaNode potential) {
+        super(new NodeIdentifier(potential.getQName()), potential);
+    }
+
+}
\ No newline at end of file
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/LeafListEntryContextNode.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/LeafListEntryContextNode.java
new file mode 100644 (file)
index 0000000..c8dd12c
--- /dev/null
@@ -0,0 +1,23 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+
+final class LeafListEntryContextNode extends AbstractLeafNodeContext<NodeWithValue> {
+
+    public LeafListEntryContextNode(final LeafListSchemaNode potential) {
+        super(new NodeWithValue(potential.getQName(), null), potential);
+    }
+
+    @Override
+    public boolean isKeyedEntry() {
+        return true;
+    }
+}
\ No newline at end of file
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/ListItemContextNode.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/ListItemContextNode.java
new file mode 100644 (file)
index 0000000..3465f56
--- /dev/null
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+final class ListItemContextNode extends
+        DataContainerContextNode<NodeIdentifierWithPredicates> {
+
+
+    protected ListItemContextNode(final NodeIdentifierWithPredicates identifier, final ListSchemaNode schema) {
+        super(identifier, schema, schema);
+    }
+
+    @Override
+    public boolean isKeyedEntry() {
+        return true;
+    }
+}
\ No newline at end of file
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/Nodes.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/Nodes.java
deleted file mode 100644 (file)
index c264473..0000000
+++ /dev/null
@@ -1,211 +0,0 @@
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others.  All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.yangtools.yang.data.util;
-
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.HashMap;
-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.MutableCompositeNode;
-import org.opendaylight.yangtools.yang.data.api.MutableSimpleNode;
-import org.opendaylight.yangtools.yang.data.api.Node;
-import org.opendaylight.yangtools.yang.data.api.SimpleNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-/**
- * @deprecated Use one of the {@link NormalizedNode} implementation packages.
- */
-@Deprecated
-public final class Nodes {
-
-    private Nodes() {
-    }
-
-    public static <T> SimpleNode<T> leafNode(final QName name, final T value) {
-        return new SimpleNodeTO<T>(name, value, null);
-    }
-
-    public static CompositeNode containerNode(final QName name, final List<Node<?>> children) {
-        return containerNode(name, children, null);
-    }
-
-    public static CompositeNode containerNode(final QName name, final List<Node<?>> children, final CompositeNode parent) {
-        return new ContainerNodeTO(name, parent, nodeMapFromList(children));
-    }
-
-    public static Map<QName, List<Node<?>>> nodeMapFromList(final List<Node<?>> children) {
-        Map<QName, List<Node<?>>> map = new HashMap<QName, List<Node<?>>>();
-        for (Node<?> node : children) {
-
-            QName name = node.getNodeType();
-            List<Node<?>> targetList = map.get(name);
-            if (targetList == null) {
-                targetList = new ArrayList<Node<?>>();
-                map.put(name, targetList);
-            }
-            targetList.add(node);
-        }
-        return map;
-    }
-
-    /**
-     * @deprecated Use one of the {@link NormalizedNode} implementation packages.
-     */
-    @Deprecated
-    private static class ContainerNodeTO extends AbstractContainerNode {
-
-        private final Map<QName, List<Node<?>>> nodeMap;
-
-        public ContainerNodeTO(final QName name, final Map<QName, List<Node<?>>> nodeMap) {
-            super(name);
-            this.nodeMap = nodeMap;
-        }
-
-        public ContainerNodeTO(final QName name, final CompositeNode parent, final Map<QName, List<Node<?>>> nodeMap) {
-            super(name, parent);
-            this.nodeMap = nodeMap;
-        }
-
-        @Override
-        protected Map<QName, List<Node<?>>> getNodeMap() {
-
-            return nodeMap;
-        }
-
-        /*
-         * (non-Javadoc)
-         *
-         * @see
-         * org.opendaylight.yangtools.yang.data.api.CompositeNode#asMutable()
-         */
-        @Override
-        public MutableCompositeNode asMutable() {
-            // TODO Auto-generated method stub
-            return null;
-        }
-
-        @Override
-        public QName getKey() {
-            return getNodeType();
-        }
-
-        @Override
-        public List<Node<?>> setValue(final List<Node<?>> value) {
-            return null;
-        }
-
-        @Override
-        public int size() {
-            return nodeMap.size();
-        }
-
-        @Override
-        public boolean isEmpty() {
-            return nodeMap.isEmpty();
-        }
-
-        @Override
-        public boolean containsKey(final Object key) {
-            return nodeMap.containsKey(key);
-        }
-
-        @Override
-        public boolean containsValue(final Object value) {
-            return nodeMap.containsValue(value);
-        }
-
-        @Override
-        public List<Node<?>> get(final Object key) {
-            return nodeMap.get(key);
-        }
-
-        @Override
-        public List<Node<?>> put(final QName key, final List<Node<?>> value) {
-            return nodeMap.put(key, value);
-        }
-
-        @Override
-        public List<Node<?>> remove(final Object key) {
-            return nodeMap.remove(key);
-        }
-
-        @Override
-        public void putAll(final Map<? extends QName, ? extends List<Node<?>>> m) {
-            nodeMap.putAll(m);
-        }
-
-        @Override
-        public void clear() {
-            nodeMap.clear();
-        }
-
-        @Override
-        public Set<QName> keySet() {
-            return nodeMap.keySet();
-        }
-
-        @Override
-        public Collection<List<Node<?>>> values() {
-            return nodeMap.values();
-        }
-
-        @Override
-        public Set<java.util.Map.Entry<QName, List<Node<?>>>> entrySet() {
-
-            return nodeMap.entrySet();
-        }
-
-    }
-
-    /**
-     * @deprecated Use one of the {@link NormalizedNode} implementation packages.
-     */
-    @Deprecated
-    private static class SimpleNodeTO<T> extends AbstractNode<T> implements SimpleNode<T> {
-
-        private final T value;
-
-        protected SimpleNodeTO(final QName name, final T val, final CompositeNode parent) {
-            super(name, parent);
-            value = val;
-
-        }
-
-        @Override
-        public T getValue() {
-            return value;
-        }
-
-        /*
-         * (non-Javadoc)
-         *
-         * @see org.opendaylight.yangtools.yang.data.api.SimpleNode#asMutable()
-         */
-        @Override
-        public MutableSimpleNode<T> asMutable() {
-            // TODO Auto-generated method stub
-            return null;
-        }
-
-        @Override
-        public T setValue(final T value) {
-            return null;
-        }
-
-        @Override
-        public QName getKey() {
-            return getNodeType();
-        }
-    }
-
-}
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/OrderedLeafListMixinContextNode.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/OrderedLeafListMixinContextNode.java
new file mode 100644 (file)
index 0000000..31143ae
--- /dev/null
@@ -0,0 +1,17 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+
+final class OrderedLeafListMixinContextNode extends UnorderedLeafListMixinContextNode {
+
+    public OrderedLeafListMixinContextNode(final LeafListSchemaNode potential) {
+        super(potential);
+    }
+}
\ No newline at end of file
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/OrderedMapMixinContextNode.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/OrderedMapMixinContextNode.java
new file mode 100644 (file)
index 0000000..81eeb90
--- /dev/null
@@ -0,0 +1,18 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+final class OrderedMapMixinContextNode extends UnorderedMapMixinContextNode {
+
+    public OrderedMapMixinContextNode(final ListSchemaNode list) {
+        super(list);
+    }
+
+}
\ No newline at end of file
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/UnkeyedListItemContextNode.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/UnkeyedListItemContextNode.java
new file mode 100644 (file)
index 0000000..cbf773d
--- /dev/null
@@ -0,0 +1,19 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+final class UnkeyedListItemContextNode extends DataContainerContextNode<NodeIdentifier> {
+
+    protected UnkeyedListItemContextNode(final ListSchemaNode schema) {
+        super(new NodeIdentifier(schema.getQName()), schema, schema);
+    }
+
+}
\ No newline at end of file
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/UnkeyedListMixinContextNode.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/UnkeyedListMixinContextNode.java
new file mode 100644 (file)
index 0000000..6a5a443
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+class UnkeyedListMixinContextNode extends AbstractMixinContextNode<NodeIdentifier> {
+
+    private final UnkeyedListItemContextNode innerNode;
+
+    public UnkeyedListMixinContextNode(final ListSchemaNode list) {
+        super(new NodeIdentifier(list.getQName()), list);
+        this.innerNode = new UnkeyedListItemContextNode(list);
+    }
+
+    @Override
+    public DataSchemaContextNode<?> getChild(final PathArgument child) {
+        if (child.getNodeType().equals(getIdentifier().getNodeType())) {
+            return innerNode;
+        }
+        return null;
+    }
+
+    @Override
+    public DataSchemaContextNode<?> getChild(final QName child) {
+        if (getIdentifier().getNodeType().equals(child)) {
+            return innerNode;
+        }
+        return null;
+    }
+
+}
\ No newline at end of file
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/UnorderedLeafListMixinContextNode.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/UnorderedLeafListMixinContextNode.java
new file mode 100644 (file)
index 0000000..13f77e7
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
+
+class UnorderedLeafListMixinContextNode extends AbstractMixinContextNode<NodeIdentifier> {
+
+    private final DataSchemaContextNode<?> innerOp;
+
+    public UnorderedLeafListMixinContextNode(final LeafListSchemaNode potential) {
+        super(new NodeIdentifier(potential.getQName()), potential);
+        innerOp = new LeafListEntryContextNode(potential);
+    }
+
+    @Override
+    public DataSchemaContextNode<?> getChild(final PathArgument child) {
+        if (child instanceof NodeWithValue) {
+            return innerOp;
+        }
+        return null;
+    }
+
+    @Override
+    public DataSchemaContextNode<?> getChild(final QName child) {
+        if (getIdentifier().getNodeType().equals(child)) {
+            return innerOp;
+        }
+        return null;
+    }
+}
\ No newline at end of file
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/UnorderedMapMixinContextNode.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/UnorderedMapMixinContextNode.java
new file mode 100644 (file)
index 0000000..10a3d0e
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import java.util.Collections;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+
+class UnorderedMapMixinContextNode extends AbstractMixinContextNode<NodeIdentifier> {
+
+    private final ListItemContextNode innerNode;
+
+    public UnorderedMapMixinContextNode(final ListSchemaNode list) {
+        super(new NodeIdentifier(list.getQName()), list);
+        this.innerNode = new ListItemContextNode(new NodeIdentifierWithPredicates(list.getQName(),
+                Collections.<QName, Object> emptyMap()), list);
+    }
+
+    @Override
+    public DataSchemaContextNode<?> getChild(final PathArgument child) {
+        if (child.getNodeType().equals(getIdentifier().getNodeType())) {
+            return innerNode;
+        }
+        return null;
+    }
+
+    @Override
+    public DataSchemaContextNode<?> getChild(final QName child) {
+        if (getIdentifier().getNodeType().equals(child)) {
+            return innerNode;
+        }
+        return null;
+    }
+
+}
\ No newline at end of file
diff --git a/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/XpathStringParsingPathArgumentBuilder.java b/yang/yang-data-util/src/main/java/org/opendaylight/yangtools/yang/data/util/XpathStringParsingPathArgumentBuilder.java
new file mode 100644 (file)
index 0000000..d25f065
--- /dev/null
@@ -0,0 +1,326 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.data.util;
+
+import com.google.common.base.CharMatcher;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import java.util.LinkedList;
+import javax.annotation.Nullable;
+import org.opendaylight.yangtools.concepts.Builder;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
+/**
+ *
+ * Iterator which lazily parses {@link PathArgument} from string representation.
+ *
+ * Note that invocation of {@link #hasNext()} or {@link #next()} may result in
+ * throwing of {@link IllegalArgumentException} if underlying string represenation
+ * is not correctly serialized or does not represent instance identifier valid
+ * for associated schema context.
+ *
+ * In order to obtain {@link Iterable} or {@link java.util.Collection} please use
+ * {@link com.google.common.collect.ImmutableList#copyOf(java.util.Iterator)}
+ * with this Iterator, which will trigger computation of all path arguments.
+ *
+ */
+class XpathStringParsingPathArgumentBuilder implements Builder<Iterable<PathArgument>> {
+
+    /**
+     * Matcher matching WSP YANG ABNF token
+     *
+     */
+    private static final CharMatcher WSP = CharMatcher.anyOf(" \t");
+
+    /**
+     * Matcher matching IDENTIFIER first char token.
+     *
+     */
+    private static final CharMatcher IDENTIFIER_FIRST_CHAR =
+            CharMatcher.inRange('a', 'z')
+            .or(CharMatcher.inRange('A', 'Z'))
+            .or(CharMatcher.is('_')).precomputed();
+    /**
+     *
+     * Matcher matching IDENTIFIER token
+     *
+     */
+    private static final CharMatcher IDENTIFIER =
+            IDENTIFIER_FIRST_CHAR
+            .or(CharMatcher.inRange('0', '9'))
+            .or(CharMatcher.anyOf(".-")).precomputed();
+
+    private static final CharMatcher SQUOTE = CharMatcher.is('\'');
+    private static final CharMatcher DQUOTE = CharMatcher.is('"');
+
+    private static final char SLASH = '/';
+    private static final char COLON = ':';
+    private static final char DOT = '.';
+    private static final char EQUALS = '=';
+    private static final char PRECONDITION_START = '[';
+    private static final char PRECONDITION_END = ']';
+
+    private final AbstractStringInstanceIdentifierCodec codec;
+    private final String data;
+
+    private final LinkedList<PathArgument> product = new LinkedList<>();
+
+    private DataSchemaContextNode<?> current;
+    private int offset;
+
+    XpathStringParsingPathArgumentBuilder(AbstractStringInstanceIdentifierCodec codec, String data) {
+        this.codec = Preconditions.checkNotNull(codec);
+        this.data = Preconditions.checkNotNull(data);
+        this.current = codec.getDataContextTree().getRoot();
+        this.offset = 0;
+    }
+
+
+    @Override
+    public Iterable<PathArgument> build() {
+        while (!allCharactersConsumed()) {
+            product.add(computeNextArgument());
+        }
+        return ImmutableList.copyOf(product);
+    }
+
+    private PathArgument computeNextArgument() {
+        checkValid(SLASH  == currentChar(),"Identifier must start with '/'.");
+        skipCurrentChar();
+
+        QName name = nextQName();
+        if(allCharactersConsumed() || SLASH == currentChar()) {
+            return computeIdentifier(name);
+        } else {
+            checkValid(PRECONDITION_START == currentChar(), "Last element must be identifier, predicate or '/'");
+            return computeIdentifierWithPredicate(name);
+        }
+    }
+
+
+    private DataSchemaContextNode<?> nextContextNode(QName name) {
+        current = current.getChild(name);
+        checkValid(current != null, "%s is not correct schema node identifier.",name);
+        while(current.isMixin()) {
+            product.add(current.getIdentifier());
+            current = current.getChild(name);
+        }
+        return current;
+    }
+
+
+    /**
+     *
+     * Creates path argument with predicates and sets offset
+     * to end of path argument.
+     *
+     * {@code
+     *     predicate = "[" *WSP (predicate-expr / pos) *WSP "]"
+     *     predicate-expr = (node-identifier / ".") *WSP "=" *WSP
+     *          ((DQUOTE string DQUOTE) /
+     *           (SQUOTE string SQUOTE))
+     *     pos = non-negative-integer-value
+     * }
+     *
+     * @param name QName of node, for which predicates are computed.
+     * @return PathArgument representing node selection with predictes
+     */
+    private PathArgument computeIdentifierWithPredicate(QName name) {
+        DataSchemaContextNode<?> currentNode = nextContextNode(name);
+        checkValid(currentNode.isKeyedEntry(), "Entry %s does not allow specifying predicates.", name);
+
+        ImmutableMap.Builder<QName,Object> keyValues = ImmutableMap.builder();
+        while(!allCharactersConsumed() && PRECONDITION_START == currentChar()) {
+            skipCurrentChar();
+            skipWhitespaces();
+            final QName key;
+            if(DOT == currentChar()) {
+                key = null;
+                skipCurrentChar();
+            } else {
+                key = nextQName();
+            }
+            skipWhitespaces();
+            checkCurrentAndSkip(EQUALS, "Precondition must contain '='");
+            skipWhitespaces();
+            final Object value = deserializeValue(key,nextQuotedValue());
+            skipWhitespaces();
+            checkCurrentAndSkip(PRECONDITION_END, "Precondition must ends with ']'");
+
+            // Break-out from method for leaf-list case
+            if(key == null && currentNode.isLeaf()) {
+                checkValid(offset == data.length(), "Leaf argument must be last argument of instance identifier.");
+                return new YangInstanceIdentifier.NodeWithValue(name, value);
+            }
+            keyValues.put(key, value);
+        }
+        return new YangInstanceIdentifier.NodeIdentifierWithPredicates(name, keyValues.build());
+    }
+
+
+    private PathArgument computeIdentifier(QName name) {
+        DataSchemaContextNode<?> currentNode = nextContextNode(name);
+        checkValid(!currentNode.isKeyedEntry(), "Entry %s requires key or value predicate to be present", name);
+        return currentNode.getIdentifier();
+    }
+
+
+    /**
+     *
+     * Returns following QName and sets offset to end of QName.
+     *
+     * @return following QName.
+     */
+    private QName nextQName() {
+        // Consume prefix or identifie
+        final String maybePrefix = nextIdentifier();
+        final String prefix,localName;
+        if(COLON == currentChar()) {
+            // previous token is prefix;
+            prefix = maybePrefix;
+            skipCurrentChar();
+            localName = nextIdentifier();
+        } else {
+            prefix = "";
+            localName = maybePrefix;
+        }
+        return createQName(prefix, localName);
+    }
+
+    /**
+     * Returns true if all characters from input string
+     * were consumed.
+     *
+     * @return true if all characters from input string
+     * were consumed.
+     */
+    private boolean allCharactersConsumed() {
+        return offset == data.length();
+    }
+
+
+    private QName createQName(String prefix, String localName) {
+        return codec.createQName(prefix, localName);
+    }
+
+    /**
+     *
+     * Skips current char if it equals expected otherwise fails parsing.
+     *
+     * @param expected Expected character
+     * @param errorMsg Error message if {@link #currentChar()} does not match expected.
+     */
+    private void checkCurrentAndSkip(char expected, String errorMsg) {
+        checkValid(expected == currentChar(), errorMsg);
+        offset++;
+    }
+
+
+    /**
+     *
+     * Deserializes value for supplied key
+     *
+     * @param key Name of referenced key, If null, referenced leaf is previous encountered item.
+     * @param value Value to be checked and deserialized
+     * @return Object representing value in yang-data-api format.
+     */
+    private Object deserializeValue(@Nullable QName key, String value) {
+        // FIXME: Use codec to deserialize value to correct Java type
+        return value;
+    }
+
+    /**
+     *
+     * Fails parsing if condition is not met.
+     *
+     * In case of error provides pointer to failed instance identifier,
+     * offset on which failure occured with explanation.
+     *
+     * @param condition Fails parsing if {@code condition} is false
+     * @param errorMsg Error message which will be provided to user.
+     * @param attributes
+     */
+    private void checkValid(boolean condition, String errorMsg, Object... attributes) {
+        Preconditions.checkArgument(condition, "Could not parse Instance Identifier '%s'. Offset: %s : Reason: %s",
+                data,
+                offset,
+                String.format(errorMsg, attributes));
+    }
+
+    /**
+     *
+     * Returns following value of quoted literal (without qoutes)
+     * and sets offset after literal.
+     *
+     * @return String literal
+     */
+    private String nextQuotedValue() {
+        char quoteChar = currentChar();
+        checkValidQuotation(quoteChar);
+        skipCurrentChar();
+        int valueStart = offset;
+        int endQoute = data.indexOf(quoteChar, offset);
+        String value = data.substring(valueStart, endQoute);
+        offset = endQoute;
+        skipCurrentChar();
+        return value;
+    }
+
+    /**
+     * Returns character at current offset.
+     *
+     * @return character at current offset.
+     */
+    private char currentChar() {
+        return data.charAt(offset);
+    }
+
+    /**
+     * Increases processing offset by 1
+     */
+    private void skipCurrentChar() {
+        offset++;
+    }
+
+    /**
+     * Skip whitespace characters, sets offset to first following
+     * non-whitespace character.
+     */
+    private void skipWhitespaces() {
+        nextSequenceEnd(WSP);
+    }
+
+    /**
+     * Returns string which matches IDENTIFIER YANG ABNF token
+     * and sets processing offset after end of identifier.
+     *
+     * @return string which matches IDENTIFIER YANG ABNF token
+     */
+    private String nextIdentifier() {
+        int start = offset;
+        checkValid(IDENTIFIER_FIRST_CHAR.matches(currentChar()), "Identifier must start with character from set 'a-zA-Z_'");
+        nextSequenceEnd(IDENTIFIER);
+        return data.substring(start, offset);
+    }
+
+    private void nextSequenceEnd(CharMatcher matcher) {
+        while(!allCharactersConsumed() && matcher.matches(data.charAt(offset))) {
+            offset++;
+        }
+    }
+
+    private void checkValidQuotation(char quoteChar) {
+        checkValid(
+                SQUOTE.matches(quoteChar) || DQUOTE.matches(quoteChar),
+                "Value must be qoute escaped with ''' or '\"'.");
+
+    }
+
+}
index d26ec448ab5178095e851e35ac1f5dd1adf10a46..3c88fe63fc49a502ff1e75ae114b4e658293027f 100644 (file)
         <dependency>
             <groupId>org.apache.maven</groupId>
             <artifactId>maven-plugin-api</artifactId>
+            <scope>provided</scope>
         </dependency>
         <dependency>
             <groupId>org.apache.maven</groupId>
             <artifactId>maven-core</artifactId>
+            <scope>provided</scope>
         </dependency>
         <dependency>
             <groupId>org.sonatype.plexus</groupId>
             <artifactId>plexus-build-api</artifactId>
+            <scope>provided</scope>
         </dependency>
     </dependencies>
 
index a7a611dd71953f57c685489a1c7e786b796b8855..ab9085398894e628fd1c76d2062229c8c9c7d163 100644 (file)
             <artifactId>maven-artifact</artifactId>
             <version>2.0</version>
         </dependency>
-        <dependency>
-            <groupId>com.jcabi</groupId>
-            <artifactId>jcabi-maven-slf4j</artifactId>
-            <version>0.8</version>
-        </dependency>
         <dependency>
             <groupId>${project.groupId}</groupId>
             <artifactId>yang-parser-impl</artifactId>
         </dependency>
     </dependencies>
 
-    <dependencyManagement>
-        <dependencies>
-            <dependency>
-                <groupId>org.sonatype.sisu</groupId>
-                <artifactId>sisu-inject-plexus</artifactId>
-                <version>2.5.0</version>
-            </dependency>
-        </dependencies>
-    </dependencyManagement>
-
     <reporting>
         <plugins>
             <plugin>
index 7d6c9912d86d816453a3e667ad852a54401869cd..b2c16ee6fea49e26326405479c44d9b1282a4fe5 100644 (file)
@@ -7,12 +7,12 @@
  */
 package org.opendaylight.yangtools.yang2sources.plugin;
 
+import com.google.common.annotations.VisibleForTesting;
 import java.io.File;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
 import java.util.Set;
-
 import org.apache.maven.artifact.repository.ArtifactRepository;
 import org.apache.maven.plugin.AbstractMojo;
 import org.apache.maven.plugin.MojoExecutionException;
@@ -27,22 +27,19 @@ import org.apache.maven.repository.RepositorySystem;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
 import org.opendaylight.yangtools.yang2sources.plugin.ConfigArg.CodeGeneratorArg;
-import org.opendaylight.yangtools.yang2sources.spi.CodeGenerator;
-import org.slf4j.impl.StaticLoggerBinder;
+import org.opendaylight.yangtools.yang2sources.spi.BasicCodeGenerator;
 import org.sonatype.plexus.build.incremental.BuildContext;
 
-import com.google.common.annotations.VisibleForTesting;
-
 /**
  * Generate sources from yang files using user provided set of
- * {@link CodeGenerator}s. Steps of this process:
+ * {@link BasicCodeGenerator}s. Steps of this process:
  * <ol>
  * <li>List yang files from {@link #yangFilesRootDir}</li>
  * <li>Process yang files using {@link YangParserImpl}</li>
- * <li>For each {@link CodeGenerator} from {@link #codeGenerators}:
+ * <li>For each {@link BasicCodeGenerator} from {@link #codeGenerators}:
  * <ol>
  * <li>Instantiate using default constructor</li>
- * <li>Call {@link CodeGenerator#generateSources(SchemaContext, File, Set)}</li>
+ * <li>Call {@link BasicCodeGenerator#generateSources(SchemaContext, File, Set)}</li>
  * </ol></li>
  * </ol>
  */
@@ -51,7 +48,7 @@ public final class YangToSourcesMojo extends AbstractMojo {
     public static final String PLUGIN_NAME = "org.opendaylight.yangtools:yang-maven-plugin";
 
     /**
-     * Classes implementing {@link CodeGenerator} interface. An instance will be
+     * Classes implementing {@link BasicCodeGenerator} interface. An instance will be
      * created out of every class using default constructor. Method {@link
      * CodeGenerator#generateSources(SchemaContext, File, Set<String>
      * yangModulesNames)} will be called on every instance.
@@ -94,19 +91,17 @@ public final class YangToSourcesMojo extends AbstractMojo {
     public YangToSourcesMojo() {
     }
 
-    public void setProject(MavenProject project) {
+    public void setProject(final MavenProject project) {
         this.project = project;
     }
 
     @VisibleForTesting
-    YangToSourcesMojo(YangToSourcesProcessor processor) {
+    YangToSourcesMojo(final YangToSourcesProcessor processor) {
         this.yangToSourcesProcessor = processor;
     }
 
     @Override
     public void execute() throws MojoExecutionException, MojoFailureException {
-        StaticLoggerBinder.getSingleton().setMavenLog(this.getLog());
-
         Util.checkClasspath(project, repoSystem, localRepository, remoteRepos, getLog());
 
         if (yangToSourcesProcessor == null) {
@@ -122,7 +117,7 @@ public final class YangToSourcesMojo extends AbstractMojo {
         yangToSourcesProcessor.execute();
     }
 
-    private static List<CodeGeneratorArg> processCodeGenerators(CodeGeneratorArg[] codeGenerators) {
+    private static List<CodeGeneratorArg> processCodeGenerators(final CodeGeneratorArg[] codeGenerators) {
         List<CodeGeneratorArg> codeGeneratorArgs;
         if (codeGenerators == null) {
             codeGeneratorArgs = Collections.emptyList();
@@ -132,7 +127,7 @@ public final class YangToSourcesMojo extends AbstractMojo {
         return codeGeneratorArgs;
     }
 
-    private static File processYangFilesRootDir(String yangFilesRootDir, File baseDir) {
+    private static File processYangFilesRootDir(final String yangFilesRootDir, final File baseDir) {
         File yangFilesRootFile;
         if (yangFilesRootDir == null) {
             yangFilesRootFile = new File(baseDir, "src" + File.separator + "main" + File.separator + "yang");
@@ -147,7 +142,7 @@ public final class YangToSourcesMojo extends AbstractMojo {
         return yangFilesRootFile;
     }
 
-    private static File[] processExcludeFiles(String[] excludeFiles, File baseDir) {
+    private static File[] processExcludeFiles(final String[] excludeFiles, final File baseDir) {
         if (excludeFiles == null) {
             return new File[] {};
         }
index 401c009fd4b4e64bf015cf91fb99e515b8c010c1..3b39e9ff254979c60e18c48c1809445605da1d38 100644 (file)
@@ -7,55 +7,15 @@
  */
 package org.opendaylight.yangtools.yang.model.api;
 
-import java.util.Set;
-
-import org.opendaylight.yangtools.yang.common.QName;
 
 /**
- *
  * The ChoiceNode defines a set of alternatives. It consists of a number of
  * branches defined as ChoiceCaseNode objects.
+ *
+ * @deprecated This interface is deprecated in favor of {@link ChoiceSchemaNode} and
+ *             will be removed in a future release.
  */
-public interface ChoiceNode extends DataSchemaNode, AugmentationTarget {
-
-    /**
-     * Returns cases of choice.
-     *
-     * @return set of ChoiceCaseNode objects defined in this node which
-     *         represents set of arguments of the YANG <code>case</code>
-     *         substatement of the <code>choice</code> statement
-     */
-    Set<ChoiceCaseNode> getCases();
-
-    /**
-     *
-     * Returns the concrete case according to specified Q name.
-     *
-     * @param name
-     *            QName of seeked Choice Case Node
-     * @return child case node of this Choice if child with given name is
-     *         present, <code>null</code> otherwise
-     */
-    ChoiceCaseNode getCaseNodeByName(QName name);
-
-    /**
-     * Returns the concrete case according to specified name.
-     *
-     * @param name
-     *            name of seeked child as String
-     * @return child case node (or local name of case node) of this Choice if
-     *         child with given name is present, <code>null</code> otherwise
-     */
-    ChoiceCaseNode getCaseNodeByName(String name);
-
-    /**
-     *
-     * Returns name of case which is in the choice specified as default
-     *
-     * @return string with the name of case which is specified in the argument
-     *         of the YANG <code>default</code> substatement of
-     *         <code>choice</code> statement.
-     */
-    String getDefaultCase();
+@Deprecated
+public interface ChoiceNode extends ChoiceSchemaNode {
 
 }
diff --git a/yang/yang-model-api/src/main/java/org/opendaylight/yangtools/yang/model/api/ChoiceSchemaNode.java b/yang/yang-model-api/src/main/java/org/opendaylight/yangtools/yang/model/api/ChoiceSchemaNode.java
new file mode 100644 (file)
index 0000000..4c243a9
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.model.api;
+
+import java.util.Set;
+import org.opendaylight.yangtools.yang.common.QName;
+
+/**
+ * A ChoiceSchemaNode defines a set of alternatives. It consists of a number of
+ * branches defined as ChoiceCaseSchemaNode objects.
+ */
+public interface ChoiceSchemaNode extends DataSchemaNode, AugmentationTarget {
+    /**
+     * Returns cases of choice.
+     *
+     * @return set of ChoiceCaseNode objects defined in this node which
+     *         represents set of arguments of the YANG <code>case</code>
+     *         substatement of the <code>choice</code> statement
+     */
+    Set<ChoiceCaseNode> getCases();
+
+    /**
+     *
+     * Returns the concrete case according to specified Q name.
+     *
+     * @param name
+     *            QName of seeked Choice Case Node
+     * @return child case node of this Choice if child with given name is
+     *         present, <code>null</code> otherwise
+     */
+    ChoiceCaseNode getCaseNodeByName(QName name);
+
+    /**
+     * Returns the concrete case according to specified name.
+     *
+     * @param name
+     *            name of seeked child as String
+     * @return child case node (or local name of case node) of this Choice if
+     *         child with given name is present, <code>null</code> otherwise
+     */
+    ChoiceCaseNode getCaseNodeByName(String name);
+
+    /**
+     *
+     * Returns name of case which is in the choice specified as default
+     *
+     * @return string with the name of case which is specified in the argument
+     *         of the YANG <code>default</code> substatement of
+     *         <code>choice</code> statement.
+     */
+    String getDefaultCase();
+
+}
index 58db208f1b26bb6b8d5eb8acf14b197827f84a9c..424c64b081ebff70b0841a2bcba368f2c9c02194 100644 (file)
@@ -54,7 +54,7 @@
  *   <dd>{@link org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode}
  *
  * <dt>choice
- *   <dd>{@link org.opendaylight.yangtools.yang.model.api.ChoiceNode}
+ *   <dd>{@link org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode}
  *
  * <dt>config
  *   <dd>{@link org.opendaylight.yangtools.yang.model.api.DataSchemaNode#isConfiguration()}
index 6ef96bffe983d3de03caf5294d37e9e7d84f3a5f..4e87fa2641fe503656a1a9154a153387f05d918f 100644 (file)
@@ -26,7 +26,7 @@ import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
@@ -222,8 +222,8 @@ class SchemaContextEmitter {
             emitLeafList((LeafListSchemaNode) child);
         } else if (child instanceof ListSchemaNode) {
             emitList((ListSchemaNode) child);
-        } else if (child instanceof ChoiceNode) {
-            emitChoice((ChoiceNode) child);
+        } else if (child instanceof ChoiceSchemaNode) {
+            emitChoice((ChoiceSchemaNode) child);
         } else if (child instanceof AnyXmlSchemaNode) {
             emitAnyxml((AnyXmlSchemaNode) child);
         } else {
@@ -852,7 +852,7 @@ class SchemaContextEmitter {
 
     }
 
-    private void emitChoice(final ChoiceNode choice) {
+    private void emitChoice(final ChoiceSchemaNode choice) {
         writer.startChoiceNode(choice.getQName());
         emitWhen(choice.getConstraints().getWhenCondition());
         // FIXME: BUG-2444: *(ifFeatureNode )
@@ -928,8 +928,8 @@ class SchemaContextEmitter {
             emitRefineLeafListNodes((LeafListSchemaNode) value);
         } else if (value instanceof ListSchemaNode) {
             emitRefineListNodes((ListSchemaNode) value);
-        } else if (value instanceof ChoiceNode) {
-            emitRefineChoiceNodes((ChoiceNode) value);
+        } else if (value instanceof ChoiceSchemaNode) {
+            emitRefineChoiceNodes((ChoiceSchemaNode) value);
         } else if (value instanceof ChoiceCaseNode) {
             emitRefineCaseNodes((ChoiceCaseNode) value);
         } else if (value instanceof ContainerSchemaNode) {
@@ -1023,8 +1023,8 @@ class SchemaContextEmitter {
 
     }
 
-    private void emitRefineChoiceNodes(final ChoiceNode value) {
-        final ChoiceNode original = getOriginalChecked(value);
+    private void emitRefineChoiceNodes(final ChoiceSchemaNode value) {
+        final ChoiceSchemaNode original = getOriginalChecked(value);
 
         // FIXME: BUG-2444: defaultNode //FIXME: BUG-2444: Optional
         if (Objects.deepEquals(original.isConfiguration(), value.isConfiguration())) {
index bbc059d9ee67551a3bddb1e7966e83ab810aff99..8b798b28862a6f5319c1ee6808f9f0dc1400d43f 100644 (file)
@@ -144,8 +144,12 @@ class SingleModuleYinStatementWriter implements StatementTextWriter {
         }
     }
 
-    private boolean isArgumentYinElement(StatementDefinition currentStatement2) {
-        // FIXME: Implement this
+    private boolean isArgumentYinElement(StatementDefinition currentStatement) {
+        if (currentStatement instanceof Rfc6020Mapping) {
+            return ((Rfc6020Mapping) currentStatement).isArgumentYinElement();
+        } else if (currentStatement instanceof ExtensionStatement) {
+            return ((ExtensionStatement) currentStatement).isArgumentYinElement();
+        }
         return false;
     }
 
index 025c11c1e26b3fd53d1f7b99b28be84fcb65f59c..b3fcbed4f0f426530542e0914bd4fe5b5408204e 100644 (file)
@@ -12,9 +12,8 @@ import java.util.Collection;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Set;
-
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
@@ -39,7 +38,7 @@ public class DataNodeIterator implements Iterator<DataSchemaNode> {
     private final DataNodeContainer container;
     private final List<ListSchemaNode> allLists;
     private final List<ContainerSchemaNode> allContainers;
-    private final List<ChoiceNode> allChoices;
+    private final List<ChoiceSchemaNode> allChoices;
     private final List<DataSchemaNode> allChilds;
     private final List<GroupingDefinition> allGroupings;
     private final List<TypeDefinition<?>> allTypedefs;
@@ -83,7 +82,7 @@ public class DataNodeIterator implements Iterator<DataSchemaNode> {
      *
      * @return Returns list all containers present in subtree.
      */
-    public List<ChoiceNode> allChoices() {
+    public List<ChoiceSchemaNode> allChoices() {
         return allChoices;
     }
 
@@ -125,8 +124,8 @@ public class DataNodeIterator implements Iterator<DataSchemaNode> {
                     final ListSchemaNode list = (ListSchemaNode) childNode;
                     allLists.add(list);
                     traverse(list);
-                } else if (childNode instanceof ChoiceNode) {
-                    final ChoiceNode choiceNode = (ChoiceNode) childNode;
+                } else if (childNode instanceof ChoiceSchemaNode) {
+                    final ChoiceSchemaNode choiceNode = (ChoiceSchemaNode) childNode;
                     allChoices.add(choiceNode);
                     final Set<ChoiceCaseNode> cases = choiceNode.getCases();
                     if (cases != null) {
diff --git a/yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/EffectiveAugmentationSchema.java b/yang/yang-model-util/src/main/java/org/opendaylight/yangtools/yang/model/util/EffectiveAugmentationSchema.java
new file mode 100644 (file)
index 0000000..88d356e
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.yangtools.yang.model.util;
+
+import com.google.common.base.Optional;
+import com.google.common.collect.ImmutableMap;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
+import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
+import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.Status;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
+import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.UsesNode;
+
+/**
+ * Proxy for AugmentationSchema. Child node schemas are replaced with actual schemas from parent.
+ *
+ * FIXME: Make this class final, once derived deprecated class is removed.
+ */
+public class EffectiveAugmentationSchema implements AugmentationSchema {
+    private final AugmentationSchema delegate;
+    private final Set<DataSchemaNode> realChildSchemas;
+    private final Map<QName, DataSchemaNode> mappedChildSchemas;
+
+    public EffectiveAugmentationSchema(final AugmentationSchema augmentSchema, final Set<DataSchemaNode> realChildSchemas) {
+        this.delegate = augmentSchema;
+        this.realChildSchemas = realChildSchemas;
+
+        final Map<QName, DataSchemaNode> m = new HashMap<>(realChildSchemas.size());
+        for (DataSchemaNode realChildSchema : realChildSchemas) {
+            m.put(realChildSchema.getQName(), realChildSchema);
+        }
+
+        this.mappedChildSchemas = ImmutableMap.copyOf(m);
+    }
+
+    @Override
+    public RevisionAwareXPath getWhenCondition() {
+        return delegate.getWhenCondition();
+    }
+
+    @Override
+    public String getDescription() {
+        return delegate.getDescription();
+    }
+
+    @Override
+    public String getReference() {
+        return delegate.getReference();
+    }
+
+    @Override
+    public Status getStatus() {
+        return delegate.getStatus();
+    }
+
+    @Override
+    public SchemaPath getTargetPath() {
+        return delegate.getTargetPath();
+    }
+
+    @Override
+    public List<UnknownSchemaNode> getUnknownSchemaNodes() {
+        return delegate.getUnknownSchemaNodes();
+    }
+
+    @Override
+    public Set<TypeDefinition<?>> getTypeDefinitions() {
+        return delegate.getTypeDefinitions();
+    }
+
+    @Override
+    public Set<DataSchemaNode> getChildNodes() {
+        return realChildSchemas;
+    }
+
+    @Override
+    public Set<GroupingDefinition> getGroupings() {
+        return delegate.getGroupings();
+    }
+
+    @Override
+    public DataSchemaNode getDataChildByName(final QName name) {
+        return mappedChildSchemas.get(name);
+    }
+
+    @Override
+    public DataSchemaNode getDataChildByName(final String name) {
+        // Unused
+        throw new UnsupportedOperationException("Unable to retrieve child node by name");
+    }
+
+    @Override
+    public Set<UsesNode> getUses() {
+        return delegate.getUses();
+    }
+
+    @Override
+    public Optional<AugmentationSchema> getOriginalDefinition() {
+        return delegate.getOriginalDefinition();
+    }
+}
index c0ac168135eaa73a52ea9b1dbd02284e663c170c..10abb048d51eb9916ad666a72eb4dc75f92f4ff7 100644 (file)
@@ -20,7 +20,7 @@ import java.util.Set;
 import javax.annotation.Nonnull;
 import javax.annotation.Nullable;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
@@ -388,8 +388,8 @@ public final class SchemaContextUtil {
             }
         }
 
-        if (foundNode == null && parent instanceof ChoiceNode) {
-            foundNode = ((ChoiceNode) parent).getCaseNodeByName(current);
+        if (foundNode == null && parent instanceof ChoiceSchemaNode) {
+            foundNode = ((ChoiceSchemaNode) parent).getCaseNodeByName(current);
             if (foundNode != null && nextPath.iterator().hasNext()) {
                 foundNode = findNodeIn(foundNode, nextPath);
             }
index e9a34d8d8d1a474228255866ce9423279ad7a3c2..d80a93df55de43ff2e8b93237742670e99bc498b 100644 (file)
@@ -12,7 +12,6 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertTrue;
 import static org.mockito.Mockito.doReturn;
 import static org.mockito.Mockito.mock;
-
 import com.google.common.collect.Sets;
 import java.net.URI;
 import java.net.URISyntaxException;
@@ -54,7 +53,7 @@ public class SchemaContextProxyTest {
         revision2 = SimpleDateFormatUtil.getRevisionFormat().parse("2015-01-15");
     }
 
-    private SchemaContext mockSchema(Module... module) {
+    private SchemaContext mockSchema(final Module... module) {
 
         SchemaContext mock = mock(SchemaContext.class);
         doReturn(Sets.newHashSet(module)).when(mock).getModules();
@@ -416,7 +415,7 @@ public class SchemaContextProxyTest {
         assertProxyContext(filteringSchemaContextProxy, moduleConfig, module2, module3, module4);
     }
 
-    private void assertProxyContext(FilteringSchemaContextProxy filteringSchemaContextProxy, Module... expected) {
+    private void assertProxyContext(final FilteringSchemaContextProxy filteringSchemaContextProxy, final Module... expected) {
 
         Set<Module> modSet = Sets.newHashSet();
 
@@ -444,9 +443,9 @@ public class SchemaContextProxyTest {
         }
     }
 
-    private FilteringSchemaContextProxy createProxySchemaCtx(SchemaContext schemaContext, Set<Module> additionalModules, Module... modules) {
+    private FilteringSchemaContextProxy createProxySchemaCtx(final SchemaContext schemaContext, final Set<Module> additionalModules, final Module... modules) {
 
-        Set<Module> modulesSet = new HashSet();
+        Set<Module> modulesSet = new HashSet<>();
 
         if(modules!=null) {
 
@@ -457,7 +456,7 @@ public class SchemaContextProxyTest {
         return new FilteringSchemaContextProxy(schemaContext, createModuleIds(modulesSet) , createModuleIds(additionalModules));
     }
 
-    private Set<ModuleId> createModuleIds(Set<Module> modules) {
+    private Set<ModuleId> createModuleIds(final Set<Module> modules) {
 
         Set<ModuleId> moduleIds = Sets.newHashSet();
 
@@ -472,7 +471,7 @@ public class SchemaContextProxyTest {
         return moduleIds;
     }
 
-    private void mockSubmodules(Module mainModule, Module... submodules){
+    private void mockSubmodules(final Module mainModule, final Module... submodules){
 
         Set<Module> submodulesSet = new HashSet<>();
         submodulesSet.addAll(Arrays.asList(submodules));
@@ -480,7 +479,7 @@ public class SchemaContextProxyTest {
         doReturn(submodulesSet).when(mainModule).getSubmodules();
     }
 
-    private void mockModuleImport(Module importer, Module... imports) {
+    private void mockModuleImport(final Module importer, final Module... imports) {
         Set<ModuleImport> mockedImports = Sets.newHashSet();
         for (final Module module : imports) {
             mockedImports.add(new ModuleImport() {
@@ -510,7 +509,7 @@ public class SchemaContextProxyTest {
     }
 
     //mock module with revision
-    private Module mockModule(String name, final Date rev){
+    private Module mockModule(final String name, final Date rev){
 
         final Module mod = mockModule(name);
 
@@ -522,7 +521,7 @@ public class SchemaContextProxyTest {
     }
 
     //mock module with default revision
-    private Module mockModule(String mName) {
+    private Module mockModule(final String mName) {
 
         Module mockedModule = mock(Module.class);
         doReturn(mName).when(mockedModule).getName();
index 6dc50de20b21b26ba2728d098a8d3c4359f35b75..6115c83b578108ce4dc9e219c481516708a140bc 100644 (file)
             <artifactId>concepts</artifactId>
         </dependency>
         <dependency>
-            <groupId>commons-io</groupId>
-            <artifactId>commons-io</artifactId>
+            <groupId>com.google.code.findbugs</groupId>
+            <artifactId>jsr305</artifactId>
         </dependency>
-      <dependency>
-        <groupId>com.google.code.findbugs</groupId>
-        <artifactId>jsr305</artifactId>
-      </dependency>
     </dependencies>
 
     <build>
index 759e779eed26e29a079b7e37681515022e8a160a..12a1f73d1ac373a82480658aeda022c2051a48e2 100644 (file)
@@ -14,6 +14,7 @@ import com.google.common.base.Splitter;
 import com.google.common.collect.Collections2;
 import com.google.common.collect.Iterables;
 import com.google.common.io.ByteSource;
+import com.google.common.io.ByteStreams;
 import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileNotFoundException;
@@ -32,7 +33,6 @@ import java.util.Map;
 import java.util.Set;
 import java.util.TreeMap;
 import org.antlr.v4.runtime.tree.ParseTree;
-import org.apache.commons.io.IOUtils;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Belongs_to_stmtContext;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Module_header_stmtsContext;
 import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Module_stmtContext;
@@ -43,7 +43,7 @@ import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.Submodule_stmtCont
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
@@ -732,8 +732,8 @@ public final class BuilderUtils {
 
         if (node instanceof AnyXmlSchemaNode) {
             return new AnyXmlBuilder(moduleName, line, qname, schemaPath, ((AnyXmlSchemaNode) node));
-        } else if (node instanceof ChoiceNode) {
-            return new ChoiceBuilder(moduleName, line, qname, schemaPath, ((ChoiceNode) node));
+        } else if (node instanceof ChoiceSchemaNode) {
+            return new ChoiceBuilder(moduleName, line, qname, schemaPath, ((ChoiceSchemaNode) node));
         } else if (node instanceof ContainerSchemaNode) {
             return new ContainerSchemaNodeBuilder(moduleName, line, qname, schemaPath, ((ContainerSchemaNode) node));
         } else if (node instanceof LeafSchemaNode) {
@@ -786,16 +786,16 @@ public final class BuilderUtils {
 
     private static final class ByteSourceImpl extends ByteSource {
         private final String toString;
-        private final ByteArrayOutputStream output = new ByteArrayOutputStream();
+        private final byte[] data;
 
         private ByteSourceImpl(final InputStream input) throws IOException {
             toString = input.toString();
-            IOUtils.copy(input, output);
+            data = ByteStreams.toByteArray(input);
         }
 
         @Override
         public InputStream openStream() throws IOException {
-            return new NamedByteArrayInputStream(output.toByteArray(), toString);
+            return new NamedByteArrayInputStream(data, toString);
         }
     }
 
index 7d67478d6655d532603c911633fb9080542d8d16..0b125f1f81de5411fdd1726dbb09f039c6e9f0c8 100644 (file)
@@ -7,6 +7,9 @@
  */
 package org.opendaylight.yangtools.yang.parser.builder.impl;
 
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableSet;
 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.List;
@@ -15,7 +18,7 @@ import java.util.TreeSet;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.opendaylight.yangtools.yang.parser.builder.api.AugmentationSchemaBuilder;
@@ -27,9 +30,6 @@ import org.opendaylight.yangtools.yang.parser.builder.api.UnknownSchemaNodeBuild
 import org.opendaylight.yangtools.yang.parser.builder.util.AbstractSchemaNodeBuilder;
 import org.opendaylight.yangtools.yang.parser.builder.util.Comparators;
 import org.opendaylight.yangtools.yang.parser.util.YangParseException;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableSet;
 
 public final class ChoiceBuilder extends AbstractSchemaNodeBuilder implements DataSchemaNodeBuilder,
 AugmentationTargetBuilder {
@@ -39,7 +39,7 @@ AugmentationTargetBuilder {
     private boolean augmenting;
     private boolean addedByUses;
     private boolean configuration;
-    private ChoiceNode originalNode;
+    private ChoiceSchemaNode originalNode;
     private ChoiceBuilder originalBuilder;
     private final ConstraintsBuilder constraints;
     // AugmentationTarget args
@@ -56,7 +56,7 @@ AugmentationTargetBuilder {
     }
 
     public ChoiceBuilder(final String moduleName, final int line, final QName qname, final SchemaPath path,
-            final ChoiceNode base) {
+            final ChoiceSchemaNode base) {
         super(moduleName, line, qname);
         this.schemaPath = path;
         constraints = new ConstraintsBuilderImpl(moduleName, line, base.getConstraints());
@@ -83,7 +83,7 @@ AugmentationTargetBuilder {
     }
 
     @Override
-    public ChoiceNode build() {
+    public ChoiceSchemaNode build() {
         if (instance != null) {
             return instance;
         }
index 1b1d3fe689c526f7c1d8b56b5dd0c59cc26c2bd9..a4a3164995ef226ebfa00a80cae26bb3058543ce 100644 (file)
@@ -9,13 +9,15 @@ import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.opendaylight.yangtools.yang.model.api.Status;
 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
 
-final class ChoiceNodeImpl implements ChoiceNode, DerivableSchemaNode {
+// FIXME: BUG-1513: remove ChoiceNode in Beryllium timeframe
+final class ChoiceNodeImpl implements ChoiceNode, ChoiceSchemaNode, DerivableSchemaNode {
     private final QName qname;
     private final SchemaPath path;
     String description;
@@ -23,7 +25,7 @@ final class ChoiceNodeImpl implements ChoiceNode, DerivableSchemaNode {
     Status status;
     boolean augmenting;
     boolean addedByUses;
-    ChoiceNode original;
+    ChoiceSchemaNode original;
     boolean configuration;
     ConstraintDefinition constraints;
     ImmutableSet<ChoiceCaseNode> cases;
@@ -72,7 +74,7 @@ final class ChoiceNodeImpl implements ChoiceNode, DerivableSchemaNode {
     }
 
     @Override
-    public Optional<ChoiceNode> getOriginal() {
+    public Optional<ChoiceSchemaNode> getOriginal() {
         return Optional.fromNullable(original);
     }
 
index aa85be959c313ee999d6e48daeb0104598e77749..7cac743689c5b8f8e51e66525fbe1ac593a06d56 100644 (file)
@@ -6,10 +6,10 @@
  */
 package org.opendaylight.yangtools.yang.parser.builder.impl;
 
+import com.google.common.base.Charsets;
 import com.google.common.base.Preconditions;
 import com.google.common.io.ByteSource;
 import java.io.IOException;
-import java.io.InputStream;
 import java.net.URI;
 import java.util.ArrayList;
 import java.util.Collections;
@@ -23,7 +23,6 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 import java.util.TreeSet;
-import org.apache.commons.io.IOUtils;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.QNameModule;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
@@ -929,9 +928,7 @@ public class ModuleBuilder extends AbstractDocumentedDataNodeContainerBuilder im
     }
 
     public void setSource(final ByteSource byteSource) throws IOException {
-        try (InputStream stream = byteSource.openStream()) {
-            setSource(IOUtils.toString(stream));
-        }
+        setSource(byteSource.asCharSource(Charsets.UTF_8).read());
     }
 
     public void setSource(final String source) {
index 36a43459956e308c1dd67eb10497f2d702b24ba0..3da4263c6b429aee3c0f7ff3aa7a56a6dfb1ef4c 100644 (file)
@@ -59,7 +59,6 @@ final class UsesNodeImpl implements UsesNode {
         return refines;
     }
 
-    @SuppressWarnings("unused")
     public List<UnknownSchemaNode> getUnknownSchemaNodes() {
         return unknownNodes;
     }
index c50aa3344f2cb877493c826bdc68904209ffc5ea..50e54140989a8dafcf066f60caef095f6de2a8fd 100644 (file)
@@ -15,7 +15,6 @@ import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.f
 import static org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils.processAugmentation;
 import static org.opendaylight.yangtools.yang.parser.builder.impl.TypeUtils.resolveType;
 import static org.opendaylight.yangtools.yang.parser.builder.impl.TypeUtils.resolveTypeUnion;
-
 import com.google.common.base.Optional;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.HashBiMap;
@@ -47,7 +46,7 @@ import org.opendaylight.yangtools.antlrv4.code.gen.YangParser.YangContext;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.common.QNameModule;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ExtensionDefinition;
@@ -1262,16 +1261,16 @@ public final class YangParserImpl implements YangContextParser {
             for (Map.Entry<Date, ModuleBuilder> childEntry : entry.getValue().entrySet()) {
                 final ModuleBuilder moduleBuilder = childEntry.getValue();
                 final Module module = moduleBuilder.build();
-                final List<ChoiceNode> allChoicesFromModule = getChoicesFrom(module);
+                final List<ChoiceSchemaNode> allChoicesFromModule = getChoicesFrom(module);
 
-                for (ChoiceNode choiceNode : allChoicesFromModule) {
+                for (ChoiceSchemaNode choiceNode : allChoicesFromModule) {
                     findDuplicityNodesIn(choiceNode, module, moduleBuilder, modules);
                 }
             }
         }
     }
 
-    private void findDuplicityNodesIn(final ChoiceNode choiceNode, final Module module, final ModuleBuilder moduleBuilder,
+    private void findDuplicityNodesIn(final ChoiceSchemaNode choiceNode, final Module module, final ModuleBuilder moduleBuilder,
             final Map<URI, TreeMap<Date, ModuleBuilder>> modules) {
         final Set<QName> duplicityTestSet = new HashSet<QName>();
 
@@ -1293,8 +1292,8 @@ public final class YangParserImpl implements YangContextParser {
         }
     }
 
-    private List<ChoiceNode> getChoicesFrom(final Module module) {
-        final List<ChoiceNode> allChoices = new ArrayList<ChoiceNode>();
+    private List<ChoiceSchemaNode> getChoicesFrom(final Module module) {
+        final List<ChoiceSchemaNode> allChoices = new ArrayList<ChoiceSchemaNode>();
 
         for (DataSchemaNode dataSchemaNode : module.getChildNodes()) {
             findChoicesIn(dataSchemaNode, allChoices);
@@ -1302,7 +1301,7 @@ public final class YangParserImpl implements YangContextParser {
         return allChoices;
     }
 
-    private void findChoicesIn(final SchemaNode schemaNode, final Collection<ChoiceNode> choiceNodes) {
+    private void findChoicesIn(final SchemaNode schemaNode, final Collection<ChoiceSchemaNode> choiceNodes) {
         if (schemaNode instanceof ContainerSchemaNode) {
             final ContainerSchemaNode contSchemaNode = (ContainerSchemaNode) schemaNode;
             for (DataSchemaNode dataSchemaNode : contSchemaNode.getChildNodes()) {
@@ -1313,8 +1312,8 @@ public final class YangParserImpl implements YangContextParser {
             for (DataSchemaNode dataSchemaNode : listSchemaNode.getChildNodes()) {
                 findChoicesIn(dataSchemaNode, choiceNodes);
             }
-        } else if (schemaNode instanceof ChoiceNode) {
-            choiceNodes.add((ChoiceNode) schemaNode);
+        } else if (schemaNode instanceof ChoiceSchemaNode) {
+            choiceNodes.add((ChoiceSchemaNode) schemaNode);
         }
     }
 
index 9d7e599c418d4fe6fdbeafd22d77f3cb7569f163..158dce8cf3361e2517b3b3e570d6640c0cdbcb18 100644 (file)
@@ -8,10 +8,10 @@
 
 package org.opendaylight.yangtools.yang.parser.util;
 
+import com.google.common.io.ByteStreams;
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.io.InputStream;
-import org.apache.commons.io.IOUtils;
 
 public class NamedByteArrayInputStream extends ByteArrayInputStream implements NamedInputStream {
     private final String toString;
@@ -21,11 +21,12 @@ public class NamedByteArrayInputStream extends ByteArrayInputStream implements N
     }
 
     public static ByteArrayInputStream create(InputStream originalIS) throws IOException {
-        String content = IOUtils.toString(originalIS);
+        final byte[] data = ByteStreams.toByteArray(originalIS);
+
         if (originalIS instanceof NamedInputStream) {
-            return new NamedByteArrayInputStream(content.getBytes(), originalIS.toString());
+            return new NamedByteArrayInputStream(data, originalIS.toString());
         } else {
-            return new ByteArrayInputStream(content.getBytes());
+            return new ByteArrayInputStream(data);
         }
     }
 
index e3c2b3cdaa02410740cf9c6f0a327ab5afc5f09b..db1278b48abe3851975d32e4e47026ae1bd28fe3 100644 (file)
@@ -28,7 +28,7 @@ import org.junit.Test;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
@@ -92,7 +92,7 @@ public class AugmentTest {
         LeafSchemaNode ds0ChannelNumber = (LeafSchemaNode) augment.getDataChildByName("ds0ChannelNumber");
         LeafSchemaNode interfaceId = (LeafSchemaNode) augment.getDataChildByName("interface-id");
         ContainerSchemaNode schemas = (ContainerSchemaNode) augment.getDataChildByName("schemas");
-        ChoiceNode odl = (ChoiceNode) augment.getDataChildByName("odl");
+        ChoiceSchemaNode odl = (ChoiceSchemaNode) augment.getDataChildByName("odl");
 
         assertNotNull(ds0ChannelNumber);
         assertNotNull(interfaceId);
@@ -195,7 +195,7 @@ public class AugmentTest {
         LeafSchemaNode ds0ChannelNumber = (LeafSchemaNode) augmentHolder.getDataChildByName("ds0ChannelNumber");
         LeafSchemaNode interfaceId = (LeafSchemaNode) augmentHolder.getDataChildByName("interface-id");
         ContainerSchemaNode schemas = (ContainerSchemaNode) augmentHolder.getDataChildByName("schemas");
-        ChoiceNode odl = (ChoiceNode) augmentHolder.getDataChildByName("odl");
+        ChoiceSchemaNode odl = (ChoiceSchemaNode) augmentHolder.getDataChildByName("odl");
 
         assertNotNull(ds0ChannelNumber);
         assertNotNull(interfaceId);
@@ -242,7 +242,7 @@ public class AugmentTest {
 
         // foo.yang
         // augment "/br:interfaces/br:ifEntry/bz:augment-holder"
-        ChoiceNode odl = (ChoiceNode) augmentedHolder.getDataChildByName("odl");
+        ChoiceSchemaNode odl = (ChoiceSchemaNode) augmentedHolder.getDataChildByName("odl");
         assertNotNull(odl);
         Set<ChoiceCaseNode> cases = odl.getCases();
         assertEquals(4, cases.size());
@@ -361,7 +361,7 @@ public class AugmentTest {
         ContainerSchemaNode input = submit.getInput();
         QName inputQName = QName.create(NS_BAR, revision, "input");
         assertEquals(inputQName, input.getQName());
-        ChoiceNode arguments = (ChoiceNode) input.getDataChildByName("arguments");
+        ChoiceSchemaNode arguments = (ChoiceSchemaNode) input.getDataChildByName("arguments");
         QName argumentsQName = QName.create(NS_BAR, revision, "arguments");
         assertEquals(argumentsQName, arguments.getQName());
         assertFalse(arguments.isAugmenting());
index 3abb8508e7b337b933fbf1b9d121a789319c7131..fc6ed21b7949bf1140d7153934050887ebb820a7 100644 (file)
@@ -12,9 +12,6 @@ import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
-
-import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
-
 import java.io.File;
 import java.io.IOException;
 import java.net.URI;
@@ -31,7 +28,7 @@ import org.junit.Test;
 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
@@ -41,6 +38,7 @@ import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.MustDefinition;
 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
 import org.opendaylight.yangtools.yang.model.api.UnknownSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.UsesNode;
 import org.opendaylight.yangtools.yang.model.parser.api.YangContextParser;
@@ -161,12 +159,12 @@ public class GroupingTest {
         assertFalse(data_u.equals(data_g));
         assertEquals(data_g,  SchemaNodeUtils.getRootOriginalIfPossible(data_u));
 
-        ChoiceNode how_u = (ChoiceNode) destination.getDataChildByName("how");
+        ChoiceSchemaNode how_u = (ChoiceSchemaNode) destination.getDataChildByName("how");
         assertNotNull(how_u);
         TestUtils.checkIsAddedByUses(how_u, true);
         assertEquals(2, how_u.getCases().size());
 
-        ChoiceNode how_g = (ChoiceNode) grouping.getDataChildByName("how");
+        ChoiceSchemaNode how_g = (ChoiceSchemaNode) grouping.getDataChildByName("how");
         assertNotNull(how_g);
         TestUtils.checkIsAddedByUses(how_g, false);
         assertEquals(2, how_g.getCases().size());
@@ -268,7 +266,7 @@ public class GroupingTest {
         assertFalse(data_u.equals(data_g));
         assertEquals(data_g, SchemaNodeUtils.getRootOriginalIfPossible(data_u));
 
-        ChoiceNode how_u = (ChoiceNode) foo.getDataChildByName("how");
+        ChoiceSchemaNode how_u = (ChoiceSchemaNode) foo.getDataChildByName("how");
         assertNotNull(how_u);
         TestUtils.checkIsAddedByUses(how_u, true);
         assertFalse(how_u.isAugmenting());
@@ -281,7 +279,7 @@ public class GroupingTest {
         LeafSchemaNode intervalLeaf = (LeafSchemaNode) interval.getDataChildByName("interval");
         assertFalse(intervalLeaf.isAugmenting());
 
-        ChoiceNode how_g = (ChoiceNode) grouping.getDataChildByName("how");
+        ChoiceSchemaNode how_g = (ChoiceSchemaNode) grouping.getDataChildByName("how");
         assertNotNull(how_g);
         TestUtils.checkIsAddedByUses(how_g, false);
         assertFalse(how_u.equals(how_g));
@@ -571,7 +569,7 @@ public class GroupingTest {
                 .getDataChildByName("my-container"))
                 .getDataChildByName("my-leaf");
 
-        TypeDefinition impType = null;
+        TypeDefinition<?> impType = null;
         Set<TypeDefinition<?>> typeDefinitions = imp.getTypeDefinitions();
         for (TypeDefinition<?> typeDefinition : typeDefinitions) {
             if (typeDefinition.getQName().getLocalName().equals("imp-type")) {
index 588e7a21e40a7df2500f0ab97b2d8e9ebb3872ad..dbf74387ce5a9f4f75a82f1569a70c55d6909503 100644 (file)
@@ -27,7 +27,7 @@ import java.util.List;
 import java.util.Set;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
@@ -185,8 +185,8 @@ final class TestUtils {
             for (DataSchemaNode child : ((DataNodeContainer) node).getChildNodes()) {
                 checkIsAugmenting(child, expected);
             }
-        } else if (node instanceof ChoiceNode) {
-            for (ChoiceCaseNode caseNode : ((ChoiceNode) node).getCases()) {
+        } else if (node instanceof ChoiceSchemaNode) {
+            for (ChoiceCaseNode caseNode : ((ChoiceSchemaNode) node).getCases()) {
                 checkIsAugmenting(caseNode, expected);
             }
         }
@@ -207,8 +207,8 @@ final class TestUtils {
             for (DataSchemaNode child : ((DataNodeContainer) node).getChildNodes()) {
                 checkIsAddedByUses(child, expected);
             }
-        } else if (node instanceof ChoiceNode) {
-            for (ChoiceCaseNode caseNode : ((ChoiceNode) node).getCases()) {
+        } else if (node instanceof ChoiceSchemaNode) {
+            for (ChoiceCaseNode caseNode : ((ChoiceSchemaNode) node).getCases()) {
                 checkIsAddedByUses(caseNode, expected);
             }
         }
index d221e7c218b52c0a2b6e1c5aebf170b7ddbeed01..6c4e1bfc68e68b1a3d5e47bf11c2bd5f7c6ca240 100644 (file)
@@ -27,7 +27,7 @@ import java.util.Set;
 import org.junit.Before;
 import org.junit.Test;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
@@ -406,7 +406,7 @@ public class UsesAugmentTest {
         assertEquals(expectedPath, box.getPath());
         assertTrue(box.isAddedByUses());
         // * |-- |-- |-- |-- |-- choice address-family
-        ChoiceNode af = (ChoiceNode) endpoints.getDataChildByName("address-family");
+        ChoiceSchemaNode af = (ChoiceSchemaNode) endpoints.getDataChildByName("address-family");
         assertNotNull(af);
         expectedQName = QName.create(UG_NS, UG_REV, "address-family");
         assertEquals(expectedQName, af.getQName());
index 760bee4bb05bb2999a51b5f46f7a443252d8a750..826a0ba9596a34db8cf4849390a0afac06a59a19 100644 (file)
@@ -13,7 +13,6 @@ import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertNull;
 import static org.junit.Assert.assertTrue;
 import static org.junit.Assert.fail;
-
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
@@ -34,13 +33,12 @@ import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
-
 import org.junit.Before;
 import org.junit.Test;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ConstraintDefinition;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
@@ -635,7 +633,7 @@ public class YangParserTest {
     public void testChoice() {
         Module foo = TestUtils.findModule(modules, "foo");
         ContainerSchemaNode transfer = (ContainerSchemaNode) foo.getDataChildByName("transfer");
-        ChoiceNode how = (ChoiceNode) transfer.getDataChildByName("how");
+        ChoiceSchemaNode how = (ChoiceSchemaNode) transfer.getDataChildByName("how");
         Set<ChoiceCaseNode> cases = how.getCases();
         assertEquals(5, cases.size());
         ChoiceCaseNode input = null;
index f997164fe06fcd7e9dc3d656d0c343af78204604..cf5ab060bf31d3cc37655876c0e8a3ab5a55ecc2 100644 (file)
@@ -11,7 +11,6 @@ import static org.junit.Assert.assertEquals;
 import static org.junit.Assert.assertFalse;
 import static org.junit.Assert.assertNotNull;
 import static org.junit.Assert.assertTrue;
-
 import com.google.common.collect.Lists;
 import java.io.File;
 import java.io.FileInputStream;
@@ -30,7 +29,7 @@ import java.util.Set;
 import org.junit.Test;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.Deviation;
@@ -135,11 +134,11 @@ public class YangParserWithContextTest {
         assertFalse(data_g.isAddedByUses());
         assertFalse(data_u.equals(data_g));
 
-        ChoiceNode how_u = (ChoiceNode) destination.getDataChildByName("how");
+        ChoiceSchemaNode how_u = (ChoiceSchemaNode) destination.getDataChildByName("how");
         assertNotNull(how_u);
         assertTrue(how_u.isAddedByUses());
 
-        ChoiceNode how_g = (ChoiceNode) grouping.getDataChildByName("how");
+        ChoiceSchemaNode how_g = (ChoiceSchemaNode) grouping.getDataChildByName("how");
         assertNotNull(how_g);
         assertFalse(how_g.isAddedByUses());
         assertFalse(how_u.equals(how_g));
index 83c0a8f850c6ad2d37cf056a72635608b1e92fc3..0a94e342cfb9d027a37abbd5bd2fb3a9b5b7da9a 100644 (file)
@@ -30,13 +30,13 @@ import com.google.common.io.Files;
 import com.google.common.util.concurrent.CheckedFuture;
 import com.google.common.util.concurrent.FutureCallback;
 import com.google.common.util.concurrent.Futures;
+import java.io.ByteArrayInputStream;
 import java.io.File;
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.Arrays;
 import java.util.List;
 import java.util.concurrent.ExecutionException;
-import org.apache.commons.io.IOUtils;
 import org.junit.Test;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
@@ -276,7 +276,7 @@ public class SharedSchemaRepositoryTest {
 
                     @Override
                     public InputStream openStream() throws IOException {
-                        return IOUtils.toInputStream("running");
+                        return new ByteArrayInputStream("running".getBytes(Charsets.UTF_8));
                     }
                 });
             }
index b8d270054856124690b8aa5517b4abdc9a26352f..cc8950d244bd653aa46dec406916a67c4b8ad9b8 100644 (file)
@@ -7,39 +7,39 @@
  */
 package org.opendaylight.yangtools.yang.parser.util;
 
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.text.ParseException;
+import java.util.Collections;
 import org.junit.Test;
 import org.mockito.Mock;
 import org.mockito.Mockito;
 import org.mockito.MockitoAnnotations;
 import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
+import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.GroupingDefinition;
 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
+import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.NotificationDefinition;
+import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.SchemaPath;
-import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
+import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
 import org.opendaylight.yangtools.yang.model.util.Int32;
 import org.opendaylight.yangtools.yang.model.util.RevisionAwareXPathImpl;
 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
 
-import java.io.File;
-import java.io.IOException;
-import java.net.URI;
-import java.net.URISyntaxException;
-import java.text.ParseException;
-import java.util.Collections;
-
-import static org.junit.Assert.*;
-
 public class SchemaContextUtilTest {
     @Mock
     private SchemaContext mockSchemaContext;
@@ -147,7 +147,7 @@ public class SchemaContextUtilTest {
         assertNotNull(foundNode);
         assertEquals(testNode, foundNode);
 
-        testNode = ((ChoiceNode) myModule.getDataChildByName("my-choice")).getCaseNodeByName("one").getDataChildByName(
+        testNode = ((ChoiceSchemaNode) myModule.getDataChildByName("my-choice")).getCaseNodeByName("one").getDataChildByName(
                 "my-choice-leaf-one");
 
         path = SchemaPath.create(true, QName.create(myModule.getQNameModule(), "my-choice"),
@@ -248,7 +248,7 @@ public class SchemaContextUtilTest {
         assertNull(testNode);
         assertNull(foundNode);
 
-        testNode = ((ChoiceNode) myModule.getDataChildByName("my-choice")).getCaseNodeByName("one").getDataChildByName(
+        testNode = ((ChoiceSchemaNode) myModule.getDataChildByName("my-choice")).getCaseNodeByName("one").getDataChildByName(
                 "no-choice-leaf");
 
         path = SchemaPath.create(true, QName.create(myModule.getQNameModule(), "my-choice"),
@@ -706,7 +706,7 @@ public class SchemaContextUtilTest {
         assertEquals(testNode, foundNode);
 
         // find grouping in case
-        dataContainer = (DataNodeContainer) ((ChoiceNode) myModule.getDataChildByName("my-choice")).getCaseNodeByName(
+        dataContainer = (DataNodeContainer) ((ChoiceSchemaNode) myModule.getDataChildByName("my-choice")).getCaseNodeByName(
                 "one").getDataChildByName("my-container-in-case");
         testNode = getGroupingByName(dataContainer, "my-grouping-in-case");
 
@@ -830,7 +830,7 @@ public class SchemaContextUtilTest {
         assertNull(foundNode);
 
         // find grouping in case
-        dataContainer = (DataNodeContainer) ((ChoiceNode) myModule.getDataChildByName("my-choice")).getCaseNodeByName(
+        dataContainer = (DataNodeContainer) ((ChoiceSchemaNode) myModule.getDataChildByName("my-choice")).getCaseNodeByName(
                 "one").getDataChildByName("my-container-in-case");
         testNode = getGroupingByName(dataContainer, "my-grouping-in-case2");
 
@@ -845,7 +845,7 @@ public class SchemaContextUtilTest {
 
     }
 
-    private static GroupingDefinition getGroupingByName(DataNodeContainer dataNodeContainer, String name) {
+    private static GroupingDefinition getGroupingByName(final DataNodeContainer dataNodeContainer, final String name) {
         for (GroupingDefinition grouping : dataNodeContainer.getGroupings()) {
             if (grouping.getQName().getLocalName().equals(name)) {
                 return grouping;
@@ -854,7 +854,7 @@ public class SchemaContextUtilTest {
         return null;
     }
 
-    private static RpcDefinition getRpcByName(Module module, String name) {
+    private static RpcDefinition getRpcByName(final Module module, final String name) {
         for (RpcDefinition rpc : module.getRpcs()) {
             if (rpc.getQName().getLocalName().equals(name)) {
                 return rpc;
@@ -863,7 +863,7 @@ public class SchemaContextUtilTest {
         return null;
     }
 
-    private static NotificationDefinition getNotificationByName(Module module, String name) {
+    private static NotificationDefinition getNotificationByName(final Module module, final String name) {
         for (NotificationDefinition notification : module.getNotifications()) {
             if (notification.getQName().getLocalName().equals(name)) {
                 return notification;
@@ -885,7 +885,7 @@ public class SchemaContextUtilTest {
         Module myModule = context.findModuleByNamespaceAndRevision(new URI("uri:my-module"),
                 QName.parseRevision("2014-10-07"));
 
-        ChoiceNode choice = (ChoiceNode)getRpcByName(myModule,"my-name").getInput().getDataChildByName("my-choice");
+        ChoiceSchemaNode choice = (ChoiceSchemaNode)getRpcByName(myModule,"my-name").getInput().getDataChildByName("my-choice");
         SchemaNode testNode = choice.getCaseNodeByName("case-two").getDataChildByName("two");
 
         SchemaPath path = SchemaPath.create(true, QName.create(myModule.getQNameModule(), "my-name"),